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

CyclopsMC / IntegratedDynamics / 20374407946

19 Dec 2025 03:19PM UTC coverage: 53.067% (-0.005%) from 53.072%
20374407946

push

github

rubensworks
Remove deprecated IIngredientComponentValueHandler

2852 of 8730 branches covered (32.67%)

Branch coverage included in aggregate %.

17389 of 29412 relevant lines covered (59.12%)

3.07 hits per line

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

42.54
/src/main/java/org/cyclops/integrateddynamics/core/network/IngredientChannelAdapter.java
1
package org.cyclops.integrateddynamics.core.network;
2

3
import com.google.common.collect.Lists;
4
import net.neoforged.neoforge.transfer.transaction.SnapshotJournal;
5
import net.neoforged.neoforge.transfer.transaction.Transaction;
6
import net.neoforged.neoforge.transfer.transaction.TransactionContext;
7
import org.apache.commons.lang3.tuple.Pair;
8
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
9
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
10
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
11
import org.cyclops.cyclopscore.datastructure.Wrapper;
12
import org.cyclops.cyclopscore.ingredient.collection.IIngredientMapMutable;
13
import org.cyclops.cyclopscore.ingredient.collection.IngredientHashMap;
14
import org.cyclops.integrateddynamics.api.network.INetworkIngredientsChannel;
15
import org.cyclops.integrateddynamics.api.network.IPartPosIteratorHandler;
16
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
17
import org.cyclops.integrateddynamics.api.network.PositionedAddonsNetworkIngredientsFilter;
18
import org.cyclops.integrateddynamics.api.part.PartPos;
19

20
import javax.annotation.Nonnull;
21
import java.util.Iterator;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.function.Supplier;
25

26
/**
27
 * An abstract {@link IIngredientComponentStorage} that wraps over a {@link IPositionedAddonsNetworkIngredients}.
28
 *
29
 * @param <T> The instance type.
30
 * @param <M> The matching condition parameter.
31
 */
32
public abstract class IngredientChannelAdapter<T, M> implements INetworkIngredientsChannel<T, M> {
33

34
    private final IPositionedAddonsNetworkIngredients<T, M> network;
35
    private final int channel;
36

37
    private boolean limitsEnabled;
38

39
    public IngredientChannelAdapter(PositionedAddonsNetworkIngredients<T, M> network, int channel) {
2✔
40
        this.network = network;
3✔
41
        this.channel = channel;
3✔
42

43
        this.limitsEnabled = true;
3✔
44
    }
1✔
45

46
    public void enableLimits() {
47
        this.limitsEnabled = true;
×
48
    }
×
49

50
    public void disableLimits() {
51
        this.limitsEnabled = false;
×
52
    }
×
53

54
    public IPositionedAddonsNetworkIngredients<T, M> getNetwork() {
55
        return network;
3✔
56
    }
57

58
    public int getChannel() {
59
        return channel;
3✔
60
    }
61

62
    @Override
63
    public IngredientComponent<T, M> getComponent() {
64
        return network.getComponent();
4✔
65
    }
66

67
    protected abstract Iterator<PartPos> getNonFullPositions();
68
    protected abstract Iterator<PartPos> getAllPositions();
69
    protected abstract Iterator<PartPos> getNonEmptyPositions();
70
    protected abstract Iterator<PartPos> getMatchingPositions(@Nonnull T prototype, M matchFlags);
71

72
    @Override
73
    public Iterable<PartPos> findNonFullPositions() {
74
        return () -> getPartPosIteratorData(this::getNonFullPositions, channel).getRight();
×
75
    }
76

77
    @Override
78
    public Iterable<PartPos> findAllPositions() {
79
        return () -> getPartPosIteratorData(this::getAllPositions, channel).getRight();
×
80
    }
81

82
    @Override
83
    public Iterable<PartPos> findNonEmptyPositions() {
84
        return () -> getPartPosIteratorData(this::getNonEmptyPositions, channel).getRight();
×
85
    }
86

87
    @Override
88
    public Iterable<PartPos> findMatchingPositions(@Nonnull T prototype, M matchFlags) {
89
        return () -> getPartPosIteratorData(() -> this.getMatchingPositions(prototype, matchFlags), channel).getRight();
×
90
    }
91

92
    @Override
93
    public long getMaxQuantity() {
94
        long sum = 0;
2✔
95
        Iterator<PartPos> it = getAllPositions();
3✔
96
        while (it.hasNext() && sum < Long.MAX_VALUE) {
7!
97
            PartPos pos = it.next();
4✔
98
            // Skip if the position is not loaded
99
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
100
                continue;
×
101
            }
102
            this.network.disablePosition(pos);
4✔
103
            try {
104
                sum = Math.addExact(sum, this.network.getPositionedStorage(pos).getMaxQuantity());
8✔
105
            } catch (ArithmeticException e) {
×
106
                sum = Long.MAX_VALUE; // If we had an overflow, we're already at max quantity.
×
107
            }
1✔
108
            this.network.enablePosition(pos);
4✔
109
        }
1✔
110

111
        // Schedule an observation, as since this method is called, there may be a need for changes later on.
112
        scheduleObservation();
2✔
113

114
        return sum;
2✔
115
    }
