• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

CyclopsMC / IntegratedCrafting / #479011785

10 Feb 2025 03:30PM UTC coverage: 25.626% (+0.3%) from 25.34%
#479011785

push

github

rubensworks
Bump mod version

737 of 2876 relevant lines covered (25.63%)

0.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.1
/src/main/java/org/cyclops/integratedcrafting/core/CraftingHelpers.java
1
package org.cyclops.integratedcrafting.core;
2

3
import com.google.common.collect.Lists;
4
import com.google.common.collect.Maps;
5
import com.google.common.collect.Sets;
6
import net.minecraft.core.Direction;
7
import net.minecraft.world.level.block.entity.BlockEntity;
8
import net.minecraftforge.common.capabilities.ICapabilityProvider;
9
import net.minecraftforge.common.util.LazyOptional;
10
import org.apache.commons.lang3.tuple.Pair;
11
import org.apache.logging.log4j.Level;
12
import org.cyclops.commoncapabilities.api.capability.recipehandler.IPrototypedIngredientAlternatives;
13
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
14
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
15
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
16
import org.cyclops.commoncapabilities.api.ingredient.IPrototypedIngredient;
17
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
18
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
19
import org.cyclops.commoncapabilities.api.ingredient.PrototypedIngredient;
20
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
21
import org.cyclops.commoncapabilities.api.ingredient.storage.IngredientComponentStorageEmpty;
22
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
23
import org.cyclops.cyclopscore.ingredient.collection.IIngredientCollectionMutable;
24
import org.cyclops.cyclopscore.ingredient.collection.IngredientArrayList;
25
import org.cyclops.cyclopscore.ingredient.collection.IngredientCollectionPrototypeMap;
26
import org.cyclops.cyclopscore.ingredient.collection.IngredientCollectionQuantitativeGrouper;
27
import org.cyclops.cyclopscore.ingredient.collection.IngredientHashSet;
28
import org.cyclops.integratedcrafting.Capabilities;
29
import org.cyclops.integratedcrafting.IntegratedCrafting;
30
import org.cyclops.integratedcrafting.api.crafting.CraftingJob;
31
import org.cyclops.integratedcrafting.api.crafting.CraftingJobDependencyGraph;
32
import org.cyclops.integratedcrafting.api.crafting.FailedCraftingRecipeException;
33
import org.cyclops.integratedcrafting.api.crafting.RecursiveCraftingRecipeException;
34
import org.cyclops.integratedcrafting.api.crafting.UnavailableCraftingInterfacesException;
35
import org.cyclops.integratedcrafting.api.crafting.UnknownCraftingRecipeException;
36
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
37
import org.cyclops.integratedcrafting.api.recipe.IRecipeIndex;
38
import org.cyclops.integratedcrafting.capability.network.CraftingNetworkConfig;
39
import org.cyclops.integrateddynamics.IntegratedDynamics;
40
import org.cyclops.integrateddynamics.api.PartStateException;
41
import org.cyclops.integrateddynamics.api.ingredient.capability.IPositionedAddonsNetworkIngredientsHandler;
42
import org.cyclops.integrateddynamics.api.network.INetwork;
43
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
44
import org.cyclops.integrateddynamics.api.part.PartPos;
45
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
46
import org.cyclops.integrateddynamics.core.network.IngredientChannelAdapter;
47
import org.cyclops.integrateddynamics.core.network.IngredientChannelIndexed;
48

49
import javax.annotation.Nullable;
50
import java.util.Collection;
51
import java.util.Collections;
52
import java.util.Iterator;
53
import java.util.List;
54
import java.util.ListIterator;
55
import java.util.Map;
56
import java.util.Set;
57
import java.util.UUID;
58
import java.util.function.Function;
59
import java.util.stream.Collectors;
60
import java.util.stream.IntStream;
61

62
/**
63
 * Helpers related to handling crafting jobs.
64
 * @author rubensworks
65
 */
66
public class CraftingHelpers {
×
67

68
    /**
69
     * Get the network at the given position,
70
     * or throw a PartStateException if it is null.
71
     * @param pos A position.
72
     * @return A network.
73
     * @throws PartStateException If the network could not be found.
74
     */
75
    public static INetwork getNetworkChecked(PartPos pos) throws PartStateException {
76
        INetwork network = NetworkHelpers.getNetwork(pos.getPos().getLevel(true), pos.getPos().getBlockPos(), pos.getSide()).orElse(null);
×
77
        if (network == null) {
×
78
            IntegratedDynamics.clog(Level.ERROR, "Could not get the network for transfer as no network was found.");
×
79
            throw new PartStateException(pos.getPos(), pos.getSide());
×
80
        }
81
        return network;
×
82
    }
83

84
    /**
85
     * Get the crafting network in the given network.
86
     * @param network A network.
87
     * @return The crafting network.
88
     */
89
    public static LazyOptional<ICraftingNetwork> getCraftingNetwork(@Nullable INetwork network) {
90
        if (network != null) {
×
91
            return network.getCapability(CraftingNetworkConfig.CAPABILITY);
×
92
        }
93
        return null;
×
94
    }
95

96
    /**
97
     * Get the crafting network in the given network.
98
     * @param network A network.
99
     * @return The crafting network.
100
     */
101
    public static ICraftingNetwork getCraftingNetworkChecked(@Nullable INetwork network) {
102
        return getCraftingNetwork(network)
×
103
                .orElseThrow(() -> new IllegalStateException("Could not find a crafting network"));
×
104
    }
105

106
    /**
107
     * Get the storage network of the given type in the given network.
108
     * @param network A network.
109
     * @param ingredientComponent The ingredient component type of the network.
110
     * @param <T> The instance type.
111
     * @param <M> The matching condition parameter.
112
     * @return The storage network.
113
     */
114
    public static <T, M> LazyOptional<IPositionedAddonsNetworkIngredients<T, M>> getIngredientsNetwork(INetwork network,
115
                                                                                                       IngredientComponent<T, M> ingredientComponent) {
116
        IPositionedAddonsNetworkIngredientsHandler<T, M> ingredientsHandler = ingredientComponent.getCapability(Capabilities.POSITIONED_ADDONS_NETWORK_INGREDIENTS_HANDLER).orElse(null);
×
117
        if (ingredientsHandler != null) {
×
118
            return ingredientsHandler.getStorage(network);
×
119
        }
120
        return LazyOptional.empty();
×
121
    }
122

123
    /**
124
     * Get the storage network of the given type in the given network.
125
     * @param network A network.
126
     * @param ingredientComponent The ingredient component type of the network.
127
     * @param <T> The instance type.
128
     * @param <M> The matching condition parameter.
129
     * @return The storage network.
130
     */
131
    public static <T, M> IPositionedAddonsNetworkIngredients<T, M> getIngredientsNetworkChecked(INetwork network,
132
                                                                                                IngredientComponent<T, M> ingredientComponent) {
133
        return getIngredientsNetwork(network, ingredientComponent)
×
134
                .orElseThrow(() -> new IllegalStateException("Could not find an ingredients network"));
×
135
    }
136

137
    /**
138
     * Get the storage of the given ingredient component type from the network.
139
     * @param network The network.
140
     * @param channel A network channel.
141
     * @param ingredientComponent The ingredient component type of the network.
142
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
143
     * @param <T> The instance type.
144
     * @param <M> The matching condition parameter.
145
     * @return The storage.
146
     */
147
    public static <T, M> IIngredientComponentStorage<T, M> getNetworkStorage(INetwork network, int channel,
148
                                                                             IngredientComponent<T, M> ingredientComponent,
149
                                                                             boolean scheduleObservation) {
150
        IPositionedAddonsNetworkIngredients<T, M> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
151
        if (ingredientsNetwork != null) {
×
152
            if (scheduleObservation) {
×
153
                ingredientsNetwork.scheduleObservation();
×
154
            }
155
            return ingredientsNetwork.getChannel(channel);
×
156
        }
157
        return new IngredientComponentStorageEmpty<>(ingredientComponent);
×
158
    }
159

160
    /**
161
     * If the network is guaranteed to have uncommitted changes (such as the one in #48),
162
     * forcefully run observers synchronously, so that we can calculate the job in a consistent network state.
163
     * @param network The network.
164
     * @param channel A network channel.
165
     */
166
    public static void beforeCalculateCraftingJobs(INetwork network, int channel) {
167
        for (IngredientComponent<?, ?> ingredientComponent : IngredientComponent.REGISTRY.getValues()) {
×
168
            IPositionedAddonsNetworkIngredients<?, ?> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
169
            if (ingredientsNetwork != null && (ingredientsNetwork.isObservationForcedPending(channel))) {
×
170
                ingredientsNetwork.runObserverSync();
×
171
            }
172
        }
×
173
    }
×
174

175
    /**
176
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
177
     * @param network The target network.
178
     * @param channel The target channel.
179
     * @param ingredientComponent The ingredient component type of the instance.
180
     * @param instance The instance to craft.
181
     * @param matchCondition The match condition of the instance.
182
     * @param craftMissing If the missing required ingredients should also be crafted.
183
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
184
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
185
     * @param collectMissingRecipes If the missing recipes should be collected inside
186
     *                              {@link UnknownCraftingRecipeException}.
187
     *                              This may slow down calculation for deeply nested recipe graphs.
188
     * @param <T> The instance type.
189
     * @param <M> The matching condition parameter.
190
     * @return The crafting job for the given instance.
191
     * @throws UnknownCraftingRecipeException If the recipe for a (sub)ingredient is unavailable.
192
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
193
     */
194
    public static <T, M> CraftingJob calculateCraftingJobs(INetwork network, int channel,
195
                                                           IngredientComponent<T, M> ingredientComponent,
196
                                                           T instance, M matchCondition, boolean craftMissing,
197
                                                           IIdentifierGenerator identifierGenerator,
198
                                                           CraftingJobDependencyGraph craftingJobsGraph,
199
                                                           boolean collectMissingRecipes)
200
            throws UnknownCraftingRecipeException, RecursiveCraftingRecipeException {
201
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
202
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
203
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
204
        beforeCalculateCraftingJobs(network, channel);
×
205

206
        CraftingJob craftingJob = calculateCraftingJobs(recipeIndex, channel, storageGetter, ingredientComponent, instance, matchCondition,
×
207
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
208
                collectMissingRecipes);
209
        craftingJobsGraph.addCraftingJobId(craftingJob);
×
210
        return craftingJob;
×
211
    }
212

213
    /**
214
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
215
     * @param network The target network.
216
     * @param channel The target channel.
217
     * @param recipe The recipe to calculate a job for.
218
     * @param amount The amount of times the recipe should be crafted.
219
     * @param craftMissing If the missing required ingredients should also be crafted.
220
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
221
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
222
     * @param collectMissingRecipes If the missing recipes should be collected inside
223
     *                              {@link FailedCraftingRecipeException}.
224
     *                              This may slow down calculation for deeply nested recipe graphs.
225
     * @return The crafting job for the given instance.
226
     * @throws FailedCraftingRecipeException If the recipe could not be crafted due to missing sub-dependencies.
227
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
228
     */
229
    public static CraftingJob calculateCraftingJobs(INetwork network, int channel,
230
                                                    IRecipeDefinition recipe, int amount, boolean craftMissing,
231
                                                    IIdentifierGenerator identifierGenerator,
232
                                                    CraftingJobDependencyGraph craftingJobsGraph,
233
                                                    boolean collectMissingRecipes)
234
            throws FailedCraftingRecipeException, RecursiveCraftingRecipeException {
235
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
236
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
237
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
238
        beforeCalculateCraftingJobs(network, channel);
×
239

240
        PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel, storageGetter, recipe, amount,
×
241
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
242
                collectMissingRecipes);
243
        if (result.getCraftingJob() == null) {
×
244
            throw new FailedCraftingRecipeException(recipe, amount, result.getMissingDependencies(),
×
245
                    compressMixedIngredients(new MixedIngredients(result.getIngredientsStorage())), result.getPartialCraftingJobs());
×
246
        } else {
247
            craftingJobsGraph.addCraftingJobId(result.getCraftingJob());
×
248
            return result.getCraftingJob();
×
249
        }
250
    }
