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

CyclopsMC / IntegratedCrafting / #479011713

12 Sep 2023 05:56PM UTC coverage: 24.982% (-0.2%) from 25.151%
#479011713

push

github-actions

rubensworks
Bump mod version

706 of 2826 relevant lines covered (24.98%)

0.25 hits per line

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

0.0
/src/main/java/org/cyclops/integratedcrafting/part/PartTypeInterfaceCrafting.java
1
package org.cyclops.integratedcrafting.part;
2

3
import com.google.common.collect.Lists;
4
import com.google.common.collect.MapMaker;
5
import it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap;
6
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
7
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
8
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
9
import it.unimi.dsi.fastutil.ints.IntArraySet;
10
import it.unimi.dsi.fastutil.ints.IntSet;
11
import net.minecraft.core.Direction;
12
import net.minecraft.nbt.CompoundTag;
13
import net.minecraft.nbt.ListTag;
14
import net.minecraft.nbt.Tag;
15
import net.minecraft.network.FriendlyByteBuf;
16
import net.minecraft.network.chat.Component;
17
import net.minecraft.network.chat.MutableComponent;
18
import net.minecraft.resources.ResourceLocation;
19
import net.minecraft.server.level.ServerPlayer;
20
import net.minecraft.world.MenuProvider;
21
import net.minecraft.world.SimpleContainer;
22
import net.minecraft.world.entity.player.Inventory;
23
import net.minecraft.world.entity.player.Player;
24
import net.minecraft.world.inventory.AbstractContainerMenu;
25
import net.minecraft.world.item.ItemStack;
26
import net.minecraft.world.level.block.state.BlockState;
27
import net.minecraftforge.common.MinecraftForge;
28
import net.minecraftforge.common.capabilities.Capability;
29
import net.minecraftforge.common.util.LazyOptional;
30
import org.apache.commons.lang3.tuple.Triple;
31
import org.apache.logging.log4j.Level;
32
import org.cyclops.commoncapabilities.api.capability.block.BlockCapabilities;
33
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
34
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeHandler;
35
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
36
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
37
import org.cyclops.commoncapabilities.api.ingredient.IPrototypedIngredient;
38
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
39
import org.cyclops.commoncapabilities.api.ingredient.IngredientInstanceWrapper;
40
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
41
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
42
import org.cyclops.cyclopscore.datastructure.DimPos;
43
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
44
import org.cyclops.cyclopscore.inventory.SimpleInventory;
45
import org.cyclops.cyclopscore.persist.nbt.NBTClassType;
46
import org.cyclops.integratedcrafting.Capabilities;
47
import org.cyclops.integratedcrafting.GeneralConfig;
48
import org.cyclops.integratedcrafting.IntegratedCrafting;
49
import org.cyclops.integratedcrafting.api.crafting.CraftingJob;
50
import org.cyclops.integratedcrafting.api.crafting.CraftingJobStatus;
51
import org.cyclops.integratedcrafting.api.crafting.ICraftingInterface;
52
import org.cyclops.integratedcrafting.api.crafting.ICraftingResultsSink;
53
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
54
import org.cyclops.integratedcrafting.capability.network.CraftingInterfaceConfig;
55
import org.cyclops.integratedcrafting.capability.network.CraftingNetworkConfig;
56
import org.cyclops.integratedcrafting.core.CraftingHelpers;
57
import org.cyclops.integratedcrafting.core.CraftingJobHandler;
58
import org.cyclops.integratedcrafting.core.CraftingProcessOverrides;
59
import org.cyclops.integratedcrafting.core.part.PartTypeCraftingBase;
60
import org.cyclops.integratedcrafting.ingredient.storage.IngredientComponentStorageSlottedInsertProxy;
61
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCrafting;
62
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCraftingSettings;
63
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
64
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
65
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
66
import org.cyclops.integrateddynamics.api.evaluate.variable.ValueDeseralizationContext;
67
import org.cyclops.integrateddynamics.api.network.INetwork;
68
import org.cyclops.integrateddynamics.api.network.INetworkIngredientsChannel;
69
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
70
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
71
import org.cyclops.integrateddynamics.api.part.IPartContainer;
72
import org.cyclops.integrateddynamics.api.part.PartPos;
73
import org.cyclops.integrateddynamics.api.part.PartTarget;
74
import org.cyclops.integrateddynamics.api.part.PrioritizedPartPos;
75
import org.cyclops.integrateddynamics.capability.network.PositionedAddonsNetworkIngredientsHandlerConfig;
76
import org.cyclops.integrateddynamics.core.evaluate.InventoryVariableEvaluator;
77
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeRecipe;
78
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
79
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
80
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
81
import org.cyclops.integrateddynamics.core.part.PartStateBase;
82
import org.cyclops.integrateddynamics.core.part.PartTypeBase;
83
import org.cyclops.integrateddynamics.core.part.event.PartVariableDrivenVariableContentsUpdatedEvent;
84

85
import javax.annotation.Nullable;
86
import java.util.Collection;
87
import java.util.Iterator;
88
import java.util.List;
89
import java.util.ListIterator;
90
import java.util.Map;
91
import java.util.Optional;
92