116

117
    protected Pair<IPartPosIteratorHandler, Iterator<PartPos>> getPartPosIteratorData(Supplier<Iterator<PartPos>> iteratorSupplier, int channel) {
118
        IPartPosIteratorHandler handler = network.getPartPosIteratorHandler();
4✔
119
        if (handler == null) {
2✔
120
            handler = PartPosIteratorHandlerDummy.INSTANCE;
3✔
121
        } else {
122
            handler = handler.clone();
3✔
123
        }
124
        return Pair.of(handler, handler.handleIterator(iteratorSupplier, channel));
7✔
125
    }
126

127
    protected void savePartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler, TransactionContext transaction) {
128
        new PartPosIteratorHandledJournal(partPosIteratorHandler.clone()).updateSnapshots(transaction);
8✔
129
        network.setPartPosIteratorHandler(partPosIteratorHandler);
4✔
130
    }
1✔
131

132
    protected void markStoragePositionChanged(int channel, PartPos targetPos) {
133
        this.network.scheduleObservationForced(channel, targetPos);
5✔
134
    }
1✔
135

136
    @Override
137
    public T insert(@Nonnull T ingredient, TransactionContext transaction) {
138
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
139

140
        // Quickly return if the to-be-inserted ingredient was already empty
141
        if (matcher.isEmpty(ingredient)) {
4!
142
            return ingredient;
×
143
        }
144

145
        // Limit rate
146
        long skippedQuantity = 0;
2✔
147
        T ingredientOriginal = ingredient;
2✔
148
        if (this.limitsEnabled) {
3!
149
            long limit = network.getRateLimit();
4✔
150
            long currentQuantity = matcher.getQuantity(ingredient);
4✔
151
            if (currentQuantity > limit) {
4!
152
                ingredient = matcher.withQuantity(ingredient, limit);
×
153
                skippedQuantity = currentQuantity - limit;
×
154
            }
155
        }
156

157
        // Try inserting the ingredient at all positions that are not full,
158
        // until the ingredient becomes completely empty.
159
        Pair<IPartPosIteratorHandler, Iterator<PartPos>> partPosIteratorData = getPartPosIteratorData(this::getNonFullPositions, channel);
7✔
160
        Iterator<PartPos> it = partPosIteratorData.getRight();
4✔
161
        while (it.hasNext()) {
3!
162
            PartPos pos = it.next();
4✔
163

164
            // Skip if the position is not loaded or disabled
165
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
166
                continue;
×
167
            }
168

169
            // Skip if a filter was set that doesn't match the ingredient
170
            PositionedAddonsNetworkIngredientsFilter<T> filter = this.network.getPositionedStorageFilter(pos);
5✔
171
            if (filter != null && !filter.testInsertion(ingredient)) {
2!
172
                continue;
×
173
            }
174

175
            this.network.disablePosition(pos);
4✔
176
            long quantityBefore = matcher.getQuantity(ingredient);
4✔
177
            ingredient = this.network.getPositionedStorage(pos).insert(ingredient, transaction);
8✔
178
            long quantityAfter = matcher.getQuantity(ingredient);
4✔
179
            this.network.enablePosition(pos);
4✔
180
            if (quantityBefore != quantityAfter) {
4!
181
                new MarkStoragePositionChangedOnRootCommitJournal(pos).updateSnapshots(transaction);
7✔
182
            }
183
            if (matcher.isEmpty(ingredient)) {
4!
184
                break;
1✔
185
            }
186
        }
