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

CyclopsMC / IntegratedDynamics / 19594217053

22 Nov 2025 10:29AM UTC coverage: 45.13% (+0.3%) from 44.865%
19594217053

push

github

rubensworks
Bump mod version

2613 of 8556 branches covered (30.54%)

Branch coverage included in aggregate %.

11857 of 23507 relevant lines covered (50.44%)

2.39 hits per line

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

39.21
/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 org.apache.commons.lang3.tuple.Pair;
5
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
6
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
7
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
8
import org.cyclops.cyclopscore.datastructure.Wrapper;
9
import org.cyclops.cyclopscore.ingredient.collection.IIngredientMapMutable;
10
import org.cyclops.cyclopscore.ingredient.collection.IngredientHashMap;
11
import org.cyclops.integrateddynamics.api.network.INetworkIngredientsChannel;
12
import org.cyclops.integrateddynamics.api.network.IPartPosIteratorHandler;
13
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
14
import org.cyclops.integrateddynamics.api.network.PositionedAddonsNetworkIngredientsFilter;
15
import org.cyclops.integrateddynamics.api.part.PartPos;
16

17
import javax.annotation.Nonnull;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.function.Supplier;
22

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

31
    private final IPositionedAddonsNetworkIngredients<T, M> network;
32
    private final int channel;
33

34
    private boolean limitsEnabled;
35

36
    public IngredientChannelAdapter(PositionedAddonsNetworkIngredients<T, M> network, int channel) {
2✔
37
        this.network = network;
3✔
38
        this.channel = channel;
3✔
39

40
        this.limitsEnabled = true;
3✔
41
    }
1✔
42

43
    public void enableLimits() {
44
        this.limitsEnabled = true;
×
45
    }
×
46

47
    public void disableLimits() {
48
        this.limitsEnabled = false;
×
49
    }
×
50

51
    public IPositionedAddonsNetworkIngredients<T, M> getNetwork() {
52
        return network;
3✔
53
    }
54

55
    public int getChannel() {
56
        return channel;
3✔
57
    }
58

59
    @Override
60
    public IngredientComponent<T, M> getComponent() {
61
        return network.getComponent();
4✔
62
    }
63

64
    protected abstract Iterator<PartPos> getNonFullPositions();
65
    protected abstract Iterator<PartPos> getAllPositions();
66
    protected abstract Iterator<PartPos> getNonEmptyPositions();
67
    protected abstract Iterator<PartPos> getMatchingPositions(@Nonnull T prototype, M matchFlags);
68

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

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

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

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

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

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

111
        return sum;
2✔
112
    }
113

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

124
    protected void savePartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
125
        network.setPartPosIteratorHandler(partPosIteratorHandler);
4✔
126
    }
1✔
127

128
    protected void markStoragePositionChanged(int channel, PartPos targetPos) {
129
        this.network.scheduleObservationForced(channel, targetPos);
5✔
130
    }
1✔
131

132
    @Override
133
    public T insert(@Nonnull T ingredient, boolean simulate) {
134
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
135

136
        // Quickly return if the to-be-inserted ingredient was already empty
137
        if (matcher.isEmpty(ingredient)) {
4!
138
            return ingredient;
×
139
        }
140

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

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

160
            // Skip if the position is not loaded or disabled
161
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
162
                continue;
×
163
            }
164

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

171
            this.network.disablePosition(pos);
4✔
172
            long quantityBefore = matcher.getQuantity(ingredient);
4✔
173
            ingredient = this.network.getPositionedStorage(pos).insert(ingredient, simulate);
8✔
174
            long quantityAfter = matcher.getQuantity(ingredient);
4✔
175
            this.network.enablePosition(pos);
4✔
176
            if (!simulate && quantityBefore != quantityAfter) {
6!
177
                markStoragePositionChanged(channel, pos);
5✔
178
            }
179
            if (matcher.isEmpty(ingredient)) {
4!
180
                break;
1✔
181
            }
182
        }
×
183

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

190
        if (!simulate) {
2✔
191
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
5✔
192
        }
193

194
        return ingredient;
2✔
195
    }
196

197
    @Override