251

252
    /**
253
     * @return An identifier generator for crafting jobs.
254
     */
255
    public static IIdentifierGenerator getGlobalCraftingJobIdentifier() {
256
        return () -> IntegratedCrafting.globalCounters.getNext("craftingJob");
×
257
    }
258

259
    /**
260
     * Calculate the effective quantity for the given instance in the output of the given recipe.
261
     * @param recipe A recipe.
262
     * @param ingredientComponent The ingredient component.
263
     * @param instance An instance.
264
     * @param matchCondition A match condition.
265
     * @param <T> The instance type.
266
     * @param <M> The matching condition parameter.
267
     * @return The effective quantity.
268
     */
269
    public static <T, M> long getOutputQuantityForRecipe(IRecipeDefinition recipe,
270
                                                         IngredientComponent<T, M> ingredientComponent,
271
                                                         T instance, M matchCondition) {
272
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
273
        return recipe.getOutput().getInstances(ingredientComponent)
1✔
274
                .stream()
1✔
275
                .filter(i -> matcher.matches(i, instance, matchCondition))
1✔
276
                .mapToLong(matcher::getQuantity)
1✔
277
                .sum();
1✔
278
    }
279

280
    /**
281
     * Calculate a crafting job for the given instance.
282
     *
283
     * This method is merely an easily-stubbable implementation for the method above,
284
     * to simplify unit testing.
285
     *
286
     * @param recipeIndex The recipe index.
287
     * @param channel The target channel that will be stored in created crafting jobs.
288
     * @param storageGetter A callback function to get a storage for the given ingredient component.
289
     * @param ingredientComponent The ingredient component type of the instance.
290
     * @param instance The instance to craft.
291
     * @param matchCondition The match condition of the instance.
292
     * @param craftMissing If the missing required ingredients should also be crafted.
293
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
294
     *                                  This is to make sure that instances can not be extracted multiple times
295
     *                                  when simulating.
296
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
297
     * @param identifierGenerator An ID generator for crafting jobs.
298
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
299
     * @param parentDependencies A set of parent recipe dependencies that are pending.
300
     *                           This is used to check for infinite recursion in recipes.
301
     * @param collectMissingRecipes If the missing recipes should be collected inside
302
     *                              {@link UnknownCraftingRecipeException}.
303
     *                              This may slow down calculation for deeply nested recipe graphs.
304
     * @param <T> The instance type.
305
     * @param <M> The matching condition parameter.
306
     * @return The crafting job for the given instance.
307
     * @throws UnknownCraftingRecipeException If the recipe for a (sub)ingredient is unavailable.
308
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
309
     */
310
    protected static <T, M> CraftingJob calculateCraftingJobs(IRecipeIndex recipeIndex, int channel,
311
                                                              Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
312
                                                              IngredientComponent<T, M> ingredientComponent,
313
                                                              T instance, M matchCondition, boolean craftMissing,
314
                                                              Map<IngredientComponent<?, ?>,
315
                                                                      IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
316
                                                              Map<IngredientComponent<?, ?>,
317
                                                                      IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
318
                                                              IIdentifierGenerator identifierGenerator,
319
                                                              CraftingJobDependencyGraph craftingJobsGraph,
320
                                                              Set<IPrototypedIngredient> parentDependencies,
321
                                                              boolean collectMissingRecipes)
322
            throws UnknownCraftingRecipeException, RecursiveCraftingRecipeException {
323
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
324
        // This matching condition makes it so that the recipe output does not have to match with the requested input by quantity.
325
        M quantifierlessCondition = matcher.withoutCondition(matchCondition,
1✔
326
                ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
327
        long instanceQuantity = matcher.getQuantity(instance);
1✔
328

329
        // Loop over all available recipes, and return the first valid one.
330
        Iterator<IRecipeDefinition> recipes = recipeIndex.getRecipes(ingredientComponent, instance, quantifierlessCondition);
1✔
331
        List<UnknownCraftingRecipeException> firstMissingDependencies = Lists.newArrayList();
1✔
332
        Map<IngredientComponent<?, ?>, List<?>> firstIngredientsStorage = Collections.emptyMap();
1✔
333
        List<CraftingJob> firstPartialCraftingJobs = Lists.newArrayList();
1✔
334
        while (recipes.hasNext()) {
1✔
335
            IRecipeDefinition recipe = recipes.next();
1✔
336

337
            // Calculate the quantity for the given instance that the recipe outputs
338
            long recipeOutputQuantity = getOutputQuantityForRecipe(recipe, ingredientComponent, instance, quantifierlessCondition);
1✔
339
            // Based on the quantity of the recipe output, calculate the amount of required recipe jobs.
340
            int amount = (int) Math.ceil(((float) instanceQuantity) / (float) recipeOutputQuantity);
1✔
341

342
            // Calculate jobs for the given recipe
343
            PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel,
1✔
344
                    storageGetter, recipe, amount, craftMissing,
345
                    simulatedExtractionMemory, extractionMemoryReusable, identifierGenerator, craftingJobsGraph, parentDependencies,
346
                    collectMissingRecipes && firstMissingDependencies.isEmpty());
1✔
347
            if (result.getCraftingJob() == null) {
1✔
348
                firstMissingDependencies = result.getMissingDependencies();
1✔
349
                firstIngredientsStorage = result.getIngredientsStorage();
1✔
350
                if (result.getPartialCraftingJobs() != null) {
1✔
351
                    firstPartialCraftingJobs = result.getPartialCraftingJobs();
1✔
352
                }
353
            } else {
354
                return result.getCraftingJob();
1✔
355
            }
356
        }
1✔
357

358
        // No valid recipes were available, so we error or collect the missing instance.
359
        throw new UnknownCraftingRecipeException(new PrototypedIngredient<>(ingredientComponent, instance, matchCondition),
1✔
360
                matcher.getQuantity(instance), firstMissingDependencies, compressMixedIngredients(new MixedIngredients(firstIngredientsStorage)),
1✔
361
                firstPartialCraftingJobs);
362
    }
363

364
    /**
365
     * Calculate a crafting job for the given recipe.
366
     *
367
     * This method is merely an easily-stubbable implementation for the method above,
368
     * to simplify unit testing.
369
     *
370
     * @param recipeIndex The recipe index.
371
     * @param channel The target channel that will be stored in created crafting jobs.
372
     * @param storageGetter A callback function to get a storage for the given ingredient component.
373
     * @param recipe The recipe to calculate a job for.
374
     * @param amount The amount of times the recipe should be crafted.
375
     * @param craftMissing If the missing required ingredients should also be crafted.
376
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
377
     *                                  This is to make sure that instances can not be extracted multiple times
378
     *                                  when simulating.
379
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
380
     * @param identifierGenerator An ID generator for crafting jobs.
381
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
382
     * @param parentDependencies A set of parent recipe dependencies that are pending.
383
     *                           This is used to check for infinite recursion in recipes.
384
     * @param collectMissingRecipes If the missing recipes should be collected inside
385
     *                              {@link UnknownCraftingRecipeException}.
386
     *                              This may slow down calculation for deeply nested recipe graphs.
387
     * @return The crafting job for the given instance.
388
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
389
     */
390
    protected static PartialCraftingJobCalculation calculateCraftingJobs(
391
            IRecipeIndex recipeIndex, int channel,
392
            Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
393
            IRecipeDefinition recipe, int amount, boolean craftMissing,
394
            Map<IngredientComponent<?, ?>,
395
                    IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
396
            Map<IngredientComponent<?, ?>,
397
                    IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
398
            IIdentifierGenerator identifierGenerator,
399
            CraftingJobDependencyGraph craftingJobsGraph,
400
            Set<IPrototypedIngredient> parentDependencies,
401
            boolean collectMissingRecipes)
402
            throws RecursiveCraftingRecipeException {
403
        List<UnknownCraftingRecipeException> missingDependencies = Lists.newArrayList();
1✔
404
        List<CraftingJob> partialCraftingJobs = Lists.newArrayList();
1✔
405

406
        // Check if all requirements are met for this recipe, if so return directly (don't schedule yet)
407
        Pair<Map<IngredientComponent<?, ?>, List<?>>, Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>>> simulation =
1✔
408
                getRecipeInputs(storageGetter, recipe, true, simulatedExtractionMemory, extractionMemoryReusable,
1✔
409
                        true, amount);
410
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> missingIngredients = simulation.getRight();
1✔
411
        if (!craftMissing && !missingIngredients.isEmpty()) {
1✔
412
            if (collectMissingRecipes) {
1✔
413
                // Collect missing ingredients as missing recipes when we don't want to craft sub-components,
414
                // but they are missing.
415
                for (Map.Entry<IngredientComponent<?, ?>, MissingIngredients<?, ?>> entry : missingIngredients.entrySet()) {
1✔
416
                    for (MissingIngredients.Element<?, ?> element : entry.getValue().getElements()) {
1✔
417
                        MissingIngredients.PrototypedWithRequested<?, ?> alternative = element.getAlternatives().get(0);
1✔
418

419
                        // Calculate the instance that was available in storage
420
                        IngredientComponent<?, ?> component = alternative.getRequestedPrototype().getComponent();
1✔
421
                        IIngredientMatcher matcher = component.getMatcher();
1✔
422
                        long storedQuantity = matcher.getQuantity(alternative.getRequestedPrototype().getPrototype()) - alternative.getQuantityMissing();
1✔
423
                        Map<IngredientComponent<?, ?>, List<?>> storageMap;
424
                        if (storedQuantity > 0) {
1✔
425
                            storageMap = Maps.newIdentityHashMap();
×
426
                            storageMap.put(component, Collections.singletonList(
×
427
                                    matcher.withQuantity(alternative.getRequestedPrototype().getPrototype(), storedQuantity)
×
428
                            ));
429
                        } else {
430
                            storageMap = Collections.emptyMap();
1✔
431
                        }
432

433
                        missingDependencies.add(new UnknownCraftingRecipeException(
1✔
434
                                alternative.getRequestedPrototype(), alternative.getQuantityMissing(),
1✔
435
                                Collections.emptyList(), compressMixedIngredients(new MixedIngredients(storageMap)), Lists.newArrayList()));
1✔
436
                    }
1✔
437
                }
1✔
438
            }
439
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), null);
1✔
440
        }
441

442
        // For all missing ingredients, recursively call this method for all missing items, and add as dependencies