×
187

188
        // Re-add skipped quantity to response if applicable
189
        if (skippedQuantity > 0) {
4!
190
            // Modify ingredientOriginal instead of ingredient, because ingredient may be EMPTY.
191
            ingredient = matcher.withQuantity(ingredientOriginal, skippedQuantity + matcher.getQuantity(ingredient));
×
192
        }
193

194
        savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
6✔
195

196
        return ingredient;
2✔
197
    }
198

199
    @Override
200
    public T extract(long maxQuantity, TransactionContext transaction) {
201
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
202

203
        // Limit rate
204
        if (this.limitsEnabled) {
3!
205
            maxQuantity = (int) Math.min(maxQuantity, network.getRateLimit());
8✔
206
        }
207

208
        // Try extracting from all non-empty positions
209
        // until one succeeds.
210
        Pair<IPartPosIteratorHandler, Iterator<PartPos>> partPosIteratorData = getPartPosIteratorData(this::getNonEmptyPositions, channel);
7✔
211
        Iterator<PartPos> it = partPosIteratorData.getRight();
4✔
212
        while (it.hasNext()) {
3!
213
            PartPos pos = it.next();
4✔
214

215
            // Skip if the position is not loaded or disabled
216
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
217
                continue;
×
218
            }
219

220
            // Obtain storage
221
            this.network.disablePosition(pos);
4✔
222
            IIngredientComponentStorage<T, M> positionedStorage = this.network.getPositionedStorage(pos);
5✔
223

224
            // If we do an effective extraction, first simulate to check if it matches the filter
225
            PositionedAddonsNetworkIngredientsFilter<T> filter = this.network.getPositionedStorageFilter(pos);
5✔
226
            if (filter != null) {
2!
227
                try (var tx = Transaction.open(transaction)) {
×
228
                    T extractedSimulated = positionedStorage.extract(maxQuantity, tx);
×
229
                    if (!filter.testExtraction(extractedSimulated)) {
×
230
                        continue;
231
                    }
232
                }
×
233
            }
234

235
            T extracted = positionedStorage.extract(maxQuantity, transaction);
5✔
236

237
            this.network.enablePosition(pos);
4✔
238
            if (!matcher.isEmpty(extracted)) {
4!
239
                new MarkStoragePositionChangedOnRootCommitJournal(pos).updateSnapshots(transaction);
7✔
240
                savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
6✔
241
                return extracted;
2✔
242
            }
243
        }
×
244

245
        savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
×
246

247
        // Schedule an observation if nothing was extracted, because the index may not be initialized yet.
248
        scheduleObservation();
×
249

250
        return matcher.getEmptyInstance();
×
251
    }
252

253
    @Override