198
    public T extract(long maxQuantity, boolean simulate) {
199
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
200

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

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

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

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

222
            // If we do an effective extraction, first simulate to check if it matches the filter
223
            PositionedAddonsNetworkIngredientsFilter<T> filter = this.network.getPositionedStorageFilter(pos);
5✔
224
            if (filter != null && !simulate) {
2!
225
                T extractedSimulated = positionedStorage.extract(maxQuantity, true);
×
226
                if (!filter.testExtraction(extractedSimulated)) {
×
227
                    continue;
×
228
                }
229
            }
230

231
            T extracted = positionedStorage.extract(maxQuantity, simulate);
5✔
232

233
            // If simulating, just check the output
234
            if (filter != null && simulate && !filter.testExtraction(extracted)) {
2!
235
                continue;
×
236
            }
237

238
            this.network.enablePosition(pos);
4✔
239
            if (!matcher.isEmpty(extracted)) {
4!
240
                if (!simulate) {
2✔
241
                    markStoragePositionChanged(channel, pos);
5✔
242
                    savePartPosIteratorHandler(partPosIteratorData.getLeft());
5✔
243
                }
244
                return extracted;
2✔
245
            }
246
        }
×
247

248
        if (!simulate) {
×
249
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
×
250
        }
251

252
        // Schedule an observation if nothing was extracted, because the index may not be initialized yet.
253
        scheduleObservation();
×
254

255
        return matcher.getEmptyInstance();
×
256
    }
257

258
    @Override
259
    public T extract(@Nonnull T prototype, M matchFlags, boolean simulate) {
260
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
×
261
        boolean checkQuantity = matcher.hasCondition(matchFlags, getComponent().getPrimaryQuantifier().getMatchCondition());
×
262

263
        // Limit rate
264
        if (this.limitsEnabled) {
×
265
            long limit = network.getRateLimit();
×
266
            if (matcher.getQuantity(prototype) > limit) {
×
267
                // Fail immediately if we require more than the limit
268
                if (checkQuantity) {
×
269
                    return matcher.getEmptyInstance();
×
270
                }
271

272
                // Otherwise, we reduce our requested quantity
273
                prototype = matcher.withQuantity(prototype, limit);
×
274
            }
275
        }
276

277
        final T prototypeFinal = prototype;
×
278
        long requiredQuantity = matcher.getQuantity(prototypeFinal);
×
279

280
        // Modify our match condition that will be used to test each separate interface
281
        if (checkQuantity) {
×
282
            matchFlags = matcher.withoutCondition(matchFlags, getComponent().getPrimaryQuantifier().getMatchCondition());
×
283
        }
284
        M finalMatchFlags = matchFlags;
×
285

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

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

297
            // Skip if the position is not loaded or disabled
298
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
×
299
                continue;
×
300
            }
301

302
            // Do a simulated extraction
303
            this.network.disablePosition(pos);
×
304
            T extractedSimulated = this.network.getPositionedStorage(pos).extract(prototypeFinal, finalMatchFlags, true);
×
305
            this.network.enablePosition(pos);
×
306
            T storagePrototype = getComponent().getMatcher().withQuantity(extractedSimulated, 1);
×
307

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

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

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

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

337
        // If we reach this point, then our effective count is below requiredQuantity
338

339
        // Save the iterator state before returning
340
        if (!simulate) {
×
341
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
×
342
        }
343

344
        // Fail if we required an exact quantity
345
        if (checkQuantity) {
×
346
            return matcher.getEmptyInstance();
×
347
        }
348

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

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

362
        return finalizeExtraction(maxInstance, matchFlags, maxValue, simulate);
×
363
    }
364

365
    protected T finalizeExtraction(T instancePrototype, M matchFlags, Pair<Wrapper<Long>, List<PartPos>> value,
366
                                   boolean simulate) {
367
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
×
368
        long extractedCount = value.getLeft().get();
×
369
        if (!simulate && extractedCount > 0) {
×
370
            long toExtract = extractedCount;
×
371
            for (PartPos pos : value.getRight()) {
×
372
                // Update the remaining prototype quantity for this iteration
373
                instancePrototype = matcher.withQuantity(instancePrototype, toExtract);
×
374

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

393
    protected void scheduleObservation() {
394
        this.network.scheduleObservation();
3✔
395
    }
1✔
396

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