443
        // We store dependencies as a mapping from recipe to job,
444
        // so that only one job exist per unique recipe,
445
        // so that a job amount can be incremented once another equal recipe is found.
446
        Map<IRecipeDefinition, CraftingJob> dependencies = Maps.newHashMapWithExpectedSize(missingIngredients.size());
1✔
447
        Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> dependenciesOutputSurplus = Maps.newIdentityHashMap();
1✔
448
        // We must be able to find crafting jobs for all dependencies
449
        for (IngredientComponent dependencyComponent : missingIngredients.keySet()) {
1✔
450
            try {
451
                // TODO: if we run into weird simulated extraction bugs, we may have to scope simulatedExtractionMemory, but I'm not sure about this (yet)
452
                PartialCraftingJobCalculationDependency resultDependency = calculateCraftingJobDependencyComponent(
1✔
453
                        dependencyComponent, dependenciesOutputSurplus, missingIngredients.get(dependencyComponent), parentDependencies,
1✔
454
                        dependencies, recipeIndex, channel, storageGetter, simulatedExtractionMemory, extractionMemoryReusable,
455
                        identifierGenerator, craftingJobsGraph, collectMissingRecipes);
456
                // Don't check the other components once we have an invalid dependency.
457
                if (!resultDependency.isValid()) {
1✔
458
                    missingDependencies.addAll(resultDependency.getUnknownCrafingRecipes());
1✔
459
                    partialCraftingJobs.addAll(resultDependency.getPartialCraftingJobs());
1✔
460
                    if (!collectMissingRecipes) {
1✔
461
                        break;
1✔
462
                    }
463
                }
464
            } catch (RecursiveCraftingRecipeException e) {
1✔
465
                e.addRecipe(recipe);
1✔
466
                throw e;
1✔
467
            }
1✔
468
        }
1✔
469
        // Add remaining surplus as negatives to simulated extraction
470
        for (IngredientComponent<?, ?> surplusComponent : dependenciesOutputSurplus.keySet()) {
1✔
471
            IngredientCollectionPrototypeMap<?, ?> surplusInstances = dependenciesOutputSurplus.get(surplusComponent);
1✔
472
            if (surplusInstances != null) {
1✔
473
                for (Object instance : surplusInstances) {
1✔
474
                    IngredientCollectionPrototypeMap<?, ?> simulatedExtractionMemoryInstances = simulatedExtractionMemory.get(surplusComponent);
1✔
475
                    if (simulatedExtractionMemoryInstances == null) {
1✔
476
                        simulatedExtractionMemoryInstances = new IngredientCollectionPrototypeMap<>(surplusComponent, true);
1✔
477
                        simulatedExtractionMemory.put(surplusComponent, simulatedExtractionMemoryInstances);
1✔
478
                    }
479
                    ((IngredientCollectionPrototypeMap) simulatedExtractionMemoryInstances).remove(instance);
1✔
480
                }
1✔
481
            }
482
        }
1✔
483

484
        // If at least one of our dependencies does not have a valid recipe or is not available,
485
        // go check the next recipe.
486
        if (!missingDependencies.isEmpty()) {
1✔
487
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), partialCraftingJobs);
1✔
488
        }
489

490
        CraftingJob craftingJob = new CraftingJob(identifierGenerator.getNext(), channel, recipe, amount,
1✔
491
                compressMixedIngredients(new MixedIngredients(simulation.getLeft())));
1✔
492
        for (CraftingJob dependency : dependencies.values()) {
1✔
493
            craftingJob.addDependency(dependency);
1✔
494
            craftingJobsGraph.addDependency(craftingJob, dependency);
1✔
495
        }
1✔
496
        return new PartialCraftingJobCalculation(craftingJob, null, simulation.getLeft(), null);
1✔
497
    }
498

499
    // Helper function for calculateCraftingJobs, returns a list of non-craftable ingredients and craftable ingredients.
500
    protected static <T, M> PartialCraftingJobCalculationDependency calculateCraftingJobDependencyComponent(
501
            IngredientComponent<T, M> dependencyComponent,
502
            Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> dependenciesOutputSurplus,
503
            MissingIngredients<T, M> missingIngredients,
504
            Set<IPrototypedIngredient> parentDependencies,
505
            Map<IRecipeDefinition, CraftingJob> dependencies,
506
            IRecipeIndex recipeIndex,
507
            int channel,
508
            Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
509
            Map<IngredientComponent<?, ?>,
510
                    IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
511
            Map<IngredientComponent<?, ?>,
512
                    IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
513
            IIdentifierGenerator identifierGenerator,
514
            CraftingJobDependencyGraph craftingJobsGraph,
515
            boolean collectMissingRecipes)
516
            throws RecursiveCraftingRecipeException {
517
        IIngredientMatcher<T, M> dependencyMatcher = dependencyComponent.getMatcher();
1✔
518
        List<UnknownCraftingRecipeException> missingDependencies = Lists.newArrayList();
1✔
519
        for (MissingIngredients.Element<T, M> missingElement : missingIngredients.getElements()) {
1✔
520
            CraftingJob dependency = null;
1✔
521
            T dependencyInstance = null;
1✔
522
            boolean skipDependency = false;
1✔
523
            UnknownCraftingRecipeException firstError = null;
1✔
524
            // Loop over all prototype alternatives, at least one has to match.
525
            for (MissingIngredients.PrototypedWithRequested<T, M> prototypedAlternative : missingElement.getAlternatives()) {
1✔
526
                // Check if the missing element is reusable, and was triggered for craft earlier.
527
                if (missingElement.isInputReusable() && ((IIngredientCollectionMutable<T, M>) extractionMemoryReusable.get(dependencyComponent))
1✔
528
                        .contains(prototypedAlternative.getRequestedPrototype().getPrototype())) {
1✔
529
                    // Nothing has to be crafted anymore, jump to next dependency
530
                    skipDependency = true;
×
531
                    break;
×
532
                }
533

534
                IPrototypedIngredient<T, M> prototype = new PrototypedIngredient<>(
1✔
535
                        dependencyComponent,
536
                        dependencyMatcher.withQuantity(prototypedAlternative.getRequestedPrototype().getPrototype(), prototypedAlternative.getQuantityMissing()),
1✔
537
                        prototypedAlternative.getRequestedPrototype().getCondition()
1✔
538
                );
539
                // First check if we can grab it from previous surplus
540
                IngredientCollectionPrototypeMap<T, M> dependencyComponentSurplusOld = (IngredientCollectionPrototypeMap<T, M>) dependenciesOutputSurplus.get(dependencyComponent);
1✔
541
                IngredientCollectionPrototypeMap<T, M> dependencyComponentSurplus = null;
1✔
542
                if (dependencyComponentSurplusOld != null) {
1✔
543
                    // First create a copy of the given surplus store,
544
                    // and only once we see that the prototype is valid,
545
                    // save this copy again.
546
                    // This is because if this prototype is invalid,
547
                    // then we don't want these invalid surpluses.
548
                    dependencyComponentSurplus = new IngredientCollectionPrototypeMap<>(dependencyComponentSurplusOld.getComponent(), true);
1✔
549
                    dependencyComponentSurplus.addAll(dependencyComponentSurplusOld);
1✔
550

551
                    long remainingQuantity = dependencyMatcher.getQuantity(prototype.getPrototype());
1✔
552
                    IIngredientMatcher<T, M> prototypeMatcher = prototype.getComponent().getMatcher();
1✔
553
                    // Check all instances in the surplus that match with the given prototype
554
                    // For each match, we subtract its quantity from the required quantity.
555
                    Iterator<T> surplusIt = dependencyComponentSurplus.iterator(prototype.getPrototype(),
1✔
556
                            prototypeMatcher.withoutCondition(prototype.getCondition(), prototype.getComponent().getPrimaryQuantifier().getMatchCondition()));
1✔
557
                    boolean updatedRemainingQuantity = false;
1✔
558
                    while (remainingQuantity > 0 && surplusIt.hasNext()) {
1✔
559
                        updatedRemainingQuantity = true;
1✔
560
                        T matchingInstance = surplusIt.next();
1✔
561
                        long matchingInstanceQuantity = dependencyMatcher.getQuantity(matchingInstance);
1✔
562
                        if (matchingInstanceQuantity <= remainingQuantity) {
1✔
563
                            // This whole surplus instance can be consumed
564
                            remainingQuantity -= matchingInstanceQuantity;
1✔
565
                            surplusIt.remove();
1✔
566
                        } else {
567
                            // Only part of this surplus instance can be consumed.
568
                            matchingInstanceQuantity -= remainingQuantity;
×
569
                            remainingQuantity = 0;
×
570
                            surplusIt.remove();
×
571
                            dependencyComponentSurplus.setQuantity(matchingInstance, matchingInstanceQuantity);
×
572
                        }
573
                    }
1✔
574
                    if (updatedRemainingQuantity) {
1✔
575
                        if (remainingQuantity == 0) {
1✔
576
                            // The prototype is valid,
577
                            // so we can finally store our temporary surplus
578
                            dependenciesOutputSurplus.put(dependencyComponent, dependencyComponentSurplus);
×
579

580
                            // Nothing has to be crafted anymore, jump to next dependency
581
                            skipDependency = true;
×
582
                            break;
×
583
                        } else {
584
                            // Partial availability, other part needs to be crafted still.
585
                            prototype = new PrototypedIngredient<>(dependencyComponent,
1✔
586
                                    dependencyMatcher.withQuantity(prototype.getPrototype(), remainingQuantity),
1✔
587
                                    prototype.getCondition());
1✔
588
                        }
589
                    }
590
                }
591

592
                // Try to craft the given prototype
593
                try {
594
                    Set<IPrototypedIngredient> childDependencies = Sets.newHashSet(parentDependencies);
1✔
595
                    if (!childDependencies.add(prototype)) {
1✔
596
                        throw new RecursiveCraftingRecipeException(prototype);
1✔
597
                    }
598

599
                    dependency = calculateCraftingJobs(recipeIndex, channel, storageGetter,
1✔
600
                            dependencyComponent, prototype.getPrototype(),
1✔
601
                            prototype.getCondition(), true, simulatedExtractionMemory, extractionMemoryReusable,
1✔
602
                            identifierGenerator, craftingJobsGraph, childDependencies, collectMissingRecipes);
603
                    dependencyInstance = prototype.getPrototype();
1✔
604

605
                    // The prototype is valid,
606
                    // so we can finally store our temporary surplus
607
                    if (dependencyComponentSurplus != null) {
1✔
608
                        dependenciesOutputSurplus.put(dependencyComponent, dependencyComponentSurplus);
1✔
609
                    }
610

611
                    // Add the auxiliary recipe outputs that are not requested to the surplus
612
                    Object dependencyQuantifierlessCondition = dependencyMatcher.withoutCondition(prototype.getCondition(),
1✔
613
                            dependencyComponent.getPrimaryQuantifier().getMatchCondition());
1✔
614
                    long requestedQuantity = dependencyMatcher.getQuantity(prototype.getPrototype());
1✔
615
                    for (IngredientComponent outputComponent : dependency.getRecipe().getOutput().getComponents()) {
1✔
616
                        IngredientCollectionPrototypeMap<?, ?> componentSurplus = dependenciesOutputSurplus.get(outputComponent);
1✔
617
                        if (componentSurplus == null) {
1✔
618
                            componentSurplus = new IngredientCollectionPrototypeMap<>(outputComponent, true);
1✔
619
                            dependenciesOutputSurplus.put(outputComponent, componentSurplus);
1✔
620
                        }
621
                        List<Object> instances = dependency.getRecipe().getOutput().getInstances(outputComponent);
1✔
622
                        long recipeAmount = dependency.getAmount();
1✔
623
                        if (recipeAmount > 1) {
1✔
624
                            IIngredientMatcher matcher = outputComponent.getMatcher();
1✔
625
                            // If more than one recipe amount was crafted, correctly multiply the outputs to calculate the effective surplus.
626
                            instances = instances
1✔
627
                                    .stream()
1✔
628
                                    .map(instance -> matcher.withQuantity(instance, matcher.getQuantity(instance) * recipeAmount))
1✔
629
                                    .collect(Collectors.toList());
1✔
630
                        }
631
                        addRemainderAsSurplusForComponent(outputComponent, (List) instances, componentSurplus,
1✔
632
                                (IngredientComponent) prototype.getComponent(), prototype.getPrototype(), dependencyQuantifierlessCondition,
1✔
633
                                requestedQuantity);
634
                    }
1✔
635

636
                    break;
1✔
637
                } catch (UnknownCraftingRecipeException e) {
1✔
638
                    // Save the first error, and check the next prototype
639
                    if (firstError == null) {
1✔
640
                        // Modify the error so that the correct missing quantity is stored
641
                        firstError = new UnknownCraftingRecipeException(
1✔
642
                                e.getIngredient(), prototypedAlternative.getQuantityMissing(),
1✔
643
                                e.getMissingChildRecipes(), compressMixedIngredients(e.getIngredientsStorage()), e.getPartialCraftingJobs());
1✔
644
                    }
645
                }
646
            }
1✔
647

648
            // Check if this dependency can be skipped
649
            if (skipDependency) {
1✔
650
                continue;
×
651
            }
652

653
            // If no valid crafting recipe was found for the current sub-instance, re-throw its error
654
            if (dependency == null) {
1✔
655
                missingDependencies.add(firstError);
1✔
656
                if (collectMissingRecipes) {
1✔
657
                    continue;
1✔
658
                } else {
659
                    break;
660
                }
661
            }
662

663
            // --- When we reach this point, a valid sub-recipe was found ---
664

665
            // Update our simulatedExtractionMemory to indicate that the dependency's
666
            // instance should not be extracted anymore.
667
            ((IngredientCollectionPrototypeMap<T, M>) simulatedExtractionMemory.get(dependencyComponent))
1✔
668
                    .remove(dependencyInstance);
1✔
669

670
            // If the dependency instance is reusable, mark it as available in our reusable extraction memory
671
            if (missingElement.isInputReusable()) {
1✔
672
                ((IIngredientCollectionMutable<T, M>) extractionMemoryReusable.get(dependencyComponent)).add(dependencyInstance);
1✔
673
            }
674

675
            // Add the valid sub-recipe it to our dependencies
676
            // If the recipe was already present at this level, just increment the amount of the existing job.
677
            CraftingJob existingJob = dependencies.get(dependency.getRecipe());
1✔
678
            if (existingJob == null) {
1✔
679
                dependencies.put(dependency.getRecipe(), dependency);
1✔
680
            } else {
681
                // Remove the standalone dependency job by merging it into the existing job
682
                craftingJobsGraph.mergeCraftingJobs(existingJob, dependency, true);
1✔
683
            }
684
        }
1✔
685

686
        return new PartialCraftingJobCalculationDependency(missingDependencies, dependencies.values());
1✔
687
    }