254
    public T extract(@Nonnull T prototype, M matchFlags, TransactionContext transaction) {
255
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
×
256
        boolean checkQuantity = matcher.hasCondition(matchFlags, getComponent().getPrimaryQuantifier().getMatchCondition());
×
257

258
        // Limit rate
259
        if (this.limitsEnabled) {
×
260
            long limit = network.getRateLimit();
×
261
            if (matcher.getQuantity(prototype) > limit) {
×
262
                // Fail immediately if we require more than the limit
263
                if (checkQuantity) {
×
264
                    return matcher.getEmptyInstance();
×
265
                }
266

267
                // Otherwise, we reduce our requested quantity
268
                prototype = matcher.withQuantity(prototype, limit);
×
269
            }
270
        }
271

272
        final T prototypeFinal = prototype;
×
273
        long requiredQuantity = matcher.getQuantity(prototypeFinal);
×
274

275
        // Modify our match condition that will be used to test each separate interface
276
        if (checkQuantity) {
×
277
            matchFlags = matcher.withoutCondition(matchFlags, getComponent().getPrimaryQuantifier().getMatchCondition());
×
278
        }
279
        M finalMatchFlags = matchFlags;
×
280

281
        // Maintain a temporary mapping of prototype items to their total count over all positions,
282
        // plus the list of positions in which they are present.
283
        IIngredientMapMutable<T, M, Pair<Wrapper<Long>, List<PartPos>>> validInstancesCollapsed = new IngredientHashMap<>(getComponent());
×
284

285
        // Try extracting from all positions that match with the given conditions
286
        // until one succeeds.
287
        Pair<IPartPosIteratorHandler, Iterator<PartPos>> partPosIteratorData = getPartPosIteratorData(() -> this.getMatchingPositions(prototypeFinal, finalMatchFlags), channel);
×
288
        Iterator<PartPos> it = partPosIteratorData.getRight();
×
289
        while (it.hasNext()) {
×
290
            PartPos pos = it.next();
×
291

292
            // Skip if the position is not loaded or disabled
293
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
×
294
                continue;
×
295
            }
296

297
            // Do a simulated extraction
298
            this.network.disablePosition(pos);
×
299
            T extractedSimulated;
300
            try (var tx = Transaction.open(transaction)) {
×
301
                extractedSimulated = this.network.getPositionedStorage(pos).extract(prototypeFinal, finalMatchFlags, tx);
×
302
            }
303
            this.network.enablePosition(pos);
×
304
            T storagePrototype = getComponent().getMatcher().withQuantity(extractedSimulated, 1);
×
305

306
            // Skip if a filter was set that doesn't match the simulated extraction
307
            PositionedAddonsNetworkIngredientsFilter<T> filter = this.network.getPositionedStorageFilter(pos);
×
308
            if (filter != null && !filter.testExtraction(extractedSimulated)) {
×
309
                continue;
×
310
            }
311

312
            // Get existing value from temporary mapping
313
            Pair<Wrapper<Long>, List<PartPos>> existingValue = validInstancesCollapsed.get(storagePrototype);
×
314
            if (existingValue == null) {
×
315
                existingValue = Pair.of(new Wrapper<>(0L), Lists.newLinkedList());
×
316
                validInstancesCollapsed.put(storagePrototype, existingValue);
×
317
            }
318

319
            // Update the counter and pos-list for our prototype
320
            long newCount = existingValue.getLeft().get() + matcher.getQuantity(extractedSimulated);
×
321
            existingValue.getLeft().set(newCount);
×
322
            existingValue.getRight().add(pos);
×
323

324
            // If the count is sufficient for our query, return
325
            if (newCount >= requiredQuantity) {
×
326
                // Save the iterator state before returning
327
                savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
×
328
                existingValue.getLeft().set(requiredQuantity);
×
329
                return finalizeExtraction(storagePrototype, matchFlags, existingValue, transaction);
×
330
            }
331
        }
×
332

333
        // If we reach this point, then our effective count is below requiredQuantity
334

335
        // Save the iterator state before returning
336
        savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
×
337

338
        // Fail if we required an exact quantity
339
        if (checkQuantity) {
×
340
            return matcher.getEmptyInstance();
×
341
        }
342

343
        // Extract for the instance that had the most matches if we didn't require an exact quantity