93
/**
94
 * Interface for item handlers.
95
 * @author rubensworks
96
 */
97
public class PartTypeInterfaceCrafting extends PartTypeCraftingBase<PartTypeInterfaceCrafting, PartTypeInterfaceCrafting.State> {
98

99
    public PartTypeInterfaceCrafting(String name) {
100
        super(name);
×
101
    }
×
102

103
    @Override
104
    public int getConsumptionRate(State state) {
105
        return state.getCraftingJobHandler().getProcessingCraftingJobs().size() * GeneralConfig.interfaceCraftingBaseConsumption;
×
106
    }
107

108
    @Override
109
    public Optional<MenuProvider> getContainerProvider(PartPos pos) {
110
        return Optional.of(new MenuProvider() {
×
111

112
            @Override
113
            public MutableComponent getDisplayName() {
114
                return Component.translatable(getTranslationKey());
×
115
            }
116

117
            @Override
118
            public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player playerEntity) {
119
                Triple<IPartContainer, PartTypeBase, PartTarget> data = PartHelpers.getContainerPartConstructionData(pos);
×
120
                PartTypeInterfaceCrafting.State partState = (PartTypeInterfaceCrafting.State) data.getLeft().getPartState(data.getRight().getCenter().getSide());
×
121
                return new ContainerPartInterfaceCrafting(id, playerInventory, partState.getInventoryVariables(),
×
122
                        Optional.of(data.getRight()), Optional.of(data.getLeft()), (PartTypeInterfaceCrafting) data.getMiddle());
×
123
            }
124
        });
125
    }
126

127
    @Override
128
    public void writeExtraGuiData(FriendlyByteBuf packetBuffer, PartPos pos, ServerPlayer player) {
129
        // Write inventory size
130
        IPartContainer partContainer = PartHelpers.getPartContainerChecked(pos);
×
131
        PartTypeInterfaceCrafting.State partState = (PartTypeInterfaceCrafting.State) partContainer.getPartState(pos.getSide());
×
132
        packetBuffer.writeInt(partState.getInventoryVariables().getContainerSize());
×
133

134
        super.writeExtraGuiData(packetBuffer, pos, player);
×
135
    }
×
136

137
    @Override
138
    public Optional<MenuProvider> getContainerProviderSettings(PartPos pos) {
139
        return Optional.of(new MenuProvider() {
×
140

141
            @Override
142
            public MutableComponent getDisplayName() {
143
                return Component.translatable(getTranslationKey());
×
144
            }
145

146
            @Override
147
            public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player playerEntity) {
148
                Triple<IPartContainer, PartTypeBase, PartTarget> data = PartHelpers.getContainerPartConstructionData(pos);
×
149
                return new ContainerPartInterfaceCraftingSettings(id, playerInventory, new SimpleContainer(0),
×
150
                        data.getRight(), Optional.of(data.getLeft()), data.getMiddle());
×
151
            }
152
        });
153
    }
154

155
    @Override
156
    protected PartTypeInterfaceCrafting.State constructDefaultState() {
157
        return new PartTypeInterfaceCrafting.State();
×
158
    }
159

160
    @Override
161
    public void afterNetworkReAlive(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
162
        super.afterNetworkReAlive(network, partNetwork, target, state);
×
163
        addTargetToNetwork(network, target, state);
×
164
    }
×
165

166
    @Override
167
    public void onNetworkRemoval(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
168
        super.onNetworkRemoval(network, partNetwork, target, state);
×
169
        removeTargetFromNetwork(network, target.getTarget(), state);
×
170
    }
×
171

172
    @Override
173
    public void onNetworkAddition(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
174
        super.onNetworkAddition(network, partNetwork, target, state);
×
175
        addTargetToNetwork(network, target, state);
×
176
    }
×
177

178
    @Override
179
    public void setPriorityAndChannel(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state, int priority, int channel) {
180
        // We need to do this because the crafting network is not automagically aware of the priority changes,
181
        // so we have to re-add it.
182
        removeTargetFromNetwork(network, target.getTarget(), state);
×
183
        super.setPriorityAndChannel(network, partNetwork, target, state, priority, channel);
×
184
        addTargetToNetwork(network, target, state);
×
185
    }
×
186

187
    protected Capability<ICraftingNetwork> getNetworkCapability() {
188
        return CraftingNetworkConfig.CAPABILITY;
×
189
    }
190

191
    protected void addTargetToNetwork(INetwork network, PartTarget pos, PartTypeInterfaceCrafting.State state) {
192
        network.getCapability(getNetworkCapability())
×
193
                .ifPresent(craftingNetwork -> {
×
194
                    int channelCrafting = state.getChannelCrafting();
×
195
                    state.setTarget(pos);
×
196
                    state.setNetworks(network, craftingNetwork, NetworkHelpers.getPartNetworkChecked(network), channelCrafting, ValueDeseralizationContext.of(pos.getCenter().getPos().getLevel(true)));
×
197
                    state.setShouldAddToCraftingNetwork(true);
×
198
                });
×
199
    }
×
200