688

689
    // Helper function for calculateCraftingJobDependencyComponent
690
    protected static <T1, M1, T2, M2> void addRemainderAsSurplusForComponent(IngredientComponent<T1, M1> ingredientComponent,
691
                                                                             List<T1> instances,
692
                                                                             IngredientCollectionPrototypeMap<T1, M1> simulatedExtractionMemory,
693
                                                                             IngredientComponent<T2, M2> blackListComponent,
694
                                                                             T2 blacklistInstance, M2 blacklistCondition,
695
                                                                             long blacklistQuantity) {
696
        IIngredientMatcher<T2, M2> blacklistMatcher = blackListComponent.getMatcher();
1✔
697
        for (T1 instance : instances) {
1✔
698
            IIngredientMatcher<T1, M1> outputMatcher = ingredientComponent.getMatcher();
1✔
699
            long reduceQuantity = 0;
1✔
700
            if (blackListComponent == ingredientComponent
1✔
701
                    && blacklistMatcher.matches(blacklistInstance, (T2) instance, blacklistCondition)) {
1✔
702
                reduceQuantity = blacklistQuantity;
1✔
703
            }
704
            long quantity = simulatedExtractionMemory.getQuantity(instance) + (outputMatcher.getQuantity(instance) - reduceQuantity);
1✔
705
            if (quantity > 0) {
1✔
706
                simulatedExtractionMemory.setQuantity(instance, quantity);
1✔
707
            }
708
        }
1✔
709
    }
1✔
710

711
    /**
712
     * Schedule all crafting jobs in the given dependency graph in the given network.
713
     * @param craftingNetwork The target crafting network.
714
     * @param craftingJobDependencyGraph The crafting job dependency graph.
715
     * @param allowDistribution If the crafting jobs are allowed to be split over multiple crafting interfaces.
716
     * @param initiator Optional UUID of the initiator.
717
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
718
     */
719
    public static void scheduleCraftingJobs(ICraftingNetwork craftingNetwork,
720
                                            CraftingJobDependencyGraph craftingJobDependencyGraph,
721
                                            boolean allowDistribution,
722
                                            @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
723
        List<CraftingJob> startedJobs = Lists.newArrayList();
×
724
        craftingNetwork.getCraftingJobDependencyGraph().importDependencies(craftingJobDependencyGraph);
×
725
        for (CraftingJob craftingJob : craftingJobDependencyGraph.getCraftingJobs()) {
×
726
            try {
727
                craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution);
×
728
            } catch (UnavailableCraftingInterfacesException e) {
×
729
                // First, cancel all jobs that were already started
730
                for (CraftingJob startedJob : startedJobs) {
×
731
                    craftingNetwork.cancelCraftingJob(startedJob.getChannel(), startedJob.getId());
×
732
                }
×
733

734
                // Then, throw an exception for all jobs in this dependency graph
735
                throw new UnavailableCraftingInterfacesException(craftingJobDependencyGraph.getCraftingJobs());
×
736
            }
×
737
            startedJobs.add(craftingJob);
×
738
            if (initiator != null) {
×
739
                craftingJob.setInitiatorUuid(initiator.toString());
×
740
            }
741
        }
×
742
    }
×
743

744
    /**
745
     * Schedule the given crafting job  in the given network.
746
     * @param craftingNetwork The target crafting network.
747
     * @param craftingJob The crafting job to schedule.
748
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
749
     * @param initiator Optional UUID of the initiator.
750
     * @return The scheduled crafting job.
751
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
752
     */
753
    public static CraftingJob scheduleCraftingJob(ICraftingNetwork craftingNetwork,
754
                                                  CraftingJob craftingJob,
755
                                                  boolean allowDistribution,
756
                                                  @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
757
        craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution);
×
758
        if (initiator != null) {
×
759
            craftingJob.setInitiatorUuid(initiator.toString());
×
760
        }
761
        return craftingJob;
×
762
    }
763

764
    /**
765
     * Schedule a crafting job for the given instance in the given network.
766
     * @param network The target network.
767
     * @param channel The target channel.
768
     * @param ingredientComponent The ingredient component type of the instance.
769
     * @param instance The instance to craft.
770
     * @param matchCondition The match condition of the instance.
771
     * @param craftMissing If the missing required ingredients should also be crafted.
772
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
773
     * @param identifierGenerator An ID generator for crafting jobs.
774
     * @param initiator Optional UUID of the initiator.
775
     * @param <T> The instance type.
776
     * @param <M> The matching condition parameter.
777
     * @return The scheduled crafting job, or null if no recipe was found.
778
     */
779
    @Nullable
780
    public static <T, M> CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
781
                                                                     IngredientComponent<T, M> ingredientComponent,
782
                                                                     T instance, M matchCondition,
783
                                                                     boolean craftMissing, boolean allowDistribution,
784
                                                                     IIdentifierGenerator identifierGenerator,
785
                                                                     @Nullable UUID initiator) {
786
        try {
787
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
788
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, ingredientComponent, instance,
×
789
                    matchCondition, craftMissing, identifierGenerator, dependencyGraph, false);
790

791
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
792

793
            scheduleCraftingJobs(craftingNetwork, dependencyGraph, allowDistribution, initiator);
×
794

795
            return craftingJob;
×
796
        } catch (UnknownCraftingRecipeException | RecursiveCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
797
            return null;
×
798
        }
799
    }
800

801
    /**
802
     * Schedule a crafting job for the given recipe in the given network.
803
     * @param network The target network.
804
     * @param channel The target channel.
805
     * @param recipe The recipe to craft.
806
     * @param amount The amount to craft.
807
     * @param craftMissing If the missing required ingredients should also be crafted.
808
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
809
     * @param identifierGenerator An ID generator for crafting jobs.
810
     * @param initiator Optional UUID of the initiator.
811
     * @return The scheduled crafting job, or null if no recipe was found.
812
     */
813
    @Nullable
814
    public static CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
815
                                                              IRecipeDefinition recipe, int amount,
816
                                                              boolean craftMissing, boolean allowDistribution,
817
                                                              IIdentifierGenerator identifierGenerator,
818
                                                              @Nullable UUID initiator) {
819
        try {
820
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
821
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, recipe, amount, craftMissing,
×
822
                    identifierGenerator, dependencyGraph, false);
823

824
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
825

826
            scheduleCraftingJobs(craftingNetwork, dependencyGraph, allowDistribution, initiator);
×
827

828
            return craftingJob;
×
829
        } catch (RecursiveCraftingRecipeException | FailedCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
830
            return null;
×
831
        }
832
    }
833

834
    /**
835
     * Check if the given network contains the given instance in any of its storages.
836
     * @param network The target network.
837
     * @param channel The target channel.
838
     * @param ingredientComponent The ingredient component type of the instance.
839
     * @param instance The instance to check.
840
     * @param matchCondition The match condition of the instance.
841
     * @param <T> The instance type.
842
     * @param <M> The matching condition parameter.
843
     * @return If the instance is present in the network.
844
     */
845
    public static <T, M> boolean hasStorageInstance(INetwork network, int channel,
846
                                                    IngredientComponent<T, M> ingredientComponent,
847
                                                    T instance, M matchCondition) {
848
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
849
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
850
        boolean contains;
851
        if (storage instanceof IngredientChannelIndexed) {
×
852
            IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
853
            long quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
854
            contains = matcher.hasCondition(matchCondition, ingredientComponent.getPrimaryQuantifier().getMatchCondition()) ? quantityPresent >= matcher.getQuantity(instance) : quantityPresent > 0;
×
855
        } else {
×
856
            contains = !ingredientComponent.getMatcher().isEmpty(storage.extract(instance, matchCondition, true));
×
857
        }
858
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
859
        return contains;
×
860
    }