344
        Pair<Wrapper<Long>, List<PartPos>> maxValue = Pair.of(new Wrapper<>(0L), Lists.newArrayList());
×
345
        T maxInstance = matcher.getEmptyInstance();
×
346
        for (Map.Entry<T, Pair<Wrapper<Long>, List<PartPos>>> entry : validInstancesCollapsed) {
×
347
            if (entry.getValue().getLeft().get() > maxValue.getLeft().get()) {
×
348
                maxInstance = entry.getKey();
×
349
                maxValue = entry.getValue();
×
350
            }
351
        }
×
352

353
        // Schedule an observation, as since this method is called, there may be a need for changes later on.
354
        scheduleObservation();
×
355

356
        return finalizeExtraction(maxInstance, matchFlags, maxValue, transaction);
×
357
    }
358

359
    protected T finalizeExtraction(T instancePrototype, M matchFlags, Pair<Wrapper<Long>, List<PartPos>> value,
360
                                   TransactionContext transaction) {
361
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
×
362
        long extractedCount = value.getLeft().get();
×
363
        if (extractedCount > 0) {
×
364
            long toExtract = extractedCount;
×
365
            for (PartPos pos : value.getRight()) {
×
366
                // Update the remaining prototype quantity for this iteration
367
                instancePrototype = matcher.withQuantity(instancePrototype, toExtract);
×
368

369
                this.network.disablePosition(pos);
×
370
                T extracted = this.network.getPositionedStorage(pos).extract(instancePrototype, matchFlags, transaction);
×
371
                this.network.enablePosition(pos);
×
372
                markStoragePositionChanged(channel, pos);
×
373
                long thisExtractedAmount = matcher.getQuantity(extracted);
×
374
                toExtract -= thisExtractedAmount;
×
375
            }
×
376
            // Quick heuristic check to see if 'storage' did not lie during its simulation
377
            if (toExtract != 0) {
×
378
                /*IntegratedDynamics.clog(org.apache.logging.log4j.Level.WARN, String.format(
379
                        "A storage resulted in inconsistent simulated and non-simulated output. Storages: %s", value.getRight()));*/
380
                // This is not such a huge problem actually, so just make sure our output is correct.
381
                extractedCount -= toExtract;
×
382
            }
383
        }
384
        return getComponent().getMatcher().withQuantity(instancePrototype, extractedCount);
×
385
    }
386

387
    protected void scheduleObservation() {
388
        this.network.scheduleObservation();
3✔
389
    }
1✔
390

391
    class MarkStoragePositionChangedOnRootCommitJournal extends SnapshotJournal<Void> {
392
        private final PartPos pos;
393

394
        MarkStoragePositionChangedOnRootCommitJournal(PartPos pos) {
5✔
395
            this.pos = pos;
3✔
396
        }
1✔
397

398
        @Override
399
        protected Void createSnapshot() {
400
            return null;
2✔
401
        }
402

403
        @Override
404
        protected void revertToSnapshot(Void unused) {
405

406
        }
1✔
407

408
        @Override
409
        protected void onRootCommit(Void originalState) {
410
            super.onRootCommit(originalState);
3✔
411
            markStoragePositionChanged(channel, pos);
8✔
412
        }
1✔
413
    }
414

415
    class PartPosIteratorHandledJournal extends SnapshotJournal<Void> {
416
        private final IPartPosIteratorHandler iteratorHandler;
417

418
        PartPosIteratorHandledJournal(IPartPosIteratorHandler iteratorHandler) {
5✔
419
            this.iteratorHandler = iteratorHandler;
3✔
420
        }
1✔
421

422
        @Override
423
        protected Void createSnapshot() {
424
            return null;
2✔
425
        }
426

427
        @Override
428
        protected void revertToSnapshot(Void unused) {
429
            network.setPartPosIteratorHandler(iteratorHandler);
6✔
430
        }
1✔
431
    }
432

433
}
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

© 2026 Coveralls, Inc