201
    protected void removeTargetFromNetwork(INetwork network, PartPos pos, PartTypeInterfaceCrafting.State state) {
202
        ICraftingNetwork craftingNetwork = state.getCraftingNetwork();
×
203
        if (craftingNetwork != null) {
×
204
            network.getCapability(getNetworkCapability())
×
205
                    .ifPresent(n -> n.removeCraftingInterface(state.getChannelCrafting(), state));
×
206
        }
207
        state.setNetworks(null, null, null, -1, null);
×
208
        state.setTarget(null);
×
209
    }
×
210

211
    @Override
212
    public boolean isUpdate(State state) {
213
        return true;
×
214
    }
215

216
    @Override
217
    public int getMinimumUpdateInterval(State state) {
218
        return state.getDefaultUpdateInterval();
×
219
    }
220

221
    @Override
222
    public void update(INetwork network, IPartNetwork partNetwork, PartTarget target, State state) {
223
        super.update(network, partNetwork, target, state);
×
224

225
        // Init network data in part state if it has not been done yet.
226
        // This can occur when the part chunk is being reloaded.
227
        if (state.getCraftingNetwork() == null) {
×
228
            addTargetToNetwork(network, target, state);
×
229
        }
230

231
        int channel = state.getChannelCrafting();
×
232

233
        // Update the network data in the part state
234
        if (state.shouldAddToCraftingNetwork()) {
×
235
            ICraftingNetwork craftingNetwork = network.getCapability(getNetworkCapability()).orElse(null);
×
236
            craftingNetwork.addCraftingInterface(channel, state);
×
237
            state.setShouldAddToCraftingNetwork(false);
×
238
        }
239

240
        // Push any pending output ingredients into the network
241
        state.flushInventoryOutputBuffer(network);
×
242

243
        // Block job ticking if there still are outputs in our crafting result buffer.
244
        if (state.getInventoryOutputBuffer().isEmpty()) {
×
245
            // Tick the job handler
246
            PartPos targetPos = state.getTarget().getTarget();
×
247
            state.getCraftingJobHandler().update(network, channel, targetPos);
×
248
        }
249

250
        // Reload recipes if needed
251
        IntSet slots = state.getDelayedRecipeReloads();
×
252
        if (!slots.isEmpty()) {
×
253
            ICraftingNetwork craftingNetwork = network.getCapability(getNetworkCapability()).orElse(null);
×
254
            if (craftingNetwork != null) {
×
255
                for (Integer slot : slots) {
×
256
                    // Remove the old recipe from the network
257
                    Int2ObjectMap<IRecipeDefinition> recipes = state.getRecipesIndexed();
×
258
                    IRecipeDefinition oldRecipe = recipes.get(slot);
×
259
                    if (oldRecipe != null) {
×
260
                        craftingNetwork.removeCraftingInterfaceRecipe(channel, state, oldRecipe);
×
261
                    }
262

263
                    // Reload the recipe in the slot
264
                    state.reloadRecipe(slot);
×
265

266
                    // Add the new recipe to the network
267
                    IRecipeDefinition newRecipe = recipes.get(slot);
×
268
                    if (newRecipe != null) {
×
269
                        craftingNetwork.addCraftingInterfaceRecipe(channel, state, newRecipe);
×
270
                    }
271
                }
×
272
            }
273
            slots.clear();
×
274
        }
275
    }
×
276

277
    @Nullable
278
    protected static <T, M> IngredientInstanceWrapper<T, M> insertIntoNetwork(IngredientInstanceWrapper<T, M> wrapper,
279
                                                                              INetwork network, int channel) {
280
        IPositionedAddonsNetworkIngredients<T, M> storageNetwork = wrapper.getComponent()
×
281
                .getCapability(PositionedAddonsNetworkIngredientsHandlerConfig.CAPABILITY)
×
282
                .map(n -> (IPositionedAddonsNetworkIngredients<T, M>) n.getStorage(network).orElse(null))
×
283
                .orElse(null);
×
284
        if (storageNetwork != null) {
×
285
            IIngredientComponentStorage<T, M> storage = storageNetwork.getChannel(channel);
×
286
            T remaining = storage.insert(wrapper.getInstance(), false);
×
287
            if (wrapper.getComponent().getMatcher().isEmpty(remaining)) {
×
288
                return null;
×
289
            } else {
290
                return new IngredientInstanceWrapper<>(wrapper.getComponent(), remaining);
×
291
            }
292
        }
293
        return wrapper;
×
294
    }
295

296
    @Override
297
    public void addDrops(PartTarget target, State state, List<ItemStack> itemStacks, boolean dropMainElement, boolean saveState) {
298
        // Drop any remaining output ingredients (only items)
299
        for (IngredientInstanceWrapper<?, ?> ingredientInstanceWrapper : state.getInventoryOutputBuffer()) {
×
300
            if (ingredientInstanceWrapper.getComponent() == IngredientComponent.ITEMSTACK) {
×
301
                itemStacks.add((ItemStack) ingredientInstanceWrapper.getInstance());
×
302
            }
303
        }
×
304
        state.getInventoryOutputBuffer().clear();
×
305

306
        // Drop the stored variables
307
        for(int i = 0; i < state.getInventoryVariables().getContainerSize(); i++) {
×
308
            ItemStack itemStack = state.getInventoryVariables().getItem(i);
×
309
            if(!itemStack.isEmpty()) {
×
310
                itemStacks.add(itemStack);
×
311
            }
312
        }
313
        state.getInventoryVariables().clearContent();
×
314

315
        super.addDrops(target, state, itemStacks, dropMainElement, saveState);
×
316
    }