861

862
    /**
863
     * Check the quantity of the given instance in the network.
864
     * @param network The target network.
865
     * @param channel The target channel.
866
     * @param ingredientComponent The ingredient component type of the instance.
867
     * @param instance The instance to check.
868
     * @param matchCondition The match condition of the instance.
869
     * @param <T> The instance type.
870
     * @param <M> The matching condition parameter.
871
     * @return The quantity in the network.
872
     */
873
    public static <T, M> long getStorageInstanceQuantity(INetwork network, int channel,
874
                                                         IngredientComponent<T, M> ingredientComponent,
875
                                                         T instance, M matchCondition) {
876
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
877
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
878
        long quantityPresent;
879
        if (storage instanceof IngredientChannelIndexed) {
×
880
            quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
881
        } else {
882
            quantityPresent = ingredientComponent.getMatcher().getQuantity(storage.extract(instance, matchCondition, true));
×
883
        }
884
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
885
        return quantityPresent;
×
886
    }
887

888
    /**
889
     * Check if there is a scheduled crafting job for the given instance.
890
     * @param craftingNetwork The target crafting network.
891
     * @param channel The target channel.
892
     * @param ingredientComponent The ingredient component type of the instance.
893
     * @param instance The instance to check.
894
     * @param matchCondition The match condition of the instance.
895
     * @param <T> The instance type.
896
     * @param <M> The matching condition parameter.
897
     * @return If the instance has a crafting job.
898
     */
899
    public static <T, M> boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
900
                                            IngredientComponent<T, M> ingredientComponent,
901
                                            T instance, M matchCondition) {
902
        Iterator<CraftingJob> craftingJobs = craftingNetwork.getCraftingJobs(channel, ingredientComponent,
×
903
                instance, matchCondition);
904
        return craftingJobs.hasNext();
×
905
    }
906

907
    /**
908
     * Check if there is a scheduled crafting job for the given recipe.
909
     * @param craftingNetwork The target crafting network.
910
     * @param channel The target channel.
911
     * @param recipe The recipe to check.
912
     * @return If the instance has a crafting job.
913
     */
914
    public static boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
915
                                     IRecipeDefinition recipe) {
916
        Iterator<CraftingJob> it = craftingNetwork.getCraftingJobs(channel);
×
917
        while (it.hasNext()) {
×
918
            if (it.next().getRecipe().equals(recipe)) {
×
919
                return true;
×
920
            }
921
        }
922
        return false;
×
923
    }
924

925
    /**
926
     * Get all required recipe input ingredients from the network for the given ingredient component.
927
     *
928
     * If multiple alternative inputs are possible,
929
     * then only the first possible match will be taken.
930
     *
931
     * Note: Make sure that you first call in simulation-mode
932
     * to see if the ingredients are available.
933
     * If you immediately call this non-simulated,
934
     * then there might be a chance that ingredients are lost
935
     * from the network.
936
     *
937
     * @param storage The target storage.
938
     * @param ingredientComponent The ingredient component to get the ingredients for.
939
     * @param recipe The recipe to get the inputs from.
940
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
941
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
942
     * @param <T> The instance type.
943
     * @param <M> The matching condition parameter, may be Void.
944
     * @return A list of slot-based ingredients, or null if no valid inputs could be found.
945
     */
946
    @Nullable
947
    public static <T, M> List<T> getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage,
948
                                                           IngredientComponent<T, M> ingredientComponent,
949
                                                           IRecipeDefinition recipe, boolean simulate,
950
                                                           long recipeOutputQuantity) {
951
        return getIngredientRecipeInputs(storage, ingredientComponent, recipe, simulate,
1✔
952
                simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null,
1✔
953
                new IngredientHashSet<>(ingredientComponent),
954
                false, recipeOutputQuantity).getLeft();
1✔
955
    }
956

957
    /**
958
     * Get all required recipe input ingredients from the network for the given ingredient component,
959
     * and optionally, explicitly calculate the missing ingredients.
960
     *
961
     * If multiple alternative inputs are possible,
962
     * then only the first possible match will be taken.
963
     *
964
     * Note: Make sure that you first call in simulation-mode
965
     * to see if the ingredients are available.
966
     * If you immediately call this non-simulated,
967
     * then there might be a chance that ingredients are lost
968
     * from the network.
969
     *
970
     * @param storage The target storage.
971
     * @param ingredientComponent The ingredient component to get the ingredients for.
972
     * @param recipe The recipe to get the inputs from.
973
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
974
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
975
     *                                  This is to make sure that instances can not be extracted multiple times
976
     *                                  when simulating.
977
     *                                  The quantities can also go negatives,
978
     *                                  which means that a surplus of the given instance is present,
979
     *                                  which will be used up first before a call to the storage.
980
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
981
     * @param collectMissingIngredients If missing ingredients should be collected.
982
     *                                  If false, then the first returned list may be null
983
     *                                  if no valid matches can be found,
984
     *                                  and the second returned list is always null,
985
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
986
     * @param <T> The instance type.
987
     * @param <M> The matching condition parameter, may be Void.
988
     * @return A pair with two lists:
989
     *           1. A list of available slot-based ingredients.
990
     *           2. A missing ingredients object.
991
     */
992
    public static <T, M> Pair<List<T>, MissingIngredients<T, M>>
993
    getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage, IngredientComponent<T, M> ingredientComponent,
994
                              IRecipeDefinition recipe, boolean simulate,
995
                              IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemory,
996
                              IIngredientCollectionMutable<T, M> extractionMemoryReusable,
997
                              boolean collectMissingIngredients, long recipeOutputQuantity) {
998
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
999

1000
        // Quickly return if the storage is empty
1001
        // We can't take this shortcut if we have a reusable ingredient AND extractionMemoryReusable is not empty
1002
        if (storage.getMaxQuantity() == 0 &&
1✔
1003
                extractionMemoryReusable.isEmpty() &&
1✔
1004
                IntStream.range(0, recipe.getInputs(ingredientComponent).size())
1✔
1005
                        .noneMatch(i -> recipe.isInputReusable(ingredientComponent, i))) {
1✔
1006
            if (collectMissingIngredients) {
1✔
1007
                List<IPrototypedIngredientAlternatives<T, M>> recipeInputs = recipe.getInputs(ingredientComponent);
1✔
1008
                MissingIngredients<T, M> missing = new MissingIngredients<>(recipeInputs.stream().map(IPrototypedIngredientAlternatives::getAlternatives)
1✔
1009
                        .map(l -> multiplyPrototypedIngredients(l, recipeOutputQuantity)) // If the input is reusable, don't multiply the expected input quantity
1✔
1010
                        .map(ps -> new MissingIngredients.Element<>(ps
1✔
1011
                                .stream()
1✔
1012
                                .map(p -> new MissingIngredients.PrototypedWithRequested<>(p, matcher.getQuantity(p.getPrototype())))
1✔
1013
                                .collect(Collectors.toList()), false)
1✔
1014
                        )
1015
                        .collect(Collectors.toList()));
1✔
1016
                return Pair.of(
1✔
1017
                        Lists.newArrayList(Collections.nCopies(recipe.getInputs(ingredientComponent).size(),
1✔
1018
                                ingredientComponent.getMatcher().getEmptyInstance())),
1✔
1019
                        missing);
1020
            } else {
1021
                return Pair.of(null, null);
1✔
1022
            }
1023
        }
1024

1025
        // Iterate over all input slots
1026
        List<IPrototypedIngredientAlternatives<T, M>> inputAlternativePrototypes = recipe.getInputs(ingredientComponent);
1✔
1027
        List<T> inputInstances = Lists.newArrayList();
1✔
1028
        List<MissingIngredients.Element<T, M>> missingElements =
1029
                collectMissingIngredients ? Lists.newArrayList() : null;
1✔
1030
        for (int inputIndex = 0; inputIndex < inputAlternativePrototypes.size(); inputIndex++) {
1✔
1031
            IPrototypedIngredientAlternatives<T, M> inputPrototypes = inputAlternativePrototypes.get(inputIndex);
1✔
1032
            T firstInputInstance = null;
1✔
1033
            boolean setFirstInputInstance = false;
1✔
1034
            T inputInstance = null;
1✔
1035
            boolean hasInputInstance = false;
1✔
1036
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBufferFirst = null;
1✔
1037
            IIngredientCollectionMutable<T, M> extractionMemoryReusableBufferFirst = null;
1✔
1038

1039
            // Iterate over all alternatives for this input slot, and take the first matching ingredient.
1040
            List<MissingIngredients.PrototypedWithRequested<T, M>> missingAlternatives = Lists.newArrayList();
1✔
1041
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryAlternative = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1042
            if (simulate) {
1✔
1043
                simulatedExtractionMemoryAlternative.addAll(simulatedExtractionMemory);
1✔
1044
            }
1045
            for (IPrototypedIngredient<T, M> inputPrototype : inputPrototypes.getAlternatives()) {
1✔
1046
                boolean inputReusable = recipe.isInputReusable(ingredientComponent, inputIndex);
1✔
1047
                IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBuffer = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1048
                IIngredientCollectionMutable<T, M> extractionMemoryReusableBuffer = inputReusable ? new IngredientHashSet<>(ingredientComponent) : null;
1✔
1049
                boolean shouldBreak = false;
1✔
1050

1051
                // Multiply required prototype if recipe quantity is higher than one, AND if the input is NOT reusable.
1052
                if (recipeOutputQuantity > 1 && !inputReusable) {
1✔
1053
                    inputPrototype = multiplyPrototypedIngredient(inputPrototype, recipeOutputQuantity);
1✔
1054
                }
1055

1056
                // If the prototype is empty, we can skip network extraction
1057
                if (matcher.isEmpty(inputPrototype.getPrototype())) {
1✔
1058
                    inputInstance = inputPrototype.getPrototype();
1✔
1059
                    hasInputInstance = true;
1✔
1060
                    break;
1✔
1061
                }
1062

1063
                long prototypeQuantity = matcher.getQuantity(inputPrototype.getPrototype());
1✔
1064
                if (inputReusable && extractionMemoryReusable.contains(inputPrototype.getPrototype())) {
1✔
1065
                    // If the reusable item has been extracted before, mark as valid, and don't extract again.
1066
                    inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1067
                    hasInputInstance = true;
1✔
1068
                    shouldBreak = true;
1✔
1069
                } else {
1070
                    long memoryQuantity;
1071
                    if (simulate && (memoryQuantity = simulatedExtractionMemoryAlternative
1✔
1072
                            .getQuantity(inputPrototype.getPrototype())) != 0) {
1✔
1073
                        long newQuantity = memoryQuantity + prototypeQuantity;
1✔
1074
                        if (newQuantity > 0) {
1✔
1075
                            // Part of our quantity can be provided via simulatedExtractionMemory,
1076
                            // but not all of it,
1077
                            // so we need to extract from storage as well.
1078
                            T newInstance = matcher.withQuantity(inputPrototype.getPrototype(), newQuantity);
1✔
1079
                            M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1080
                                    ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1081
                            if (storage instanceof IngredientChannelAdapter)
1✔
1082
                                ((IngredientChannelAdapter) storage).disableLimits();
×
1083
                            T extracted = storage.extract(newInstance, matchCondition, true);
1✔
1084
                            if (storage instanceof IngredientChannelAdapter)
1✔
1085
                                ((IngredientChannelAdapter) storage).enableLimits();
×
1086
                            long quantityExtracted = matcher.getQuantity(extracted);
1✔
1087
                            if (quantityExtracted == newQuantity) {
1✔
1088
                                // All remaining could be extracted from storage, all is fine now
1089
                                inputInstance = inputPrototype.getPrototype();
1✔
1090
                                simulatedExtractionMemoryAlternative.add(inputInstance);
1✔
1091
                                simulatedExtractionMemoryBuffer.add(inputInstance);
1✔
1092
                                if (inputReusable) {
1✔
1093
                                    extractionMemoryReusableBuffer.add(inputInstance);
1✔
1094
                                }
1095
                                hasInputInstance = true;
1✔
1096
                                shouldBreak = true;
1✔
1097
                            } else if (collectMissingIngredients) {
1✔
1098
                                // Not everything could be extracted from storage, we *miss* the remaining ingredient.
1099
                                long quantityMissingPrevious = Math.max(0, memoryQuantity - quantityExtracted);
1✔
1100
                                long quantityMissingTotal = newQuantity - quantityExtracted;
1✔
1101
                                long quantityMissingRelative = quantityMissingTotal - quantityMissingPrevious;
1✔
1102

1103
                                missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissingRelative));
1✔
1104
                                inputInstance = matcher.withQuantity(inputPrototype.getPrototype(), prototypeQuantity - quantityMissingRelative);
1✔
1105
                                simulatedExtractionMemoryAlternative.setQuantity(inputPrototype.getPrototype(), quantityMissingTotal);
1✔
1106
                                // Original prototype quantity because we what can be extracted from storage and what could NOT be extracted from storage should be added to the simulation extraction memory.
1107
                                // The part that could NOT be extracted will be removed later when crafting jobs are calculated for the missing elements. (not doing so would lead to over-estimation of what is in storage)
1108
                                simulatedExtractionMemoryBuffer.add(matcher.withQuantity(inputPrototype.getPrototype(), prototypeQuantity));
1✔
1109
                            }
1110
                        } else {
1✔
1111
                            // All of our quantity can be provided via our surplus in simulatedExtractionMemory
1112
                            simulatedExtractionMemoryAlternative.add(inputPrototype.getPrototype());
1✔
1113
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1114
                            if (inputReusable) {
1✔
1115
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1116
                            }
1117
                            inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1118
                            hasInputInstance = true;
1✔
1119
                            shouldBreak = true;
1✔
1120
                        }
1121
                    } else {
1✔
1122
                        M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1123
                                ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1124
                        if (storage instanceof IngredientChannelAdapter)
1✔
1125
                            ((IngredientChannelAdapter) storage).disableLimits();
×
1126
                        T extracted = storage.extract(inputPrototype.getPrototype(), matchCondition, simulate);
1✔
1127
                        if (storage instanceof IngredientChannelAdapter)
1✔
1128
                            ((IngredientChannelAdapter) storage).enableLimits();
×
1129
                        long quantityExtracted = matcher.getQuantity(extracted);
1✔
1130
                        inputInstance = extracted;
1✔
1131
                        if (simulate) {
1✔
1132
                            simulatedExtractionMemoryAlternative.add(extracted);
1✔
1133
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1134
                        }
1135
                        if (prototypeQuantity == quantityExtracted) {
1✔
1136
                            hasInputInstance = true;
1✔
1137
                            shouldBreak = true;
1✔
1138
                            if (inputReusable) {
1✔
1139
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1140
                            }
1141
                        } else if (collectMissingIngredients) {
1✔
1142
                            long quantityMissing = prototypeQuantity - quantityExtracted;
1✔
1143
                            missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissing));
1✔
1144
                        }
1145
                    }
