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

CyclopsMC / IntegratedDynamics / 20210191346

14 Dec 2025 03:32PM UTC coverage: 19.514% (-33.5%) from 53.061%
20210191346

push

github

rubensworks
Remove deprecations

663 of 8728 branches covered (7.6%)

Branch coverage included in aggregate %.

6786 of 29445 relevant lines covered (23.05%)

1.09 hits per line

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

0.0
/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) {
×
40
        this.network = network;
×
41
        this.channel = channel;
×
42

43
        this.limitsEnabled = true;
×
44
    }
×
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;
×
56
    }
57

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

62
    @Override
63
    public IngredientComponent<T, M> getComponent() {
64
        return network.getComponent();
×
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;
×
95
        Iterator<PartPos> it = getAllPositions();
×
96
        while (it.hasNext() && sum < Long.MAX_VALUE) {
×
97
            PartPos pos = it.next();
×
98
            // Skip if the position is not loaded
99
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
×
100
                continue;
×
101
            }
102
            this.network.disablePosition(pos);
×
103
            try {
104
                sum = Math.addExact(sum, this.network.getPositionedStorage(pos).getMaxQuantity());
×
105
            } catch (ArithmeticException e) {
×
106
                sum = Long.MAX_VALUE; // If we had an overflow, we're already at max quantity.
×
107
            }
×
108
            this.network.enablePosition(pos);
×
109
        }
×
110

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

114
        return sum;
×
115
    }
116

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

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

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

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

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

145
        // Limit rate
146
        long skippedQuantity = 0;
×
147
        T ingredientOriginal = ingredient;
×
148
        if (this.limitsEnabled) {
×
149
            long limit = network.getRateLimit();
×
150
            long currentQuantity = matcher.getQuantity(ingredient);
×
151
            if (currentQuantity > limit) {
×
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);
×
160
        Iterator<PartPos> it = partPosIteratorData.getRight();
×
161
        while (it.hasNext()) {
×
162
            PartPos pos = it.next();
×
163

164
            // Skip if the position is not loaded or disabled
165
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
×
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);
×
171
            if (filter != null && !filter.testInsertion(ingredient)) {
×
172
                continue;
×
173
            }
174

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

188
        // Re-add skipped quantity to response if applicable
189
        if (skippedQuantity > 0) {
×
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);
×
195

196
        return ingredient;
×
197
    }
198

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

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

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

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

220
            // Obtain storage
221
            this.network.disablePosition(pos);
×
222
            IIngredientComponentStorage<T, M> positionedStorage = this.network.getPositionedStorage(pos);
×
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);
×
226
            if (filter != null) {
×
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);
×
236

237
            this.network.enablePosition(pos);
×
238
            if (!matcher.isEmpty(extracted)) {
×
239
                new MarkStoragePositionChangedOnRootCommitJournal(pos).updateSnapshots(transaction);
×
240
                savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
×
241
                return extracted;
×
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 = this.network.getPositionedStorage(pos).extract(prototypeFinal, finalMatchFlags, true);
×
300
            this.network.enablePosition(pos);
×
301
            T storagePrototype = getComponent().getMatcher().withQuantity(extractedSimulated, 1);
×
302

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

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

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

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

330
        // If we reach this point, then our effective count is below requiredQuantity
331

332
        // Save the iterator state before returning
333
        savePartPosIteratorHandler(partPosIteratorData.getLeft(), transaction);
×
334

335
        // Fail if we required an exact quantity
336
        if (checkQuantity) {
×
337
            return matcher.getEmptyInstance();
×
338
        }
339

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

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

353
        return finalizeExtraction(maxInstance, matchFlags, maxValue, transaction);
×
354
    }
355

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

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

384
    protected void scheduleObservation() {
385
        this.network.scheduleObservation();
×
386
    }
×
387

388
    class MarkStoragePositionChangedOnRootCommitJournal extends SnapshotJournal<Void> {
389
        private final PartPos pos;
390

391
        MarkStoragePositionChangedOnRootCommitJournal(PartPos pos) {
×
392
            this.pos = pos;
×
393
        }
×
394

395
        @Override
396
        protected Void createSnapshot() {
397
            return null;
×
398
        }
399

400
        @Override
401
        protected void revertToSnapshot(Void unused) {
402

403
        }
×
404

405
        @Override
406
        protected void onRootCommit(Void originalState) {
407
            super.onRootCommit(originalState);
×
408
            markStoragePositionChanged(channel, pos);
×
409
        }
×
410
    }
411

412
    class PartPosIteratorHandledJournal extends SnapshotJournal<Void> {
413
        private final IPartPosIteratorHandler iteratorHandler;
414

415
        PartPosIteratorHandledJournal(IPartPosIteratorHandler iteratorHandler) {
×
416
            this.iteratorHandler = iteratorHandler;
×
417
        }
×
418

419
        @Override
420
        protected Void createSnapshot() {
421
            return null;
×
422
        }
423

424
        @Override
425
        protected void revertToSnapshot(Void unused) {
426
            network.setPartPosIteratorHandler(iteratorHandler);
×
427
        }
×
428
    }
429

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