×
317

318
    public static class State extends PartStateBase<PartTypeInterfaceCrafting>
319
            implements ICraftingInterface, ICraftingResultsSink {
320

321
        private final CraftingJobHandler craftingJobHandler;
322
        private final SimpleInventory inventoryVariables;
323
        private final List<InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe>> variableEvaluators;
324
        private final List<IngredientInstanceWrapper<?, ?>> inventoryOutputBuffer;
325
        private final Int2ObjectMap<MutableComponent> recipeSlotMessages;
326
        private final Int2BooleanMap recipeSlotValidated;
327
        private final IntSet delayedRecipeReloads;
328
        private final Map<IVariable, Boolean> variableListeners;
329
        private int channelCrafting = 0;
×
330
        private boolean disableCraftingCheck = false;
×
331

332
        private final Int2ObjectMap<IRecipeDefinition> currentRecipes;
333
        private PartTarget target = null;
×
334
        private INetwork network = null;
×
335
        private ICraftingNetwork craftingNetwork = null;
×
336
        private IPartNetwork partNetwork = null;
×
337
        private int channel = -1;
×
338
        private ValueDeseralizationContext valueDeseralizationContext;
339
        private boolean shouldAddToCraftingNetwork = false;
×
340
        private Player lastPlayer;
341

342
        public State() {
×
343
            this.craftingJobHandler = new CraftingJobHandler(1, true,
×
344
                    CraftingProcessOverrides.REGISTRY.getCraftingProcessOverrides(), this);
×
345
            this.inventoryVariables = new SimpleInventory(9, 1);
×
346
            this.inventoryVariables.addDirtyMarkListener(this);
×
347
            this.variableEvaluators = Lists.newArrayList();
×
348
            this.inventoryOutputBuffer = Lists.newArrayList();
×
349
            this.recipeSlotMessages = new Int2ObjectArrayMap<>();
×
350
            this.recipeSlotValidated = new Int2BooleanArrayMap();
×
351
            this.delayedRecipeReloads = new IntArraySet();
×
352
            this.variableListeners = new MapMaker().weakKeys().makeMap();
×
353
            this.currentRecipes = new Int2ObjectArrayMap<>();
×
354
        }
×
355

356
        @Override
357
        protected int getDefaultUpdateInterval() {
358
            return GeneralConfig.minCraftingInterfaceUpdateFreq;
×
359
        }
360

361
        /**
362
         * @return The inner variables inventory
363
         */
364
        public SimpleInventory getInventoryVariables() {
365
            return this.inventoryVariables;
×
366
        }
367

368
        @Override
369
        public void writeToNBT(CompoundTag tag) {
370
            super.writeToNBT(tag);
×
371
            inventoryVariables.writeToNBT(tag, "variables");
×
372

373
            ListTag instanceTags = new ListTag();
×
374
            for (IngredientInstanceWrapper instanceWrapper : inventoryOutputBuffer) {
×
375
                CompoundTag instanceTag = new CompoundTag();
×
376
                instanceTag.putString("component", IngredientComponent.REGISTRY.getKey(instanceWrapper.getComponent()).toString());
×
377
                instanceTag.put("instance", instanceWrapper.getComponent().getSerializer().serializeInstance(instanceWrapper.getInstance()));
×
378
                instanceTags.add(instanceTag);
×
379
            }
×
380
            tag.put("inventoryOutputBuffer", instanceTags);
×
381

382
            this.craftingJobHandler.writeToNBT(tag);
×
383
            tag.putInt("channelCrafting", channelCrafting);
×
384

385
            CompoundTag recipeSlotErrorsTag = new CompoundTag();
×
386
            for (Int2ObjectMap.Entry<MutableComponent> entry : this.recipeSlotMessages.int2ObjectEntrySet()) {
×
387
                NBTClassType.writeNbt(MutableComponent.class, String.valueOf(entry.getIntKey()), entry.getValue(), recipeSlotErrorsTag);
×
388
            }
×
389
            tag.put("recipeSlotMessages", recipeSlotErrorsTag);
×
390

391
            CompoundTag recipeSlotValidatedTag = new CompoundTag();
×
392
            for (Int2BooleanMap.Entry entry : this.recipeSlotValidated.int2BooleanEntrySet()) {
×
393
                recipeSlotValidatedTag.putBoolean(String.valueOf(entry.getIntKey()), entry.getBooleanValue());
×
394
            }
×
395
            tag.put("recipeSlotValidated", recipeSlotValidatedTag);
×
396

397
            tag.putBoolean("disableCraftingCheck", disableCraftingCheck);
×
398
        }
×
399

400
        @Override
401
        public void readFromNBT(ValueDeseralizationContext valueDeseralizationContext, CompoundTag tag) {
402
            super.readFromNBT(valueDeseralizationContext, tag);
×
403
            inventoryVariables.readFromNBT(tag, "variables");
×
404

405
            this.inventoryOutputBuffer.clear();
×
406
            for (Tag instanceTagRaw : tag.getList("inventoryOutputBuffer", Tag.TAG_COMPOUND)) {
×
407
                CompoundTag instanceTag = (CompoundTag) instanceTagRaw;
×
408
                String componentName = instanceTag.getString("component");
×
409
                IngredientComponent<?, ?> component = IngredientComponent.REGISTRY.getValue(new ResourceLocation(componentName));
×
410
                this.inventoryOutputBuffer.add(new IngredientInstanceWrapper(component,
×
411
                        component.getSerializer().deserializeInstance(instanceTag.get("instance"))));
×
412
            }
×
413

414
            this.craftingJobHandler.readFromNBT(tag);
×
415
            this.channelCrafting = tag.getInt("channelCrafting");
×
416

417
            this.recipeSlotMessages.clear();
×
418
            CompoundTag recipeSlotErrorsTag = tag.getCompound("recipeSlotMessages");
×
419
            for (String slot : recipeSlotErrorsTag.getAllKeys()) {
×
420
                MutableComponent unlocalizedString = NBTClassType.readNbt(MutableComponent.class, slot, recipeSlotErrorsTag);
×
421
                this.recipeSlotMessages.put(Integer.parseInt(slot), unlocalizedString);
×
422
            }
×
423

424
            this.recipeSlotValidated.clear();
×
425
            CompoundTag recipeSlotValidatedTag = tag.getCompound("recipeSlotValidated");
×
426
            for (String slot : recipeSlotValidatedTag.getAllKeys()) {
×
427
                this.recipeSlotValidated.put(Integer.parseInt(slot), recipeSlotValidatedTag.getBoolean(slot));
×
428
            }
×
429

430
            this.disableCraftingCheck = tag.getBoolean("disableCraftingCheck");
×
431
        }
×
432

433
        public void setChannelCrafting(int channelCrafting) {
434
            if (this.channelCrafting != channelCrafting) {
×
435
                // Unregister from the network
436
                if (craftingNetwork != null) {
×
437
                    craftingNetwork.removeCraftingInterface(this.channelCrafting, this);
×
438
                }
439

440
                // Update the channel
441
                this.channelCrafting = channelCrafting;
×
442

443
                // Re-register to the network
444
                if (craftingNetwork != null) {
×
445
                    craftingNetwork.addCraftingInterface(this.channelCrafting, this);
×
446
                }
447

448
                sendUpdate();
×
449
            }
450
        }
×
451

452
        public int getChannelCrafting() {
453
            return channelCrafting;
×
454
        }
455

456
        public void reloadRecipes() {
457
            this.currentRecipes.clear();
×
458
            this.recipeSlotMessages.clear();
×
459
            this.recipeSlotValidated.clear();
×
460
            variableEvaluators.clear();
×
461
            for (int i = 0; i < getInventoryVariables().getContainerSize(); i++) {
×
462
                int slot = i;
×
463
                variableEvaluators.add(new InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe>(
×
464
                        getInventoryVariables(), slot, valueDeseralizationContext, ValueTypes.OBJECT_RECIPE) {
×
465
                    @Override
466
                    public void onErrorsChanged() {
467
                        super.onErrorsChanged();
×
468
                        setLocalErrors(slot, getErrors());
×
469
                    }
×
470
                });
471
            }
472
            if (this.partNetwork != null) {
×
473
                for (int i = 0; i < getInventoryVariables().getContainerSize(); i++) {
×
474
                    reloadRecipe(i);
×
475
                }
476
            }
477
        }
×
478

479
        private void setLocalErrors(int slot, List<MutableComponent> errors) {
480
            if (errors.isEmpty()) {
×
481
                if (this.recipeSlotMessages.size() > slot) {
×
482
                    this.recipeSlotMessages.remove(slot);
×
483
                }
484
            } else {
485
                this.recipeSlotMessages.put(slot, errors.get(0));
×
486
            }
487
        }
×
488

489
        protected void reloadRecipe(int slot) {
490
            this.currentRecipes.remove(slot);
×
491
            if (this.recipeSlotMessages.size() > slot) {
×
492
                this.recipeSlotMessages.remove(slot);
×
493
            }
494
            if (this.recipeSlotValidated.size() > slot) {
×
495
                this.recipeSlotValidated.remove(slot);
×
496
            }
497
            if (this.partNetwork != null) {
×
498
                InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe> evaluator = variableEvaluators.get(slot);
×
499
                evaluator.refreshVariable(network, false);
×
500
                IVariable<ValueObjectTypeRecipe.ValueRecipe> variable = evaluator.getVariable(network);
×
501
                if (variable != null) {
×
502
                    try {
503
                        // Refresh the recipe if variable is changed
504
                        // The map is needed because we only want to register the listener once for each variable
505
                        if (!this.variableListeners.containsKey(variable)) {
×
506
                            variable.addInvalidationListener(() -> {
×
507
                                this.variableListeners.remove(variable);
×
508
                                delayedReloadRecipe(slot);
×
509
                            });
×
510
                            this.variableListeners.put(variable, true);
×
511
                        }
512

513
                        IValue value = variable.getValue();
×
514
                        if (value.getType() == ValueTypes.OBJECT_RECIPE) {
×
515
                            Optional<IRecipeDefinition> recipeWrapper = ((ValueObjectTypeRecipe.ValueRecipe) value).getRawValue();
×
516
                            if (recipeWrapper.isPresent()) {
×
517
                                IRecipeDefinition recipe = recipeWrapper.get();
×
518
                                if (!GeneralConfig.validateRecipesCraftingInterface || this.disableCraftingCheck || isValid(recipe)) {
×
519
                                    this.currentRecipes.put(slot, recipe);
×
520
                                    this.recipeSlotValidated.put(slot, true);
×
521
                                    this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.valid"));
×
522
                                } else {
523
                                    this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.invalid"));
×
524
                                }
525
                            }
526
                        } else {
×
527
                            this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.norecipe"));
×
528
                        }
529
                    } catch (EvaluationException e) {
×
530
                        this.recipeSlotMessages.put(slot, e.getErrorMessage());
×
531
                    }
×
532
                } else {
533
                    this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.norecipe"));
×
534
                }
535

536
                try {
537
                    IPartNetwork partNetwork = NetworkHelpers.getPartNetworkChecked(network);
×
538
                    MinecraftForge.EVENT_BUS.post(new PartVariableDrivenVariableContentsUpdatedEvent<>(network,
×
539
                            partNetwork, getTarget(),
×
540
                            PartTypes.INTERFACE_CRAFTING, this, lastPlayer, variable,
541
                            variable != null ? variable.getValue() : null));
×
542
                } catch (EvaluationException e) {
×
543
                    // Ignore error
544
                }
×
545
            }
546
            sendUpdate();
×
547
        }
×
548

549
        public void setLastPlayer(Player lastPlayer) {
550
            this.lastPlayer = lastPlayer;
×
551
        }
×
552

553
        private void delayedReloadRecipe(int slot) {
554
            this.delayedRecipeReloads.add(slot);
×
555
        }
×
556

557

558
        private boolean isValid(IRecipeDefinition recipe) {
559
            DimPos dimPos = getTarget().getTarget().getPos();
×
560
            Direction side = getTarget().getTarget().getSide();
×
561
            IRecipeHandler recipeHandler = BlockEntityHelpers.getCapability(dimPos.getLevel(true), dimPos.getBlockPos(), side, Capabilities.RECIPE_HANDLER).orElse(null);
×
562
            if (recipeHandler == null) {
×
563
                BlockState blockState = dimPos.getLevel(true).getBlockState(dimPos.getBlockPos());
×
564
                recipeHandler = BlockCapabilities.getInstance().getCapability(blockState, Capabilities.RECIPE_HANDLER,
×
565
                        dimPos.getLevel(true), dimPos.getBlockPos(), side)
×
566
                .orElse(null);
×
567
            }
568
            if (recipeHandler != null) {
×
569
                IMixedIngredients simulatedOutput = recipeHandler.simulate(MixedIngredients.fromRecipeInput(recipe));
×
570
                if (simulatedOutput != null && !simulatedOutput.isEmpty()) {
×
571
                    if (recipe.getOutput().containsAll(simulatedOutput)) {
×
572
                        return true;
×
573
                    } else {
574
                        if (GeneralConfig.logRecipeValidationFailures) {
×
575
                            IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: incompatible recipe output and simulated output:\nRecipe output: " + recipe.getOutput() + "\nSimulated output: " + simulatedOutput);
×
576
                        }
577
                        return false;
×
578
                    }
579
                }
580
                if (GeneralConfig.logRecipeValidationFailures) {
×
581
                    IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: No output was obtained when simulating a recipe\n" + recipe);
×
582
                }
583
                return false;
×
584
            }
585
            return true; // No recipe handler capability is present, so we can't confirm that the recipe will work.
×
586
        }
587

588
        @Override
589
        public void onDirty() {
590
            super.onDirty();
×
591

592
            // Unregister from the network, when all old recipes are still in place
593
            if (craftingNetwork != null) {
×
594
                craftingNetwork.removeCraftingInterface(channelCrafting, this);
×
595
            }
596

597
            // Recalculate recipes
598
            if (getTarget() != null && !getTarget().getCenter().getPos().getLevel(true).isClientSide) {
×
599
                reloadRecipes();
×
600
            }
601

602
            // Re-register to the network, to force an update for all new recipes
603
            if (craftingNetwork != null) {
×
604
                craftingNetwork.addCraftingInterface(channelCrafting, this);
×
605
            }
606
        }
×
607

608
        public void setTarget(PartTarget target) {
609
            this.target = target;
×
610
        }
×
611

612
        public PartTarget getTarget() {
613
            return target;
×
614
        }
615

616
        public void setNetworks(@Nullable INetwork network, @Nullable ICraftingNetwork craftingNetwork,
617
                                @Nullable IPartNetwork partNetwork, int channel,
618
                                @Nullable ValueDeseralizationContext valueDeseralizationContext) {
619
            this.network = network;
×
620
            this.craftingNetwork = craftingNetwork;
×
621
            this.partNetwork = partNetwork;
×
622
            this.channel = channel;
×
623
            this.valueDeseralizationContext = valueDeseralizationContext;
×
624
            reloadRecipes();
×
625
            if (network != null) {
×
626
                this.getCraftingJobHandler().reRegisterObservers(network);
×
627
            }
628
        }
×
629

630
        public ICraftingNetwork getCraftingNetwork() {
631
            return craftingNetwork;
×
632
        }
633

634
        @Override
635
        public int getChannel() {
636
            return channel;
×
637
        }
638

639
        @Override
640
        public Collection<IRecipeDefinition> getRecipes() {
641
            return this.currentRecipes.values();
×
642
        }
643

644
        public Int2ObjectMap<IRecipeDefinition> getRecipesIndexed() {
645
            return currentRecipes;
×
646
        }
647

648
        @Override
649
        public boolean canScheduleCraftingJobs() {
650
            return getCraftingJobHandler().canScheduleCraftingJobs();
×
651
        }
652

653
        @Override
654
        public void scheduleCraftingJob(CraftingJob craftingJob) {
655
            getCraftingJobHandler().scheduleCraftingJob(craftingJob);
×
656
        }
×
657

658
        @Override
659
        public int getCraftingJobsCount() {
660
            return this.craftingJobHandler.getAllCraftingJobs().size();
×
661
        }
662

663
        @Override
664
        public Iterator<CraftingJob> getCraftingJobs() {
665
            return this.craftingJobHandler.getAllCraftingJobs().values().iterator();
×
666
        }
667

668
        @Override
669
        public List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> getPendingCraftingJobOutputs(int craftingJobId) {
670
            List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> pending = this.craftingJobHandler.getProcessingCraftingJobsPendingIngredients().get(craftingJobId);
×
671
            if (pending == null) {
×
672
                pending = Lists.newArrayList();
×
673
            }
674
            return pending;
×
675
        }
676

677
        @Override
678
        public CraftingJobStatus getCraftingJobStatus(ICraftingNetwork network, int channel, int craftingJobId) {
679
            return craftingJobHandler.getCraftingJobStatus(network, channel, craftingJobId);
×
680
        }
681

682
        @Override
683
        public void cancelCraftingJob(int channel, int craftingJobId) {
684
            craftingJobHandler.markCraftingJobFinished(craftingJobId);
×
685
        }
×
686

687
        @Override
688
        public PrioritizedPartPos getPosition() {
689
            return PrioritizedPartPos.of(getTarget().getCenter(), getPriority());
×
690
        }
691

692
        public CraftingJobHandler getCraftingJobHandler() {
693
            return craftingJobHandler;
×
694
        }
695

696
        public boolean shouldAddToCraftingNetwork() {
697
            return shouldAddToCraftingNetwork;
×
698
        }
699

700
        public void setShouldAddToCraftingNetwork(boolean shouldAddToCraftingNetwork) {
701
            this.shouldAddToCraftingNetwork = shouldAddToCraftingNetwork;
×
702
        }
×
703

704
        public List<IngredientInstanceWrapper<?, ?>> getInventoryOutputBuffer() {
705
            return inventoryOutputBuffer;
×
706
        }
707

708
        @Override
709
        public <T> LazyOptional<T> getCapability(Capability<T> capability, INetwork network, IPartNetwork partNetwork, PartTarget target) {
710
            if (capability == CraftingInterfaceConfig.CAPABILITY) {
×
711
                return LazyOptional.of(() -> this).cast();
×
712
            }
713

714
            // Expose the whole storage
715
            if (this.network != null) {
×
716
                IngredientComponent<?, ?> ingredientComponent = IngredientComponent.getIngredientComponentForStorageCapability(capability);
×
717
                if (ingredientComponent != null) {
×
718
                    T cap = wrapStorageCapability(capability, ingredientComponent);
×
719
                    if (cap != null) {
×
720
                        return LazyOptional.of(() -> cap);
×
721
                    }
722
                }
723
            }
724

725
            return super.getCapability(capability, network, partNetwork, target);
×
726
        }
727

728
        protected <C, T, M> C wrapStorageCapability(Capability<C> capability, IngredientComponent<T, M> ingredientComponent) {
729
            IIngredientComponentStorage<T, M> storage = CraftingHelpers.getNetworkStorage(this.network, this.channelCrafting,
×
730
                    ingredientComponent, false);
731

732
            // Don't allow extraction, only insertion
733
            storage = new IngredientComponentStorageSlottedInsertProxy<>(storage);
×
734

735
            return ingredientComponent.getStorageWrapperHandler(capability).wrapStorage(storage);
×
736
        }
737

738
        @Override
739
        public <T, M> void addResult(IngredientComponent<T, M> ingredientComponent, T instance) {
740
            this.getInventoryOutputBuffer().add(new IngredientInstanceWrapper<>(ingredientComponent, instance));
×
741

742
            // Try to flush buffer immediately
743
            if (this.network != null) {
×
744
                this.flushInventoryOutputBuffer(this.network);
×
745
            }
746
        }
×
747

748
        public void setIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent, Direction side) {
749
            if (getTarget().getTarget().getSide() == side) {
×
750
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, null);
×
751
            } else {
752
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, side);
×
753
            }
