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

CyclopsMC / IntegratedDynamics / 14820654720

04 May 2025 11:14AM UTC coverage: 45.291% (-0.04%) from 45.326%
14820654720

push

github

rubensworks
Add translations through Crowdin

2562 of 8411 branches covered (30.46%)

Branch coverage included in aggregate %.

11731 of 23147 relevant lines covered (50.68%)

2.4 hits per line

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

39.19
/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()) {
3✔
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
            sum = Math.addExact(sum, this.network.getPositionedStorage(pos).getMaxQuantity());
8✔
101
            this.network.enablePosition(pos);
4✔
102
        }
1✔
103

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

107
        return sum;
2✔
108
    }
109

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

120
    protected void savePartPosIteratorHandler(IPartPosIteratorHandler partPosIteratorHandler) {
121
        network.setPartPosIteratorHandler(partPosIteratorHandler);
4✔
122
    }
1✔
123

124
    protected void markStoragePositionChanged(int channel, PartPos targetPos) {
125
        this.network.scheduleObservationForced(channel, targetPos);
5✔
126
    }
1✔
127

128
    @Override
129
    public T insert(@Nonnull T ingredient, boolean simulate) {
130
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
131

132
        // Quickly return if the to-be-inserted ingredient was already empty
133
        if (matcher.isEmpty(ingredient)) {
4!
134
            return ingredient;
×
135
        }
136

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

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

156
            // Skip if the position is not loaded or disabled
157
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
158
                continue;
×
159
            }
160

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

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

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

186
        if (!simulate) {
2✔
187
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
5✔
188
        }
189

190
        return ingredient;
2✔
191
    }
192

193
    @Override
194
    public T extract(long maxQuantity, boolean simulate) {
195
        IIngredientMatcher<T, M> matcher = getComponent().getMatcher();
4✔
196

197
        // Limit rate
198
        if (this.limitsEnabled) {
3!
199
            maxQuantity = (int) Math.min(maxQuantity, network.getRateLimit());
8✔
200
        }
201

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

209
            // Skip if the position is not loaded or disabled
210
            if (!pos.getPos().isLoaded() || network.isPositionDisabled(pos)) {
9!
211
                continue;
×
212
            }
213

214
            // Obtain storage
215
            this.network.disablePosition(pos);
4✔
216
            IIngredientComponentStorage<T, M> positionedStorage = this.network.getPositionedStorage(pos);
5✔
217

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

227
            T extracted = positionedStorage.extract(maxQuantity, simulate);
5✔
228

229
            // If simulating, just check the output
230
            if (filter != null && simulate && !filter.testExtraction(extracted)) {
2!
231
                continue;
×
232
            }
233

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

244
        if (!simulate) {
×
245
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
×
246
        }
247

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

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

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

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

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

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

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

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

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

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

298
            // Do a simulated extraction
299
            this.network.disablePosition(pos);
×
300
            T extractedSimulated = this.network.getPositionedStorage(pos).extract(prototypeFinal, finalMatchFlags, true);
×
301
            this.network.enablePosition(pos);
×
302
            T storagePrototype = getComponent().getMatcher().withQuantity(extractedSimulated, 1);
×
303

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

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

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

322
            // If the count is sufficient for our query, return
323
            if (newCount >= requiredQuantity) {
×
324
                // Save the iterator state before returning
325
                if (!simulate) {
×
326
                    savePartPosIteratorHandler(partPosIteratorData.getLeft());
×
327
                }
328
                existingValue.getLeft().set(requiredQuantity);
×
329
                return finalizeExtraction(storagePrototype, matchFlags, existingValue, simulate);
×
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
        if (!simulate) {
×
337
            savePartPosIteratorHandler(partPosIteratorData.getLeft());
×
338
        }
339

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

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

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

358
        return finalizeExtraction(maxInstance, matchFlags, maxValue, simulate);
×
359
    }
360

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

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

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

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