1146
                }
1147

1148
                if (!setFirstInputInstance || shouldBreak) {
1✔
1149
                    setFirstInputInstance = true;
1✔
1150
                    firstInputInstance = inputInstance;
1✔
1151
                    simulatedExtractionMemoryBufferFirst = simulatedExtractionMemoryBuffer;
1✔
1152
                    if (inputReusable) {
1✔
1153
                        extractionMemoryReusableBufferFirst = extractionMemoryReusableBuffer;
1✔
1154
                    } else {
1155
                        extractionMemoryReusableBufferFirst = null;
1✔
1156
                    }
1157
                }
1158

1159
                if (shouldBreak) {
1✔
1160
                    break;
1✔
1161
                }
1162
            }
1✔
1163

1164
            if (simulatedExtractionMemoryBufferFirst != null) {
1✔
1165
                for (T instance : simulatedExtractionMemoryBufferFirst) {
1✔
1166
                    simulatedExtractionMemory.add(instance);
1✔
1167
                }
1✔
1168
            }
1169
            if (extractionMemoryReusableBufferFirst != null) {
1✔
1170
                for (T instance : extractionMemoryReusableBufferFirst) {
1✔
1171
                    extractionMemoryReusable.add(instance);
1✔
1172
                }
1✔
1173
            }
1174

1175
            // If none of the alternatives were found, fail immediately
1176
            if (!hasInputInstance) {
1✔
1177
                if (!simulate) {
1✔
1178
                    // But first, re-insert all already-extracted instances
1179
                    for (T instance : inputInstances) {
1✔
1180
                        T remaining = storage.insert(instance, false);
1✔
1181
                        if (!matcher.isEmpty(remaining)) {
1✔
1182
                            throw new IllegalStateException("Extraction for a crafting recipe failed" +
×
1183
                                    "due to inconsistent insertion behaviour by destination in simulation " +
1184
                                    "and non-simulation: " + storage + ". Lost: " + remaining);
1185
                        }
1186
                    }
1✔
1187
                }
1188

1189
                if (!collectMissingIngredients) {
1✔
1190
                    // This input failed, return immediately
1191
                    return Pair.of(null, null);
1✔
1192
                } else {
1193
                    // Multiply missing collection if recipe quantity is higher than one
1194
                    if (missingAlternatives.size() > 0) {
1✔
1195
                        missingElements.add(new MissingIngredients.Element<>(missingAlternatives, recipe.isInputReusable(ingredientComponent, inputIndex)));
1✔
1196
                    }
1197
                }
1198
            }
1199

1200
            // Otherwise, append it to the list and carry on.
1201
            // If none of the instances were valid, we add the first partially valid instance.
1202
            if (hasInputInstance) {
1✔
1203
                inputInstances.add(inputInstance);
1✔
1204
            } else if (setFirstInputInstance && !matcher.isEmpty(firstInputInstance)) {
1✔
1205
                inputInstances.add(firstInputInstance);
1✔
1206
            }
1207
        }
1208

1209
        return Pair.of(
1✔
1210
                inputInstances,
1211
                collectMissingIngredients ? new MissingIngredients<>(missingElements) : null
1✔
1212
        );
1213
    }
1214

1215
    /**
1216
     * Get all required recipe input ingredients from the network.
1217
     *
1218
     * If multiple alternative inputs are possible,
1219
     * then only the first possible match will be taken.
1220
     *
1221
     * Note: Make sure that you first call in simulation-mode
1222
     * to see if the ingredients are available.
1223
     * If you immediately call this non-simulated,
1224
     * then there might be a chance that ingredients are lost
1225
     * from the network.
1226
     *
1227
     * @param network The target network.
1228
     * @param channel The target channel.
1229
     * @param recipe The recipe to get the inputs from.
1230
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1231
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1232
     * @return The found ingredients or null.
1233
     */
1234
    @Nullable
1235
    public static IMixedIngredients getRecipeInputs(INetwork network, int channel,
1236
                                                    IRecipeDefinition recipe, boolean simulate,
1237
                                                    long recipeOutputQuantity) {
1238
        Map<IngredientComponent<?, ?>, List<?>> inputs = getRecipeInputs(getNetworkStorageGetter(network, channel, true),
×
1239
                recipe, simulate, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), false, recipeOutputQuantity).getLeft();
×
1240
        return inputs == null ? null : new MixedIngredients(inputs);
×
1241
    }
1242

1243
    /**
1244
     * Create a callback function for getting a storage for an ingredient component from the given network channel.
1245
     * @param network The target network.
1246
     * @param channel The target channel.
1247
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
1248
     * @return A callback function for getting a storage for an ingredient component.
1249
     */
1250
    public static Function<IngredientComponent<?, ?>, IIngredientComponentStorage> getNetworkStorageGetter(INetwork network, int channel, boolean scheduleObservation) {
1251
        return ingredientComponent -> getNetworkStorage(network, channel, ingredientComponent, scheduleObservation);
×
1252
    }
1253

1254
    /**
1255
     * Get all required recipe input ingredients based on a given storage callback.
1256
     *
1257
     * If multiple alternative inputs are possible,
1258
     * then only the first possible match will be taken.
1259
     *
1260
     * Note: Make sure that you first call in simulation-mode
1261
     * to see if the ingredients are available.
1262
     * If you immediately call this non-simulated,
1263
     * then there might be a chance that ingredients are lost
1264
     * from the network.
1265
     *
1266
     * @param storageGetter A callback function to get a storage for the given ingredient component.
1267
     * @param recipe The recipe to get the inputs from.
1268
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1269
     * @param simulatedExtractionMemories This map remembers all extracted instances in simulation mode.
1270
     *                                    This is to make sure that instances can not be extracted multiple times
1271
     *                                    when simulating.
1272
     * @param extractionMemoriesReusable Like simulatedExtractionMemories, but it stores the reusable ingredients.
1273
     * @param collectMissingIngredients If missing ingredients should be collected.
1274
     *                                  If false, then the first returned mixed ingredients may be null
1275
     *                                  if no valid matches can be found,
1276
     *                                  and the second returned list is always null,
1277
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1278
     * @return A pair with two objects:
1279
     *           1. The found ingredients or null.
1280
     *           2. A mapping from ingredient component to missing ingredients (non-slot-based).
1281
     */
1282
    public static Pair<Map<IngredientComponent<?, ?>, List<?>>, Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>>>