754
            sendUpdate();
×
755
        }
×
756

757
        public Direction getIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent) {
758
            Direction side = craftingJobHandler.getIngredientComponentTarget(ingredientComponent);
×
759
            if (side == null) {
×
760
                side = getTarget().getTarget().getSide();
×
761
            }
762
            return side;
×
763
        }
764

765
        public boolean isRecipeSlotValid(int slot) {
766
            return this.recipeSlotValidated.containsKey(slot);
×
767
        }
768

769
        @Nullable
770
        public MutableComponent getRecipeSlotUnlocalizedMessage(int slot) {
771
            return this.recipeSlotMessages.get(slot);
×
772
        }
773

774
        public IntSet getDelayedRecipeReloads() {
775
            return delayedRecipeReloads;
×
776
        }
777

778
        public void setDisableCraftingCheck(boolean disableCraftingCheck) {
779
            if (disableCraftingCheck != this.disableCraftingCheck) {
×
780
                this.disableCraftingCheck = disableCraftingCheck;
×
781

782
                this.sendUpdate();
×
783
            }
784
        }
×
785

786
        public boolean isDisableCraftingCheck() {
787
            return disableCraftingCheck;
×
788
        }
789

790
        public void flushInventoryOutputBuffer(INetwork network) {
791
            // Try to insert each ingredient in the buffer into the network.
792
            boolean changed = false;
×
793
            ListIterator<IngredientInstanceWrapper<?, ?>> outputBufferIt = this.getInventoryOutputBuffer().listIterator();
×
794
            while (outputBufferIt.hasNext()) {
×
795
                IngredientInstanceWrapper<?, ?> oldWrapper = outputBufferIt.next();
×
796

797
                // Force observation before insertion (see #98 on why this is necessary)
798
                this.forceObservationOnInsertable(oldWrapper);
×
799

800
                IngredientInstanceWrapper<?, ?> newWrapper = insertIntoNetwork(oldWrapper,
×
801
                        network, this.getChannelCrafting());
×
802
                if (newWrapper != oldWrapper) {
×
803
                    changed = true;
×
804
                }
805
                if (newWrapper == null) {
×
806
                    outputBufferIt.remove();
×
807
                } else {
808
                    outputBufferIt.set(newWrapper);
×
809
                }
810
            }
×
811

812
            // If at least one ingredient was inserted, force a sync observer update in the network.
813
            if (changed) {
×
814
                CraftingHelpers.beforeCalculateCraftingJobs(network, getChannelCrafting());
×
815
            }
816
        }
