-
Notifications
You must be signed in to change notification settings - Fork 183
/
Copy pathWarehouse.java
372 lines (321 loc) · 12.2 KB
/
Warehouse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
* Copyright (C) 2020-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MekHQ.
*
* MekHQ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MekHQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*/
package mekhq.campaign;
import megamek.common.annotations.Nullable;
import megamek.logging.MMLogger; // FIXME: LOGGER
import mekhq.MekHQ;
import mekhq.campaign.event.PartChangedEvent;
import mekhq.campaign.event.PartNewEvent;
import mekhq.campaign.event.PartRemovedEvent;
import mekhq.campaign.parts.AmmoStorage;
import mekhq.campaign.parts.Armor;
import mekhq.campaign.parts.Part;
import mekhq.campaign.parts.Refit;
import mekhq.utilities.MHQXMLUtility;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Stores parts for a Campaign.
*/
public class Warehouse {
private static final MMLogger logger = MMLogger.create(Warehouse.class); // FIXME: LOGGER
private final TreeMap<Integer, Part> parts = new TreeMap<>();
/**
* Adds a part to the warehouse.
* @param part The part to add to the warehouse.
* @return The part added to the warehouse.
*/
public Part addPart(Part part) {
return addPart(part, false);
}
/**
* Adds a part to the warehouse, optionally merging it with
* any existing spare part.
* @param part The part to add to the warehouse.
* @param mergeWithExisting If true and the part is spare, it may
* be merged with an existing spare part.
* @return The part itself or the spare part it was merged with.
*/
public Part addPart(Part part, boolean mergeWithExisting) {
Objects.requireNonNull(part);
// Attempting to log here will cause NPEs when loading saves. Strange.
if (mergeWithExisting && part.isSpare()) {
Part mergedPart = mergePartWithExisting(part);
// CAW: intentional reference equality
if (mergedPart != part) {
// We've merged parts, so let interested parties know we've
// updated the merged part.
MekHQ.triggerEvent(new PartChangedEvent(mergedPart));
// Check if the part being added exists, and if so
// remove it from the warehouse
if (part.getId() > 0) {
removePart(part);
}
return mergedPart;
}
// ... we did not merge parts, so fall through to the
// normal addPart logic.
}
// is this a new part? if so set its next ID
if (part.getId() <= 0) {
part.setId(parts.isEmpty() ? 1 : (parts.lastKey() + 1));
}
// Is this a part we've never tracked before?
boolean isNewPart = !parts.containsKey(part.getId());
parts.put(part.getId(), part);
if (isNewPart) {
MekHQ.triggerEvent(new PartNewEvent(part));
} else {
// Part was removed from a unit, or something similar
MekHQ.triggerEvent(new PartChangedEvent(part));
}
return part;
}
/**
* Gets a collection of parts within the warehouse.
*/
public Collection<Part> getParts() {
return parts.values();
}
/**
* Gets a part from the warehouse by its ID.
* @param id The unique ID of the part.
* @return The part with the given ID, or null if no matching part exists.
*/
public @Nullable Part getPart(int id) {
return parts.get(id);
}
/**
* Executes a function for each part in the warehouse.
* @param consumer A function to apply to each part.
*/
public void forEachPart(Consumer<Part> consumer) {
for (Part part : parts.values()) {
consumer.accept(part);
}
}
/**
* Removes a part from the warehouse.
* @param part The part to remove.
* @return A value indicating whether or not the part was removed.
*/
public boolean removePart(Part part) {
Objects.requireNonNull(part);
boolean didRemove = (parts.remove(part.getId()) != null);
if (didRemove) {
MekHQ.triggerEvent(new PartRemovedEvent(part));
}
// Clear the part's ID
part.setId(-1);
if (didRemove && !part.getChildParts().isEmpty()) {
// Remove child parts as well
List<Part> childParts = new ArrayList<>(part.getChildParts());
for (Part childPart : childParts) {
part.removeChildPart(childPart);
removePart(childPart);
}
}
return didRemove;
}
/**
* Removes one or more parts from the warehouse.
* @param part The part to remove.
* @param quantity The amount of the part to remove.
* @return A value indicating whether or not the part was removed.
*/
public boolean removePart(Part part, int quantity) {
Objects.requireNonNull(part);
// Only allow removing spare parts.
if (!part.isSpare()) {
return false;
}
if (part instanceof AmmoStorage) {
return removeAmmo((AmmoStorage) part, quantity);
} else if (part instanceof Armor) {
return removeArmor((Armor) part, quantity);
}
if (quantity >= part.getQuantity()) {
removePart(part);
} else {
while (quantity > 0) {
part.decrementQuantity();
quantity--;
}
MekHQ.triggerEvent(new PartChangedEvent(part));
}
return true;
}
/**
* Attempts to merge a given part with an existing spare part in stock. The merge
* is only possible if a compatible spare part is found, and both parts have the
* same "brand new" state.
*
* <p>The merge process follows these steps:</p>
* <ul>
* <li>If the part has no associated unit, no parent part, and is not reserved for replacement,
* the method searches for an existing spare part to merge with.</li>
* <li>A merge can only occur if the spare part exists and the {@code isBrandNew}
* property matches for both the part and the spare.</li>
* <li>Specific handling is applied based on the type of the part:
* <ul>
* <li>If the part is of type {@code Armor}, the quantities are added together.</li>
* <li>If the part is of type {@code AmmoStorage}, the shot counts are updated.</li>
* <li>For other part types, the quantities are incremented.</li>
* </ul>
* </li>
* </ul>
*
* @param part The part to attempt to merge with an existing spare part. Cannot be {@code null}.
* @return The original part if no merge occurs, or the existing spare part if the parts are merged.
* @throws NullPointerException If the {@code part} parameter is {@code null}.
*/
private Part mergePartWithExisting(Part part) {
Objects.requireNonNull(part);
// Check if the part has no unit, no parent part, and is not reserved for replacement
if ((null == part.getUnit()) && !part.hasParentPart() && !part.isReservedForReplacement()) {
Part spare = checkForExistingSparePart(part);
// Ensure a matching spare exists and both parts share the same isBrandNew state
if (spare != null && part.isBrandNew() == spare.isBrandNew()) {
// Handle specific part types
if (part instanceof Armor && spare instanceof Armor) {
((Armor) spare).setAmount(((Armor) spare).getAmount() + ((Armor) part).getAmount());
return spare;
} else if (part instanceof AmmoStorage && spare instanceof AmmoStorage) {
((AmmoStorage) spare).changeShots(((AmmoStorage) part).getShots());
return spare;
} else {
// Handle generic parts by incrementing the quantity
spare.changeQuantity(part.getQuantity());
return spare;
}
}
}
return part;
}
/**
* Checks for an existing spare part.
* @param part The part to search for in the warehouse.
* @return The matching spare part or null if none were found.
*/
public @Nullable Part checkForExistingSparePart(Part part) {
Objects.requireNonNull(part);
return findSparePart(spare ->
(spare.getId() != part.getId())
&& part.isSamePartTypeAndStatus(spare));
}
/**
* Gets a list of spare parts in the warehouse.
* @return A list of spare parts in the warehouse.
*/
public List<Part> getSpareParts() {
return getParts().stream()
.filter(Part::isSpare)
.collect(Collectors.toList());
}
/**
* Executes a method for each spare part in the warehouse.
*
* @param consumer The method to apply to each spare part
* in the warehouse.
*/
public void forEachSparePart(Consumer<Part> consumer) {
for (Part part : getParts()) {
if (part.isSpare()) {
consumer.accept(part);
}
}
}
/**
* Finds the first spare part matching a predicate.
*
* @param predicate The predicate to use when searching
* for a suitable spare part.
* @return A matching spare {@link Part} or {@code null}
* if no suitable match was found.
*/
public @Nullable Part findSparePart(Predicate<Part> predicate) {
for (Part part : getParts()) {
if (part.isSpare() && predicate.test(part)) {
return part;
}
}
return null;
}
/**
* Streams the spare parts in the campaign.
*
* @return A stream of spare parts in the campaign.
*/
public Stream<Part> streamSpareParts() {
return getParts().stream().filter(Part::isSpare);
}
/**
* Adds ammo to the warehouse.
* @param ammo Ammo in the warehouse.
* @param shots The amount of ammo to add to the warehouse.
*/
public void addAmmo(AmmoStorage ammo, int shots) {
Objects.requireNonNull(ammo);
ammo.changeShots(shots);
MekHQ.triggerEvent(new PartChangedEvent(ammo));
}
/**
* Removes ammo from the warehouse.
* @param ammo Ammo in the warehouse.
* @param shots The amount of ammo to remove from the warehouse.
*/
public boolean removeAmmo(AmmoStorage ammo, int shots) {
Objects.requireNonNull(ammo);
if (shots >= ammo.getShots()) {
removePart(ammo);
} else {
ammo.changeShots(-shots);
MekHQ.triggerEvent(new PartChangedEvent(ammo));
}
return true;
}
public boolean removeArmor(Armor armor, int points) {
Objects.requireNonNull(armor);
if (points >= armor.getAmount()) {
removePart(armor);
} else {
armor.changeAmountAvailable(-points);
MekHQ.triggerEvent(new PartChangedEvent(armor));
}
return true;
}
public void writeToXML(final PrintWriter pw, final int indent, final String tag) {
MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent, tag);
forEachPart(part -> part.writeToXML(pw, indent + 1));
MHQXMLUtility.writeSimpleXMLCloseTag(pw, indent, tag);
}
}