1283
    getRecipeInputs(Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter, IRecipeDefinition recipe, boolean simulate,
1284
                    Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemories,
1285
                    Map<IngredientComponent<?, ?>, IIngredientCollectionMutable<?, ?>> extractionMemoriesReusable,
1286
                    boolean collectMissingIngredients, long recipeOutputQuantity) {
1287
        // Determine available and missing ingredients
1288
        Map<IngredientComponent<?, ?>, List<?>> ingredientsAvailable = Maps.newIdentityHashMap();
1✔
1289
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> ingredientsMissing = Maps.newIdentityHashMap();
1✔
1290
        for (IngredientComponent<?, ?> ingredientComponent : recipe.getInputComponents()) {
1✔
1291
            IIngredientComponentStorage storage = storageGetter.apply(ingredientComponent);
1✔
1292
            IngredientCollectionPrototypeMap<?, ?> simulatedExtractionMemory = simulatedExtractionMemories.get(ingredientComponent);
1✔
1293
            if (simulatedExtractionMemory == null) {
1✔
1294
                simulatedExtractionMemory = new IngredientCollectionPrototypeMap<>(ingredientComponent, true);
1✔
1295
                simulatedExtractionMemories.put(ingredientComponent, simulatedExtractionMemory);
1✔
1296
            }
1297
            IIngredientCollectionMutable extractionMemoryReusable = extractionMemoriesReusable.get(ingredientComponent);
1✔
1298
            if (extractionMemoryReusable == null) {
1✔
1299
                extractionMemoryReusable = new IngredientHashSet<>(ingredientComponent);
1✔
1300
                extractionMemoriesReusable.put(ingredientComponent, extractionMemoryReusable);
1✔
1301
            }
1302
            Pair<List<?>, MissingIngredients<?, ?>> subIngredients = getIngredientRecipeInputs(storage,
1✔
1303
                    (IngredientComponent) ingredientComponent, recipe, simulate, simulatedExtractionMemory, extractionMemoryReusable,
1304
                    collectMissingIngredients, recipeOutputQuantity);
1305
            List<?> subIngredientAvailable = subIngredients.getLeft();
1✔
1306
            MissingIngredients<?, ?> subIngredientsMissing = subIngredients.getRight();
1✔
1307
            if (subIngredientAvailable == null && !collectMissingIngredients) {
1✔
1308
                return Pair.of(null, null);
×
1309
            } else {
1310
                if (subIngredientAvailable != null && !subIngredientAvailable.isEmpty()) {
1✔
1311
                    ingredientsAvailable.put(ingredientComponent, subIngredientAvailable);
1✔
1312
                }
1313
                if (collectMissingIngredients && !subIngredientsMissing.getElements().isEmpty()) {
1✔
1314
                    ingredientsMissing.put(ingredientComponent, subIngredientsMissing);
1✔
1315
                }
1316
            }
1317
        }
1✔
1318

1319
        // Compress missing ingredients
1320
        // We do this to ensure that instances missing multiple times can be easily combined
1321
        // when triggering a crafting job for them.
1322
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> ingredientsMissingCompressed = Maps.newIdentityHashMap();
1✔
1323
        for (IngredientComponent<?, ?> ingredientComponent : ingredientsMissing.keySet()) {
1✔
1324
            ingredientsMissingCompressed.put(ingredientComponent, compressMissingIngredients(ingredientsMissing.get(ingredientComponent)));
1✔
1325
        }
1✔
1326

1327
        return Pair.of(ingredientsAvailable, ingredientsMissingCompressed);
1✔
1328
    }
1329

1330
    /**
1331
     * Create a list of prototyped ingredients from the instances
1332
     * of the given ingredient component type in the given mixed ingredients.
1333
     *
1334
     * Equal prototypes will be stacked.
1335
     *
1336
     * @param ingredientComponent The ingredient component type.
1337
     * @param mixedIngredients The mixed ingredients.
1338
     * @param <T> The instance type.
1339
     * @param <M> The matching condition parameter.
1340
     * @return A list of prototypes.
1341
     */
1342
    public static <T, M> List<IPrototypedIngredient<T, M>> getCompressedIngredients(IngredientComponent<T, M> ingredientComponent,
1343
                                                                                    IMixedIngredients mixedIngredients) {
1344
        List<IPrototypedIngredient<T, M>> outputs = Lists.newArrayList();
1✔
1345

1346
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
1347
        for (T instance : mixedIngredients.getInstances(ingredientComponent)) {
1✔
1348
            // Try to stack this instance with an existing prototype
1349
            boolean stacked = false;
1✔
1350
            ListIterator<IPrototypedIngredient<T, M>> existingIt = outputs.listIterator();
1✔
1351
            while(existingIt.hasNext()) {
1✔
1352
                IPrototypedIngredient<T, M> prototypedIngredient = existingIt.next();
1✔
1353
                if (matcher.matches(instance, prototypedIngredient.getPrototype(),
1✔
1354
                        prototypedIngredient.getCondition())) {
1✔
1355
                    T stackedInstance = matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1356
                            matcher.getQuantity(prototypedIngredient.getPrototype())
1✔
1357
                                    + matcher.getQuantity(instance));
1✔
1358
                    existingIt.set(new PrototypedIngredient<>(ingredientComponent, stackedInstance,
1✔
1359
                            prototypedIngredient.getCondition()));
1✔
1360
                    stacked = true;
1✔
1361
                    break;
1✔
1362
                }
1363
            }
1✔
1364

1365
            // If not possible, just append it to the list
1366
            if (!stacked) {
1✔
1367
                outputs.add(new PrototypedIngredient<>(ingredientComponent, instance,
1✔
1368
                        matcher.getExactMatchNoQuantityCondition()));
1✔
1369
            }
1370
        }
1✔
1371

1372
        return outputs;
1✔
1373
    }
1374

1375
    /**
1376
     * Compress the given missing ingredients so that equal instances just have an incremented quantity.
1377
     *
1378
     * @param missingIngredients The missing ingredients.
1379
     * @param <T> The instance type.
1380
     * @param <M> The matching condition parameter.
1381
     * @return A new missing ingredients object.
1382
     */
1383
    public static <T, M> MissingIngredients<T, M> compressMissingIngredients(MissingIngredients<T, M> missingIngredients) {
1384
        // Index identical missing ingredients in a map, to group them by quantity
1385
        Map<MissingIngredients.Element<T, M>, Long> elementsCompressedMap = Maps.newLinkedHashMap(); // Must be a linked map to maintain our order!!!
1✔
1386
        for (MissingIngredients.Element<T, M> element : missingIngredients.getElements()) {
1✔
1387
            elementsCompressedMap.merge(element, 1L, Long::sum);
1✔
1388
        }
1✔
1389

1390
        // Create a new missing ingredients list where we multiply the missing quantities
1391
        List<MissingIngredients.Element<T, M>> elementsCompressed = Lists.newArrayList();
1✔
1392
        for (Map.Entry<MissingIngredients.Element<T, M>, Long> entry : elementsCompressedMap.entrySet()) {
1✔
1393
            Long quantity = entry.getValue();
1✔
1394
            if (quantity == 1L || entry.getKey().isInputReusable()) {
1✔
1395
                elementsCompressed.add(entry.getKey());
1✔
1396
            } else {
1397
                MissingIngredients.Element<T, M> elementOld = entry.getKey();
1✔
1398
                MissingIngredients.Element<T, M> elementNewQuantity = new MissingIngredients.Element<>(
1✔
1399
                        elementOld.getAlternatives().stream()
1✔
1400
                                .map(alt -> new MissingIngredients.PrototypedWithRequested<>(alt.getRequestedPrototype(), alt.getQuantityMissing() * quantity))
1✔
1401
                                .toList(),
1✔
1402
                        elementOld.isInputReusable()
1✔
1403
                );
1404
                elementsCompressed.add(elementNewQuantity);
1✔
1405
            }
1406
        }
1✔
1407
        return new MissingIngredients<>(elementsCompressed);
1✔
1408
    }
1409

1410
    /**
1411
     * Create a collection of prototypes from the given recipe's outputs.
1412
     *
1413
     * Equal prototypes will be stacked.
1414
     *
1415
     * @param recipe A recipe.
1416
     * @return A map from ingredient component types to their list of prototypes.
1417
     */
1418
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> getRecipeOutputs(IRecipeDefinition recipe) {
1419
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> outputs = Maps.newHashMap();
1✔
1420

1421
        IMixedIngredients mixedIngredients = recipe.getOutput();
1✔
1422
        for (IngredientComponent ingredientComponent : mixedIngredients.getComponents()) {
1✔
1423
            outputs.put(ingredientComponent, getCompressedIngredients(ingredientComponent, mixedIngredients));
1✔
1424
        }
1✔
1425

1426
        return outputs;
1✔
1427
    }
1428

1429
    /**
1430
     * Creates a new recipe outputs object with all ingredient quantities multiplied by the given amount.
1431
     * @param recipeOutputs A recipe objects holder.
1432
     * @param amount An amount to multiply all instances by.
1433
     * @return A new recipe objects holder.
1434
     */
1435
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> multiplyRecipeOutputs(
1436
            Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> recipeOutputs, int amount) {
1437
        if (amount == 1) {
1✔
1438
            return recipeOutputs;
1✔
1439
        }
1440

1441
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> newRecipeOutputs = Maps.newIdentityHashMap();
1✔
1442
        for (Map.Entry<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> entry : recipeOutputs.entrySet()) {
1✔
1443
            newRecipeOutputs.put(entry.getKey(), multiplyPrototypedIngredients((List) entry.getValue(), amount));
1✔
1444
        }
1✔
1445
        return newRecipeOutputs;
1✔
1446
    }
1447

1448
    /**
1449
     * Multiply the quantity of a given prototyped ingredient list with the given amount.
1450
     * @param prototypedIngredients A prototyped ingredient list.
1451
     * @param amount An amount to multiply by.
1452
     * @param <T> The instance type.
1453
     * @param <M> The matching condition parameter.
1454
     * @return A multiplied prototyped ingredient list.
1455
     */
1456
    public static <T, M> List<IPrototypedIngredient<T, M>> multiplyPrototypedIngredients(Collection<IPrototypedIngredient<T, M>> prototypedIngredients,
1457
                                                                                         long amount) {
1458
        return prototypedIngredients
1✔
1459
                .stream()
1✔
1460
                .map(p -> multiplyPrototypedIngredient(p, amount))
1✔
1461
                .collect(Collectors.toList());
1✔
1462
    }
1463

1464
    /**
1465
     * Multiply the quantity of a given prototyped ingredient with the given amount.
1466
     * @param prototypedIngredient A prototyped ingredient.
1467
     * @param amount An amount to multiply by.
1468
     * @param <T> The instance type.
1469
     * @param <M> The matching condition parameter.
1470
     * @return A multiplied prototyped ingredient.
1471
     */
1472
    public static <T, M> IPrototypedIngredient<T, M> multiplyPrototypedIngredient(IPrototypedIngredient<T, M> prototypedIngredient,
1473
                                                                                  long amount) {
1474
        IIngredientMatcher<T, M> matcher = prototypedIngredient.getComponent().getMatcher();
1✔
1475
        return new PrototypedIngredient<>(prototypedIngredient.getComponent(),
1✔
1476
                matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1477
                        matcher.getQuantity(prototypedIngredient.getPrototype()) * amount),
1✔
1478
                prototypedIngredient.getCondition());
1✔
1479
    }
1480

1481
    /**
1482
     * Merge two mixed ingredients in a new mixed ingredients object.
1483
     * Instances will be stacked.
1484
     * @param a A first mixed ingredients object.
1485
     * @param b A second mixed ingredients object.
1486
     * @return A merged mixed ingredients object.
1487
     */