×
817

818
        /**
819
         * Iterate over all positions that *could* accept the given instance,
820
         * and force an observation over them.
821
         *
822
         * This is necessary to ensure that we have the latest state indexed right before insertion.
823
         * This allows us to force another observation right after the insertion,
824
         * which will guarantee that we will track the expected diff events as result.
825
         *
826
         * @param oldWrapper The ingredient to attempt to insert (simulated).
827
         * @param <T> Ingredient type.
828
         * @param <M> Match flags.
829
         */
830
        protected <T, M> void forceObservationOnInsertable(IngredientInstanceWrapper<T, M> oldWrapper) {
831
            IIngredientMatcher<T, M> matcher = oldWrapper.getComponent().getMatcher();
×
832
            IPositionedAddonsNetworkIngredients<T, M> ingredientsNetwork = CraftingHelpers.getIngredientsNetwork(network, oldWrapper.getComponent()).orElse(null);
×
833
            if (ingredientsNetwork != null) {
×
834
                boolean marked = false;
×
835
                INetworkIngredientsChannel<?, ?> ingredientsNetworkChannel = ingredientsNetwork.getChannelInternal(this.getChannelCrafting());
×
836
                T instance = oldWrapper.getInstance();
×
837
                for (PartPos position : ingredientsNetworkChannel.findNonFullPositions()) {
×
838
                    T instanceOut = ingredientsNetwork.getPositionedStorage(position).insert(instance, true);
×
839
                    if (!matcher.matchesExactly(instanceOut, instance)) {
×
840
                        marked = true;
×
841
                        instance = instanceOut;
×
842
                        ingredientsNetwork.scheduleObservationForced(this.getChannelCrafting(), position);
×
843
                        if (matcher.isEmpty(instance)) {
×
844
                            break;
×
845
                        }
846
                    }
847
                }
×
848

849
                if (marked || ingredientsNetwork.isObservationForcedPending(channel)) {
×
850
                    ingredientsNetwork.runObserverSync();
×
851
                }
852
            }
853
        }
×
854
    }
855
}
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