1488
    public static IMixedIngredients mergeMixedIngredients(IMixedIngredients a, IMixedIngredients b) {
1489
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1490
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1491
        for (IngredientComponent<?, ?> component : a.getComponents()) {
1✔
1492
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1493
            groupings.put(component, grouping);
1✔
1494
            grouping.addAll(a.getInstances(component));
1✔
1495
        }
1✔
1496
        for (IngredientComponent<?, ?> component : b.getComponents()) {
1✔
1497
            IngredientCollectionQuantitativeGrouper grouping = groupings.get(component);
1✔
1498
            if (grouping == null) {
1✔
1499
                grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1500
                groupings.put(component, grouping);
1✔
1501
            }
1502
            grouping.addAll(b.getInstances(component));
1✔
1503
        }
1✔
1504

1505
        // Convert IngredientCollectionPrototypeMaps to lists
1506
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1507
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1508
            ingredients.put(entry.getKey(), Lists.newArrayList(entry.getValue()));
1✔
1509
        }
1✔
1510
        return new MixedIngredients(ingredients);
1✔
1511
    }
1512

1513
    /**
1514
     * Stack all ingredients in the given mixed ingredients object.
1515
     * @param mixedIngredients A mixed ingredients object.
1516
     * @return A new mixed ingredients object.
1517
     */
1518
    protected static IMixedIngredients compressMixedIngredients(IMixedIngredients mixedIngredients) {
1519
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1520
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1521
        for (IngredientComponent<?, ?> component : mixedIngredients.getComponents()) {
1✔
1522
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1523
            groupings.put(component, grouping);
1✔
1524
            grouping.addAll(mixedIngredients.getInstances(component));
1✔
1525
        }
1✔
1526

1527
        // Convert IngredientCollectionPrototypeMaps to lists
1528
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1529
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1530
            IIngredientMatcher matcher = entry.getKey().getMatcher();
1✔
1531
            List<?> values = entry.getValue()
1✔
1532
                    .stream()
1✔
1533
                    .filter(i -> !matcher.isEmpty(i))
1✔
1534
                    .collect(Collectors.toList());
1✔
1535
            if (!values.isEmpty()) {
1✔
1536
                ingredients.put(entry.getKey(), values);
1✔
1537
            }
1538
        }
1✔
1539
        return new MixedIngredients(ingredients);
1✔
1540
    }
1541

1542
    /**
1543
     * Insert the ingredients of the given ingredient component type into the target to make it start crafting.
1544
     *
1545
     * If insertion in non-simulation mode fails,
1546
     * ingredients will be re-inserted into the network.
1547
     *
1548
     * @param ingredientComponent The ingredient component type.
1549
     * @param capabilityProvider The target capability provider.
1550
     * @param side The target side.
1551
     * @param ingredients The ingredients to insert.
1552
     * @param storageFallback The storage to insert any failed ingredients back into. Can be null in simulation mode.
1553
     * @param simulate If insertion should be simulated.
1554
     * @param <T> The instance type.
1555
     * @param <M> The matching condition parameter.
1556
     * @return If all instances could be inserted.
1557
     */
1558
    public static <T, M> boolean insertIngredientCrafting(IngredientComponent<T, M> ingredientComponent,
1559
                                                          ICapabilityProvider capabilityProvider,
1560
                                                          @Nullable Direction side,
1561
                                                          IMixedIngredients ingredients,
1562
                                                          IIngredientComponentStorage<T, M> storageFallback,
1563
                                                          boolean simulate) {
1564
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
1565
        IIngredientComponentStorage<T, M> storage = ingredientComponent.getStorage(capabilityProvider, side);
×
1566
        List<T> instances = ingredients.getInstances(ingredientComponent);
×
1567
        List<T> failedInstances = Lists.newArrayList();
×
1568
        boolean ok = true;
×
1569
        for (T instance : instances) {
×
1570
            T remaining = storage.insert(instance, simulate);
×
1571
            if (!matcher.isEmpty(remaining)) {
×
1572
                ok = false;
×
1573
                if (!simulate) {
×
1574
                    failedInstances.add(remaining);
×
1575
                }
1576
            }
1577
        }
×
1578

1579
        // If we had failed insertions, try to insert them back into the network.
1580
        for (T instance : failedInstances) {
×
1581
            T remaining = storageFallback.insert(instance, false);
×
1582
            if (!matcher.isEmpty(remaining)) {
×
1583
                throw new IllegalStateException("Insertion for a crafting recipe failed" +
×
1584
                        "due to inconsistent insertion behaviour by destination in simulation " +
1585
                        "and non-simulation: " + capabilityProvider + ". Lost: " + instances);
1586
            }
1587
        }
×
1588

1589
        return ok;
×
1590
    }
1591

1592
    /**
1593
     * Insert the ingredients of all applicable ingredient component types into the target to make it start crafting.
1594
     *
1595
     * If insertion in non-simulation mode fails,
1596
     * ingredients will be re-inserted into the network.
1597
     *
1598
     * @param targetGetter A function to get the target position.
1599
     * @param ingredients The ingredients to insert.
1600
     * @param network The network.
1601
     * @param channel The channel.
1602
     * @param simulate If insertion should be simulated.
1603
     * @return If all instances could be inserted.
1604
     */
1605
    public static boolean insertCrafting(Function<IngredientComponent<?, ?>, PartPos> targetGetter,
1606
                                         IMixedIngredients ingredients,
1607
                                         INetwork network, int channel,
1608
                                         boolean simulate) {
1609
        Map<IngredientComponent<?, ?>, BlockEntity> tileMap = Maps.newIdentityHashMap();
×
1610

1611
        // First, check if we can find valid tiles for all ingredient components
1612
        for (IngredientComponent<?, ?> ingredientComponent : ingredients.getComponents()) {
×
1613
            BlockEntity tile = BlockEntityHelpers.get(targetGetter.apply(ingredientComponent).getPos(), BlockEntity.class).orElse(null);
×
1614
            if (tile != null) {
×
1615
                tileMap.put(ingredientComponent, tile);
×
1616
            } else {
1617
                return false;
×
1618
            }
1619
        }
×
1620

1621
        // Next, insert the instances into the respective tiles
1622
        boolean ok = true;
×
1623
        for (Map.Entry<IngredientComponent<?, ?>, BlockEntity> entry : tileMap.entrySet()) {
×
1624
            IIngredientComponentStorage<?, ?> storageNetwork = simulate ? null : getNetworkStorage(network, channel, entry.getKey(), false);
×
1625
            if (!insertIngredientCrafting((IngredientComponent) entry.getKey(), entry.getValue(),
×
1626
                    targetGetter.apply(entry.getKey()).getSide(), ingredients,
×
1627
                    storageNetwork, simulate)) {
1628
                ok = false;
×
1629
            }
1630
        }
×
1631

1632
        return ok;
×
1633
    }
1634

1635
    /**
1636
     * Split the given crafting job amount into new jobs with a given split factor.
1637
     * @param craftingJob A crafting job to split.
1638
     * @param splitFactor The number of jobs to split the job over.
1639
     * @param dependencyGraph The dependency graph that will be updated if there are dependencies in the original job.
1640
     * @param identifierGenerator An identifier generator for the crafting jobs ids.
1641
     * @return The newly created crafting jobs.
1642
     */
1643
    public static List<CraftingJob> splitCraftingJobs(CraftingJob craftingJob, int splitFactor,
1644
                                                      CraftingJobDependencyGraph dependencyGraph,
1645
                                                      IIdentifierGenerator identifierGenerator) {
1646
        splitFactor = Math.min(splitFactor, craftingJob.getAmount());
1✔
1647
        int division = craftingJob.getAmount() / splitFactor;
1✔
1648
        int modulus = craftingJob.getAmount() % splitFactor;
1✔
1649

1650
        // Clone original job into splitFactor jobs
1651
        List<CraftingJob> newCraftingJobs = Lists.newArrayList();
1✔
1652
        for (int i = 0; i < splitFactor; i++) {
1✔
1653
            CraftingJob clonedJob = craftingJob.clone(identifierGenerator);
1✔
1654
            newCraftingJobs.add(clonedJob);
1✔
1655

1656
            // Update amount
1657
            int newAmount = division;
1✔
1658
            if (modulus > 0) {
1✔
1659
                // No amounts will be lost, as modulus is guaranteed to be smaller than splitFactor
1660
                newAmount++;
1✔
1661
                modulus--;
1✔
1662
            }
1663
            clonedJob.setAmount(newAmount);
1✔
1664
        }
1665

1666
        // Collect dependency links
1667
        Collection<CraftingJob> originalDependencies = dependencyGraph.getDependencies(craftingJob);
1✔
1668
        Collection<CraftingJob> originalDependents = dependencyGraph.getDependents(craftingJob);
1✔
1669

1670
        // Remove dependency links to and from the original jobs
1671
        for (CraftingJob dependency : originalDependencies) {
1✔
1672
            craftingJob.removeDependency(dependency);
1✔
1673
            dependencyGraph.removeDependency(craftingJob.getId(), dependency.getId());
1✔
1674
        }
1✔
1675
        for (CraftingJob dependent : originalDependents) {
1✔
1676
            dependent.removeDependency(craftingJob);
1✔
1677
            dependencyGraph.removeDependency(dependent.getId(), craftingJob.getId());
1✔
1678
        }
1✔
1679

1680
        // Create dependency links to and from the new crafting jobs
1681
        for (CraftingJob dependency : originalDependencies) {
1✔
1682
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1683
                newCraftingJob.addDependency(dependency);
1✔
1684
                dependencyGraph.addDependency(newCraftingJob, dependency);
1✔
1685
            }
1✔
1686
        }
1✔
1687
        for (CraftingJob originalDependent : originalDependents) {
1✔
1688
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1689
                originalDependent.addDependency(newCraftingJob);
1✔
1690
                dependencyGraph.addDependency(originalDependent, newCraftingJob);
1✔
1691
            }
1✔
1692
        }
1✔
1693

1694
        return newCraftingJobs;
1✔
1695
    }
1696

1697
    /**
1698
     * Insert the given ingredients into the given storage networks.
1699
     * @param ingredients A collection of ingredients.
1700
     * @param storageGetter A storage network getter.
1701
     * @param simulate If insertion should be simulated.
1702
     * @return The remaining ingredients that were not inserted.
1703
     */
1704
    public static IMixedIngredients insertIngredients(IMixedIngredients ingredients,
1705
                                                      Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
1706
                                                      boolean simulate) {
1707
        Map<IngredientComponent<?, ?>, List<?>> remainingIngredients = Maps.newIdentityHashMap();
×
1708
        for (IngredientComponent<?, ?> component : ingredients.getComponents()) {
×
1709
            IIngredientComponentStorage storage = storageGetter.apply(component);
×
1710
            IIngredientMatcher matcher = component.getMatcher();
×
1711
            for (Object instance : ingredients.getInstances(component)) {
×
1712
                Object remainder = storage.insert(instance, simulate);
×
1713
                if (!matcher.isEmpty(remainder)) {
×
1714
                    List remainingInstances = remainingIngredients.get(component);
×
1715
                    if (remainingInstances == null) {
×
1716
                        remainingInstances = Lists.newArrayList();
×
1717
                        remainingIngredients.put(component, remainingInstances);
×
1718
                    }
1719
                    remainingInstances.add(instance);
×
1720
                }
1721
            }
×
1722
        }
×
1723
        return new MixedIngredients(remainingIngredients);
×
1724
    }
1725

1726
    /**
1727
     * Generates semi-unique IDs.
1728
     */
1729
    public static interface IIdentifierGenerator {
1730
        public int getNext();
1731
    }
1732

1733
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc