BlueGit

timfa containerpipes

Let incoming pipes supply orchestrated crafters via the normal planner.

Input pipes inherit the output recipe as their transfer filter and insert into matching crafter slots; the output pipe only checks grid completeness and triggers craft. Fixes sources not being consumed by the separate pull path.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-18 · 3 months ago

Hash
01e3c7370f4c46222ec0ee54f722f44b0952d6e1
Parent
c2631537
3 files changed +148 −334
src/main/java/nl/timfalken/containerpipes/AdvancedEndpointsPatch.java +0 −4
@@ -52,10 +52,6 @@ public final class AdvancedEndpointsPatch {
52 52 if (location == null) return false;
53 53 Object block = call(location, "getBlock");
54 54 if (!"CRAFTER".equals(materialName(block))) return false;
55 if (block instanceof Block bukkitBlock
56 && CrafterPipeManager.isOrchestrated(bukkitBlock)) {
57 return false;
58 }
59 55 if (block instanceof Block bukkitBlock
60 56 && sourceStack instanceof ItemStack itemStack
61 57 && !CrafterPipeManager.allowsIncomingInsert(bukkitBlock, itemStack)) {
@@ -52,10 +52,6 @@ public final class AdvancedEndpointsPatch {
52 if (location == null) return false;
52 if (location == null) return false;
53 Object block = call(location, "getBlock");
53 Object block = call(location, "getBlock");
54 if (!"CRAFTER".equals(materialName(block))) return false;
54 if (!"CRAFTER".equals(materialName(block))) return false;
55 if (block instanceof Block bukkitBlock
56 && CrafterPipeManager.isOrchestrated(bukkitBlock)) {
57 return false;
58 }
59 if (block instanceof Block bukkitBlock
55 if (block instanceof Block bukkitBlock
60 && sourceStack instanceof ItemStack itemStack
56 && sourceStack instanceof ItemStack itemStack
61 && !CrafterPipeManager.allowsIncomingInsert(bukkitBlock, itemStack)) {
57 && !CrafterPipeManager.allowsIncomingInsert(bukkitBlock, itemStack)) {
src/main/java/nl/timfalken/containerpipes/CrafterPipeManager.java +130 −323
@@ -20,10 +20,9 @@ import java.lang.reflect.Method;
20 20 import java.util.*;
21 21
22 22 /**
23 * Crafter output pipes use a 3x3 recipe grid. Incoming pipes are slaved and
24 * supply those exact ingredients; the vanilla crafter is then told to craft.
25 * No recipe lookup or result preview — if the layout is wrong, the crafter
26 * fails and this network sleeps until an inventory/craft event wakes it.
23 * Crafter output pipes use a 3x3 recipe grid. Incoming pipes deliver recipe
24 * ingredients through the normal transfer planner; this class only coordinates
25 * slot locks, recipe-aware insertion, and triggering the vanilla crafter.
27 26 */
28 27 public final class CrafterPipeManager implements Listener {
29 28 private CrafterPipeManager() {}
@@ -32,7 +31,7 @@ public final class CrafterPipeManager implements Listener {
32 31 private static final Map<CrafterPos, Network> networks = new HashMap<>();
33 32 private static final Map<Long, Network> outgoingIndex = new HashMap<>();
34 33 private static final Map<CrafterPos, Integer> appliedSlotMask = new HashMap<>();
35 private static final Set<Long> slavedIncomingIds = new HashSet<>();
34 private static final Set<Long> incomingToOrchestrated = new HashSet<>();
36 35 private static final Set<Long> craftingGridIds = new HashSet<>();
37 36 private static final Map<String, Method> methodCache = new HashMap<>();
38 37 private static boolean applying;
@@ -40,7 +39,6 @@ public final class CrafterPipeManager implements Listener {
40 39 private static boolean scheduled;
41 40 private static boolean needsRetry;
42 41 private static int orchestratorCount;
43 private static Network running;
44 42 private static int idleAfter = 3;
45 43 private static int sleepProbe = 200;
46 44
@@ -64,44 +62,13 @@ public final class CrafterPipeManager implements Listener {
64 62 }
65 63 }
66 64
67 static final class SourceCache {
68 final Block block;
69 final List<PipeRef> pipes = new ArrayList<>();
70 ItemStack[] contents;
71 boolean dirty = true;
72
73 SourceCache(Block block) { this.block = block; }
74
75 void refresh() {
76 if (!dirty && contents != null) return;
77 World world = block.getWorld();
78 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) {
79 contents = new ItemStack[0];
80 dirty = false;
81 return;
82 }
83 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
84 contents = inventory == null ? new ItemStack[0] : cloneContents(inventory.getStorageContents());
85 dirty = false;
86 }
87
88 Inventory liveInventory() {
89 World world = block.getWorld();
90 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) return null;
91 return HopperStyleEndpoints.inventoryOf(block);
92 }
93 }
94
95 65 static final class Network {
96 66 final CrafterPos pos;
97 67 PipeRef outgoing;
98 68 PipeRef orchestrator;
99 69 final List<PipeRef> incoming = new ArrayList<>();
100 final List<SourceCache> sources = new ArrayList<>();
101 70 final ItemStack[] recipe = new ItemStack[9];
102 71 int recipeMask;
103 ItemStack[] crafterCache;
104 boolean crafterDirty = true;
105 72 boolean sleeping;
106 73 int failed;
107 74 int sleepUntil;
@@ -128,13 +95,6 @@ public final class CrafterPipeManager implements Listener {
128 95 sleeping = false;
129 96 failed = 0;
130 97 sleepUntil = 0;
131 crafterDirty = true;
132 for (SourceCache source : sources) source.dirty = true;
133 }
134
135 void sleepUntil(int tick) {
136 sleeping = true;
137 sleepUntil = tick;
138 98 }
139 99 }
140 100
@@ -148,7 +108,7 @@ public final class CrafterPipeManager implements Listener {
148 108 networks.clear();
149 109 outgoingIndex.clear();
150 110 appliedSlotMask.clear();
151 slavedIncomingIds.clear();
111 incomingToOrchestrated.clear();
152 112 craftingGridIds.clear();
153 113 methodCache.clear();
154 114 orchestratorCount = 0;
@@ -164,7 +124,7 @@ public final class CrafterPipeManager implements Listener {
164 124 try {
165 125 networks.clear();
166 126 outgoingIndex.clear();
167 slavedIncomingIds.clear();
127 incomingToOrchestrated.clear();
168 128 craftingGridIds.clear();
169 129 orchestratorCount = 0;
170 130 needsRetry = false;
@@ -187,8 +147,7 @@ public final class CrafterPipeManager implements Listener {
187 147 outgoingIndex.put(network.outgoing.id, network);
188 148 if (network.orchestrator != null) {
189 149 orchestratorCount++;
190 for (PipeRef incoming : network.incoming) slavedIncomingIds.add(incoming.id);
191 indexSources(network);
150 for (PipeRef incoming : network.incoming) incomingToOrchestrated.add(incoming.id);
192 151 }
193 152 applySlotLocksNow(network);
194 153 }
@@ -213,6 +172,65 @@ public final class CrafterPipeManager implements Listener {
213 172 return orchestratorCount > 0;
214 173 }
215 174
175 /** Material filter for incoming pipes whose destination is an orchestrated crafter. */
176 public static EnumSet<Material> recipeMaterials(Block crafterBlock) {
177 Network network = networkAt(crafterBlock);
178 if (network == null || network.orchestrator == null) return null;
179 EnumSet<Material> materials = EnumSet.noneOf(Material.class);
180 for (ItemStack template : network.recipe) {
181 if (template != null) materials.add(template.getType());
182 }
183 return materials.isEmpty() ? null : materials;
184 }
185
186 public static boolean insertRecipeItem(Inventory inventory, Block block, ItemStack source) {
187 if (!validItem(source) || inventory == null || block == null) return false;
188 Network network = networkAt(block);
189 if (network == null || network.orchestrator == null) {
190 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
191 }
192 if (!allowsIncomingInsert(block, source)) return false;
193
194 ItemStack one = source.clone();
195 one.setAmount(1);
196 Crafter crafter = liveCrafter(block);
197 int maxStack = Math.min(one.getMaxStackSize(), inventory.getMaxStackSize());
198
199 for (int slot = 0; slot < 9; slot++) {
200 ItemStack template = network.recipe[slot];
201 if (template == null || !one.isSimilar(template)) continue;
202 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
203 ItemStack existing = inventory.getItem(slot);
204 if (validItem(existing)) continue;
205 ItemStack actual = inventory.getItem(slot);
206 if (validItem(actual)) continue;
207 inventory.setItem(slot, one.clone());
208 return true;
209 }
210
211 int bestSlot = -1;
212 int bestAmount = Integer.MAX_VALUE;
213 for (int slot = 0; slot < 9; slot++) {
214 ItemStack template = network.recipe[slot];
215 if (template == null || !one.isSimilar(template)) continue;
216 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
217 ItemStack existing = inventory.getItem(slot);
218 if (!validItem(existing) || !existing.isSimilar(one)) continue;
219 if (existing.getAmount() >= Math.min(existing.getMaxStackSize(), maxStack)) continue;
220 if (existing.getAmount() < bestAmount) {
221 bestAmount = existing.getAmount();
222 bestSlot = slot;
223 }
224 }
225 if (bestSlot < 0) return false;
226 ItemStack existing = inventory.getItem(bestSlot);
227 if (!validItem(existing) || existing.getAmount() != bestAmount || !existing.isSimilar(one)) return false;
228 ItemStack merged = existing.clone();
229 merged.setAmount(existing.getAmount() + 1);
230 inventory.setItem(bestSlot, merged);
231 return true;
232 }
233
216 234 private static void scheduleRebuild(Object owner) {
217 235 Plugin p = plugin != null ? plugin : owner instanceof Plugin pl ? pl : null;
218 236 if (p == null || scheduled) return;
@@ -226,22 +244,20 @@ public final class CrafterPipeManager implements Listener {
226 244
227 245 public static void invalidateBlock(Block block) {
228 246 if (block == null || orchestratorCount == 0) return;
229 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
230 wakeMatching(block, inventory);
247 Network network = networkAt(block);
248 if (network != null && network.orchestrator != null) network.wake();
231 249 }
232 250
233 251 public static void invalidateInventory(Inventory inventory) {
234 252 if (inventory == null || orchestratorCount == 0) return;
235 Block block = null;
236 253 try {
237 254 var location = inventory.getLocation();
238 if (location != null && location.getWorld() != null) block = location.getBlock();
255 if (location != null && location.getWorld() != null) invalidateBlock(location.getBlock());
239 256 } catch (Throwable ignored) {}
240 wakeMatching(block, inventory);
241 257 }
242 258
243 259 public static boolean isSlavedIncoming(long connectionId) {
244 return slavedIncomingIds.contains(connectionId);
260 return incomingToOrchestrated.contains(connectionId);
245 261 }
246 262
247 263 public static boolean isFilteredCrafterOutput(long connectionId) {
@@ -262,14 +278,13 @@ public final class CrafterPipeManager implements Listener {
262 278 }
263 279
264 280 public static boolean blocksFilter(long connectionId) {
265 return slavedIncomingIds.contains(connectionId);
281 return incomingToOrchestrated.contains(connectionId);
266 282 }
267 283
268 284 public static boolean isCrafter(Block block) {
269 285 return block != null && block.getType() == Material.CRAFTER;
270 286 }
271 287
272 /** Minecraft orientation is {@code <dispense>_<top>}; the first token is the output face. */
273 288 public static BlockFace outputFace(Block block) {
274 289 if (!isCrafter(block)) return null;
275 290 if (!(block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data)) return BlockFace.NORTH;
@@ -292,7 +307,7 @@ public final class CrafterPipeManager implements Listener {
292 307
293 308 public static boolean allowsIncomingInsert(Block crafterBlock, ItemStack stack) {
294 309 if (!validItem(stack)) return false;
295 Network network = networks.get(CrafterPos.of(crafterBlock));
310 Network network = networkAt(crafterBlock);
296 311 if (network == null || network.orchestrator == null) return true;
297 312 for (ItemStack template : network.recipe) {
298 313 if (template != null && stack.isSimilar(template)) return true;
@@ -309,20 +324,21 @@ public final class CrafterPipeManager implements Listener {
309 324 if (network.orchestrator == null) continue;
310 325 if (network.sleeping && now < network.sleepUntil) continue;
311 326 try {
312 RunResult result = orchestrate(owner, network);
313 if (result == RunResult.MOVED || result == RunResult.STALE) {
327 RunResult result = tryCraft(owner, network);
328 if (result == RunResult.MOVED) {
314 329 network.sleeping = false;
315 330 network.failed = 0;
316 331 } else if (result == RunResult.CRAFT_FAILED) {
317 network.sleepUntil(now + sleepProbe);
332 network.sleeping = true;
333 network.sleepUntil = now + sleepProbe;
318 334 } else if (++network.failed >= idleAfter) {
319 network.sleepUntil(now + sleepProbe);
335 network.sleeping = true;
336 network.sleepUntil = now + sleepProbe;
320 337 }
321 338 } catch (Throwable t) {
322 339 if (plugin != null) plugin.getLogger().warning("Crafter orchestration failed: " + t);
323 network.crafterDirty = true;
324 for (SourceCache source : network.sources) source.dirty = true;
325 network.sleepUntil(now + sleepProbe);
340 network.sleeping = true;
341 network.sleepUntil = now + sleepProbe;
326 342 }
327 343 }
328 344 }
@@ -358,16 +374,15 @@ public final class CrafterPipeManager implements Listener {
358 374 }
359 375 event.setCancelled(true);
360 376 event.setResult(new ItemStack(Material.AIR));
361 network.crafterDirty = true;
362 377 if (network.outgoing.destBlock != null) {
363 378 OptimizedTransferPlanner.invalidateBlock(plugin, network.outgoing.destBlock);
364 379 }
365 380 OptimizedTransferPlanner.invalidateBlock(plugin, block);
366 381 }
367 382
368 private enum RunResult { MOVED, NO_MOVE, STALE, CRAFT_FAILED }
383 private enum RunResult { MOVED, NO_MOVE, CRAFT_FAILED }
369 384
370 private static RunResult orchestrate(Object owner, Network network) {
385 private static RunResult tryCraft(Object owner, Network network) {
371 386 World world = Bukkit.getWorld(network.pos.world);
372 387 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return RunResult.NO_MOVE;
373 388
@@ -375,65 +390,56 @@ public final class CrafterPipeManager implements Listener {
375 390 if (block.getType() != Material.CRAFTER) return RunResult.NO_MOVE;
376 391 if (isBusy(block)) return RunResult.NO_MOVE;
377 392
378 running = network;
379 try {
380 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
381 applySlotLocksNow(network);
382 }
393 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
394 applySlotLocksNow(network);
395 }
383 396
384 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
385 if (crafterInv == null) return RunResult.NO_MOVE;
386 refreshCrafterCache(network, crafterInv);
397 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
398 if (crafterInv == null) return RunResult.NO_MOVE;
387 399
388 if (gridMatchesRecipe(network.crafterCache, network.recipe)) {
389 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
390 }
391 if (!gridEmpty(network.crafterCache)) return RunResult.CRAFT_FAILED;
400 ItemStack[] grid = readGrid(crafterInv);
401 if (hasJunk(grid, network.recipe)) return RunResult.CRAFT_FAILED;
402 if (!gridMatchesRecipe(grid, network.recipe)) return RunResult.NO_MOVE;
403
404 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
405 }
392 406
393 for (SourceCache source : network.sources) source.refresh();
394 Pull[] pulls = planPulls(network.sources, network.recipe);
395 if (pulls == null) return RunResult.NO_MOVE;
407 private static ItemStack[] readGrid(Inventory inventory) {
408 ItemStack[] storage = inventory.getStorageContents();
409 ItemStack[] grid = new ItemStack[9];
410 int limit = Math.min(9, storage.length);
411 for (int slot = 0; slot < limit; slot++) {
412 ItemStack item = storage[slot];
413 grid[slot] = validItem(item) ? item.clone() : null;
414 }
415 return grid;
416 }
396 417
397 List<Take> takes = new ArrayList<>(9);
398 ItemStack[] placed = new ItemStack[9];
399 for (int slot = 0; slot < 9; slot++) {
400 Pull pull = pulls[slot];
401 if (pull == null) continue;
402 Inventory live = pull.source.liveInventory();
403 if (live == null) {
404 restoreTakes(takes);
405 return RunResult.NO_MOVE;
406 }
407 ItemStack expected = pull.source.contents[pull.invSlot];
408 if (!slotMatches(live, pull.invSlot, expected)) {
409 pull.source.dirty = true;
410 restoreTakes(takes);
411 return RunResult.STALE;
412 }
413 ItemStack before = takeOne(live, pull.invSlot, network.recipe[slot]);
414 if (before == null) {
415 pull.source.dirty = true;
416 restoreTakes(takes);
417 return RunResult.STALE;
418 }
419 takes.add(new Take(live, pull.invSlot, before, pull.source, expected));
420 decrementCache(pull.source, pull.invSlot);
421 ItemStack one = before.clone();
422 one.setAmount(1);
423 placed[slot] = one;
418 private static boolean hasJunk(ItemStack[] grid, ItemStack[] recipe) {
419 for (int slot = 0; slot < 9; slot++) {
420 ItemStack want = recipe[slot];
421 ItemStack have = grid[slot];
422 if (want == null) {
423 if (validItem(have)) return true;
424 } else if (validItem(have) && !have.isSimilar(want)) {
425 return true;
424 426 }
427 }
428 return false;
429 }
425 430
426 writeGrid(crafterInv, placed);
427 network.crafterCache = cloneContents(placed);
428 network.crafterDirty = false;
429 for (SourceCache source : network.sources) {
430 if (!source.dirty) OptimizedTransferPlanner.invalidateBlock(owner, source.block);
431 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
432 if (grid == null) return false;
433 for (int slot = 0; slot < 9; slot++) {
434 ItemStack want = recipe[slot];
435 ItemStack have = grid[slot];
436 if (want == null) {
437 if (validItem(have)) return false;
438 } else if (!validItem(have) || !have.isSimilar(want)) {
439 return false;
431 440 }
432
433 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
434 } finally {
435 running = null;
436 441 }
442 return true;
437 443 }
438 444
439 445 private static boolean triggerCraft(Object owner, Network network, Block block) {
@@ -454,7 +460,6 @@ public final class CrafterPipeManager implements Listener {
454 460 return false;
455 461 } finally {
456 462 network.attemptingCraft = false;
457 network.crafterDirty = true;
458 463 if (network.outgoing != null && network.outgoing.destBlock != null) {
459 464 OptimizedTransferPlanner.invalidateBlock(owner, network.outgoing.destBlock);
460 465 }
@@ -473,41 +478,6 @@ public final class CrafterPipeManager implements Listener {
473 478 }
474 479 }
475 480
476 private static void refreshCrafterCache(Network network, Inventory inventory) {
477 if (!network.crafterDirty && network.crafterCache != null) return;
478 ItemStack[] storage = inventory.getStorageContents();
479 ItemStack[] grid = new ItemStack[9];
480 int limit = Math.min(9, storage.length);
481 for (int slot = 0; slot < limit; slot++) {
482 ItemStack item = storage[slot];
483 grid[slot] = validItem(item) ? item.clone() : null;
484 }
485 network.crafterCache = grid;
486 network.crafterDirty = false;
487 }
488
489 private static boolean gridEmpty(ItemStack[] grid) {
490 if (grid == null) return true;
491 for (ItemStack item : grid) {
492 if (validItem(item)) return false;
493 }
494 return true;
495 }
496
497 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
498 if (grid == null) return false;
499 for (int slot = 0; slot < 9; slot++) {
500 ItemStack want = recipe[slot];
501 ItemStack have = slot < grid.length ? grid[slot] : null;
502 if (want == null) {
503 if (validItem(have)) return false;
504 } else if (!validItem(have) || !have.isSimilar(want)) {
505 return false;
506 }
507 }
508 return true;
509 }
510
511 481 private static boolean routeOutgoing(Object owner, PipeRef outgoing, ItemStack item) {
512 482 try {
513 483 if (!validItem(item) || outgoing == null) return false;
@@ -598,6 +568,11 @@ public final class CrafterPipeManager implements Listener {
598 568 return false;
599 569 }
600 570
571 private static Network networkAt(Block block) {
572 if (block == null || block.getType() != Material.CRAFTER) return null;
573 return networks.get(CrafterPos.of(block));
574 }
575
601 576 private static void applySlotLocksNow(Network network) {
602 577 World world = Bukkit.getWorld(network.pos.world);
603 578 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return;
@@ -620,101 +595,6 @@ public final class CrafterPipeManager implements Listener {
620 595 try { crafter.update(true, false); } catch (Throwable ignored) {}
621 596 }
622 597
623 private static Pull[] planPulls(List<SourceCache> sources, ItemStack[] recipe) {
624 Pull[] pulls = new Pull[9];
625 int needed = 0;
626 int[][] reserved = new int[sources.size()][];
627 for (int i = 0; i < sources.size(); i++) {
628 ItemStack[] contents = sources.get(i).contents;
629 reserved[i] = new int[contents == null ? 0 : contents.length];
630 }
631 for (int slot = 0; slot < 9; slot++) {
632 ItemStack template = recipe[slot];
633 if (template == null) continue;
634 needed++;
635 Pull pull = null;
636 for (int s = 0; s < sources.size(); s++) {
637 SourceCache source = sources.get(s);
638 ItemStack[] contents = source.contents;
639 if (contents == null) continue;
640 for (int invSlot = 0; invSlot < contents.length; invSlot++) {
641 ItemStack stack = contents[invSlot];
642 if (!validItem(stack) || !stack.isSimilar(template)) continue;
643 if (stack.getAmount() <= reserved[s][invSlot]) continue;
644 reserved[s][invSlot]++;
645 pull = new Pull(source, invSlot);
646 break;
647 }
648 if (pull != null) break;
649 }
650 if (pull == null) return null;
651 pulls[slot] = pull;
652 }
653 return needed == 0 ? null : pulls;
654 }
655
656 private static boolean slotMatches(Inventory inventory, int slot, ItemStack expected) {
657 ItemStack actual = inventory.getItem(slot);
658 if (expected == null || expected.getType().isAir()) {
659 return actual == null || actual.getType().isAir();
660 }
661 if (actual == null || actual.getType().isAir()) return false;
662 return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
663 }
664
665 private static ItemStack takeOne(Inventory inventory, int slot, ItemStack template) {
666 ItemStack have = inventory.getItem(slot);
667 if (!validItem(have) || (template != null && !have.isSimilar(template))) return null;
668 ItemStack before = have.clone();
669 if (have.getAmount() <= 1) inventory.setItem(slot, null);
670 else {
671 ItemStack reduced = have.clone();
672 reduced.setAmount(have.getAmount() - 1);
673 inventory.setItem(slot, reduced);
674 }
675 return before;
676 }
677
678 private static void decrementCache(SourceCache source, int slot) {
679 if (source.contents == null || slot < 0 || slot >= source.contents.length) return;
680 ItemStack have = source.contents[slot];
681 if (!validItem(have)) return;
682 if (have.getAmount() <= 1) source.contents[slot] = null;
683 else {
684 ItemStack reduced = have.clone();
685 reduced.setAmount(have.getAmount() - 1);
686 source.contents[slot] = reduced;
687 }
688 }
689
690 private static void restoreTakes(List<Take> takes) {
691 for (int i = takes.size() - 1; i >= 0; i--) {
692 Take take = takes.get(i);
693 take.inventory.setItem(take.slot, take.before);
694 if (take.source.contents != null && take.slot < take.source.contents.length) {
695 take.source.contents[take.slot] = take.cachedBefore == null ? null : take.cachedBefore.clone();
696 }
697 }
698 }
699
700 private static void writeGrid(Inventory inventory, ItemStack[] placed) {
701 int limit = Math.min(9, inventory.getSize());
702 for (int slot = 0; slot < limit; slot++) {
703 ItemStack item = placed[slot];
704 inventory.setItem(slot, validItem(item) ? item.clone() : null);
705 }
706 }
707
708 private static ItemStack[] cloneContents(ItemStack[] input) {
709 ItemStack[] copy = new ItemStack[input.length];
710 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
711 return copy;
712 }
713
714 private record Pull(SourceCache source, int invSlot) {}
715
716 private record Take(Inventory inventory, int slot, ItemStack before, SourceCache source, ItemStack cachedBefore) {}
717
718 598 private static Crafter liveCrafter(Block block) {
719 599 try {
720 600 BlockState state = block.getState(false);
@@ -735,80 +615,7 @@ public final class CrafterPipeManager implements Listener {
735 615 private static void playTransferEffects(Network network) {
736 616 if (!(plugin instanceof ContainerPipesPlugin pipes)) return;
737 617 if (network.outgoing != null) pipes.playTransferAnimation(network.outgoing.raw);
738 for (SourceCache source : network.sources) {
739 for (PipeRef incoming : source.pipes) pipes.playTransferAnimation(incoming.raw);
740 }
741 }
742
743 private static void wakeMatching(Block block, Inventory inventory) {
744 CrafterPos pos = block == null ? null : CrafterPos.of(block);
745 for (Network network : networks.values()) {
746 if (network.orchestrator == null) continue;
747 if (network == running) {
748 network.crafterDirty = true;
749 continue;
750 }
751 if (pos != null && network.pos.equals(pos)) {
752 network.wake();
753 continue;
754 }
755 if (pos != null && network.outgoing != null && network.outgoing.destBlock != null
756 && CrafterPos.of(network.outgoing.destBlock).equals(pos)) {
757 network.wake();
758 continue;
759 }
760 if (matchesSource(network, block, inventory)) network.wake();
761 }
762 }
763
764 private static boolean matchesSource(Network network, Block block, Inventory inventory) {
765 Integer invX = null, invY = null, invZ = null;
766 World invWorld = null;
767 if (inventory != null) {
768 try {
769 var location = inventory.getLocation();
770 if (location != null && location.getWorld() != null) {
771 invWorld = location.getWorld();
772 invX = location.getBlockX();
773 invY = location.getBlockY();
774 invZ = location.getBlockZ();
775 }
776 } catch (Throwable ignored) {}
777 }
778 for (SourceCache source : network.sources) {
779 if (block != null && source.block.getWorld() == block.getWorld()
780 && source.block.getX() == block.getX()
781 && source.block.getY() == block.getY()
782 && source.block.getZ() == block.getZ()) {
783 return true;
784 }
785 if (invWorld != null && source.block.getWorld() == invWorld
786 && source.block.getX() == invX
787 && source.block.getY() == invY
788 && source.block.getZ() == invZ) {
789 return true;
790 }
791 }
792 return false;
793 }
794
795 private static void indexSources(Network network) {
796 network.sources.clear();
797 Map<String, SourceCache> byBlock = new LinkedHashMap<>();
798 for (PipeRef incoming : network.incoming) {
799 Block block = incoming.sourceBlock;
800 if (block == null) continue;
801 String key = block.getWorld().getUID() + ":" + block.getX() + "," + block.getY() + "," + block.getZ();
802 SourceCache cache = byBlock.get(key);
803 if (cache == null) {
804 cache = new SourceCache(block);
805 byBlock.put(key, cache);
806 }
807 cache.pipes.add(incoming);
808 }
809 network.sources.addAll(byBlock.values());
810 network.crafterDirty = true;
811 network.wake();
618 for (PipeRef incoming : network.incoming) pipes.playTransferAnimation(incoming.raw);
812 619 }
813 620
814 621 private static boolean stripIncomingFilters(Object owner) {
@@ -20,10 +20,9 @@ import java.lang.reflect.Method;
20import java.util.*;
20import java.util.*;
21
21
22/**
22/**
23 * Crafter output pipes use a 3x3 recipe grid. Incoming pipes are slaved and
23 * Crafter output pipes use a 3x3 recipe grid. Incoming pipes deliver recipe
24 * supply those exact ingredients; the vanilla crafter is then told to craft.
24 * ingredients through the normal transfer planner; this class only coordinates
25 * No recipe lookup or result preview — if the layout is wrong, the crafter
25 * slot locks, recipe-aware insertion, and triggering the vanilla crafter.
26 * fails and this network sleeps until an inventory/craft event wakes it.
27 */
26 */
28public final class CrafterPipeManager implements Listener {
27public final class CrafterPipeManager implements Listener {
29 private CrafterPipeManager() {}
28 private CrafterPipeManager() {}
@@ -32,7 +31,7 @@ public final class CrafterPipeManager implements Listener {
32 private static final Map<CrafterPos, Network> networks = new HashMap<>();
31 private static final Map<CrafterPos, Network> networks = new HashMap<>();
33 private static final Map<Long, Network> outgoingIndex = new HashMap<>();
32 private static final Map<Long, Network> outgoingIndex = new HashMap<>();
34 private static final Map<CrafterPos, Integer> appliedSlotMask = new HashMap<>();
33 private static final Map<CrafterPos, Integer> appliedSlotMask = new HashMap<>();
35 private static final Set<Long> slavedIncomingIds = new HashSet<>();
34 private static final Set<Long> incomingToOrchestrated = new HashSet<>();
36 private static final Set<Long> craftingGridIds = new HashSet<>();
35 private static final Set<Long> craftingGridIds = new HashSet<>();
37 private static final Map<String, Method> methodCache = new HashMap<>();
36 private static final Map<String, Method> methodCache = new HashMap<>();
38 private static boolean applying;
37 private static boolean applying;
@@ -40,7 +39,6 @@ public final class CrafterPipeManager implements Listener {
40 private static boolean scheduled;
39 private static boolean scheduled;
41 private static boolean needsRetry;
40 private static boolean needsRetry;
42 private static int orchestratorCount;
41 private static int orchestratorCount;
43 private static Network running;
44 private static int idleAfter = 3;
42 private static int idleAfter = 3;
45 private static int sleepProbe = 200;
43 private static int sleepProbe = 200;
46
44
@@ -64,44 +62,13 @@ public final class CrafterPipeManager implements Listener {
64 }
62 }
65 }
63 }
66
64
67 static final class SourceCache {
68 final Block block;
69 final List<PipeRef> pipes = new ArrayList<>();
70 ItemStack[] contents;
71 boolean dirty = true;
72
73 SourceCache(Block block) { this.block = block; }
74
75 void refresh() {
76 if (!dirty && contents != null) return;
77 World world = block.getWorld();
78 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) {
79 contents = new ItemStack[0];
80 dirty = false;
81 return;
82 }
83 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
84 contents = inventory == null ? new ItemStack[0] : cloneContents(inventory.getStorageContents());
85 dirty = false;
86 }
87
88 Inventory liveInventory() {
89 World world = block.getWorld();
90 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) return null;
91 return HopperStyleEndpoints.inventoryOf(block);
92 }
93 }
94
95 static final class Network {
65 static final class Network {
96 final CrafterPos pos;
66 final CrafterPos pos;
97 PipeRef outgoing;
67 PipeRef outgoing;
98 PipeRef orchestrator;
68 PipeRef orchestrator;
99 final List<PipeRef> incoming = new ArrayList<>();
69 final List<PipeRef> incoming = new ArrayList<>();
100 final List<SourceCache> sources = new ArrayList<>();
101 final ItemStack[] recipe = new ItemStack[9];
70 final ItemStack[] recipe = new ItemStack[9];
102 int recipeMask;
71 int recipeMask;
103 ItemStack[] crafterCache;
104 boolean crafterDirty = true;
105 boolean sleeping;
72 boolean sleeping;
106 int failed;
73 int failed;
107 int sleepUntil;
74 int sleepUntil;
@@ -128,13 +95,6 @@ public final class CrafterPipeManager implements Listener {
128 sleeping = false;
95 sleeping = false;
129 failed = 0;
96 failed = 0;
130 sleepUntil = 0;
97 sleepUntil = 0;
131 crafterDirty = true;
132 for (SourceCache source : sources) source.dirty = true;
133 }
134
135 void sleepUntil(int tick) {
136 sleeping = true;
137 sleepUntil = tick;
138 }
98 }
139 }
99 }
140
100
@@ -148,7 +108,7 @@ public final class CrafterPipeManager implements Listener {
148 networks.clear();
108 networks.clear();
149 outgoingIndex.clear();
109 outgoingIndex.clear();
150 appliedSlotMask.clear();
110 appliedSlotMask.clear();
151 slavedIncomingIds.clear();
111 incomingToOrchestrated.clear();
152 craftingGridIds.clear();
112 craftingGridIds.clear();
153 methodCache.clear();
113 methodCache.clear();
154 orchestratorCount = 0;
114 orchestratorCount = 0;
@@ -164,7 +124,7 @@ public final class CrafterPipeManager implements Listener {
164 try {
124 try {
165 networks.clear();
125 networks.clear();
166 outgoingIndex.clear();
126 outgoingIndex.clear();
167 slavedIncomingIds.clear();
127 incomingToOrchestrated.clear();
168 craftingGridIds.clear();
128 craftingGridIds.clear();
169 orchestratorCount = 0;
129 orchestratorCount = 0;
170 needsRetry = false;
130 needsRetry = false;
@@ -187,8 +147,7 @@ public final class CrafterPipeManager implements Listener {
187 outgoingIndex.put(network.outgoing.id, network);
147 outgoingIndex.put(network.outgoing.id, network);
188 if (network.orchestrator != null) {
148 if (network.orchestrator != null) {
189 orchestratorCount++;
149 orchestratorCount++;
190 for (PipeRef incoming : network.incoming) slavedIncomingIds.add(incoming.id);
150 for (PipeRef incoming : network.incoming) incomingToOrchestrated.add(incoming.id);
191 indexSources(network);
192 }
151 }
193 applySlotLocksNow(network);
152 applySlotLocksNow(network);
194 }
153 }
@@ -213,6 +172,65 @@ public final class CrafterPipeManager implements Listener {
213 return orchestratorCount > 0;
172 return orchestratorCount > 0;
214 }
173 }
215
174
175 /** Material filter for incoming pipes whose destination is an orchestrated crafter. */
176 public static EnumSet<Material> recipeMaterials(Block crafterBlock) {
177 Network network = networkAt(crafterBlock);
178 if (network == null || network.orchestrator == null) return null;
179 EnumSet<Material> materials = EnumSet.noneOf(Material.class);
180 for (ItemStack template : network.recipe) {
181 if (template != null) materials.add(template.getType());
182 }
183 return materials.isEmpty() ? null : materials;
184 }
185
186 public static boolean insertRecipeItem(Inventory inventory, Block block, ItemStack source) {
187 if (!validItem(source) || inventory == null || block == null) return false;
188 Network network = networkAt(block);
189 if (network == null || network.orchestrator == null) {
190 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
191 }
192 if (!allowsIncomingInsert(block, source)) return false;
193
194 ItemStack one = source.clone();
195 one.setAmount(1);
196 Crafter crafter = liveCrafter(block);
197 int maxStack = Math.min(one.getMaxStackSize(), inventory.getMaxStackSize());
198
199 for (int slot = 0; slot < 9; slot++) {
200 ItemStack template = network.recipe[slot];
201 if (template == null || !one.isSimilar(template)) continue;
202 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
203 ItemStack existing = inventory.getItem(slot);
204 if (validItem(existing)) continue;
205 ItemStack actual = inventory.getItem(slot);
206 if (validItem(actual)) continue;
207 inventory.setItem(slot, one.clone());
208 return true;
209 }
210
211 int bestSlot = -1;
212 int bestAmount = Integer.MAX_VALUE;
213 for (int slot = 0; slot < 9; slot++) {
214 ItemStack template = network.recipe[slot];
215 if (template == null || !one.isSimilar(template)) continue;
216 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
217 ItemStack existing = inventory.getItem(slot);
218 if (!validItem(existing) || !existing.isSimilar(one)) continue;
219 if (existing.getAmount() >= Math.min(existing.getMaxStackSize(), maxStack)) continue;
220 if (existing.getAmount() < bestAmount) {
221 bestAmount = existing.getAmount();
222 bestSlot = slot;
223 }
224 }
225 if (bestSlot < 0) return false;
226 ItemStack existing = inventory.getItem(bestSlot);
227 if (!validItem(existing) || existing.getAmount() != bestAmount || !existing.isSimilar(one)) return false;
228 ItemStack merged = existing.clone();
229 merged.setAmount(existing.getAmount() + 1);
230 inventory.setItem(bestSlot, merged);
231 return true;
232 }
233
216 private static void scheduleRebuild(Object owner) {
234 private static void scheduleRebuild(Object owner) {
217 Plugin p = plugin != null ? plugin : owner instanceof Plugin pl ? pl : null;
235 Plugin p = plugin != null ? plugin : owner instanceof Plugin pl ? pl : null;
218 if (p == null || scheduled) return;
236 if (p == null || scheduled) return;
@@ -226,22 +244,20 @@ public final class CrafterPipeManager implements Listener {
226
244
227 public static void invalidateBlock(Block block) {
245 public static void invalidateBlock(Block block) {
228 if (block == null || orchestratorCount == 0) return;
246 if (block == null || orchestratorCount == 0) return;
229 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
247 Network network = networkAt(block);
230 wakeMatching(block, inventory);
248 if (network != null && network.orchestrator != null) network.wake();
231 }
249 }
232
250
233 public static void invalidateInventory(Inventory inventory) {
251 public static void invalidateInventory(Inventory inventory) {
234 if (inventory == null || orchestratorCount == 0) return;
252 if (inventory == null || orchestratorCount == 0) return;
235 Block block = null;
236 try {
253 try {
237 var location = inventory.getLocation();
254 var location = inventory.getLocation();
238 if (location != null && location.getWorld() != null) block = location.getBlock();
255 if (location != null && location.getWorld() != null) invalidateBlock(location.getBlock());
239 } catch (Throwable ignored) {}
256 } catch (Throwable ignored) {}
240 wakeMatching(block, inventory);
241 }
257 }
242
258
243 public static boolean isSlavedIncoming(long connectionId) {
259 public static boolean isSlavedIncoming(long connectionId) {
244 return slavedIncomingIds.contains(connectionId);
260 return incomingToOrchestrated.contains(connectionId);
245 }
261 }
246
262
247 public static boolean isFilteredCrafterOutput(long connectionId) {
263 public static boolean isFilteredCrafterOutput(long connectionId) {
@@ -262,14 +278,13 @@ public final class CrafterPipeManager implements Listener {
262 }
278 }
263
279
264 public static boolean blocksFilter(long connectionId) {
280 public static boolean blocksFilter(long connectionId) {
265 return slavedIncomingIds.contains(connectionId);
281 return incomingToOrchestrated.contains(connectionId);
266 }
282 }
267
283
268 public static boolean isCrafter(Block block) {
284 public static boolean isCrafter(Block block) {
269 return block != null && block.getType() == Material.CRAFTER;
285 return block != null && block.getType() == Material.CRAFTER;
270 }
286 }
271
287
272 /** Minecraft orientation is {@code <dispense>_<top>}; the first token is the output face. */
273 public static BlockFace outputFace(Block block) {
288 public static BlockFace outputFace(Block block) {
274 if (!isCrafter(block)) return null;
289 if (!isCrafter(block)) return null;
275 if (!(block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data)) return BlockFace.NORTH;
290 if (!(block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data)) return BlockFace.NORTH;
@@ -292,7 +307,7 @@ public final class CrafterPipeManager implements Listener {
292
307
293 public static boolean allowsIncomingInsert(Block crafterBlock, ItemStack stack) {
308 public static boolean allowsIncomingInsert(Block crafterBlock, ItemStack stack) {
294 if (!validItem(stack)) return false;
309 if (!validItem(stack)) return false;
295 Network network = networks.get(CrafterPos.of(crafterBlock));
310 Network network = networkAt(crafterBlock);
296 if (network == null || network.orchestrator == null) return true;
311 if (network == null || network.orchestrator == null) return true;
297 for (ItemStack template : network.recipe) {
312 for (ItemStack template : network.recipe) {
298 if (template != null && stack.isSimilar(template)) return true;
313 if (template != null && stack.isSimilar(template)) return true;
@@ -309,20 +324,21 @@ public final class CrafterPipeManager implements Listener {
309 if (network.orchestrator == null) continue;
324 if (network.orchestrator == null) continue;
310 if (network.sleeping && now < network.sleepUntil) continue;
325 if (network.sleeping && now < network.sleepUntil) continue;
311 try {
326 try {
312 RunResult result = orchestrate(owner, network);
327 RunResult result = tryCraft(owner, network);
313 if (result == RunResult.MOVED || result == RunResult.STALE) {
328 if (result == RunResult.MOVED) {
314 network.sleeping = false;
329 network.sleeping = false;
315 network.failed = 0;
330 network.failed = 0;
316 } else if (result == RunResult.CRAFT_FAILED) {
331 } else if (result == RunResult.CRAFT_FAILED) {
317 network.sleepUntil(now + sleepProbe);
332 network.sleeping = true;
333 network.sleepUntil = now + sleepProbe;
318 } else if (++network.failed >= idleAfter) {
334 } else if (++network.failed >= idleAfter) {
319 network.sleepUntil(now + sleepProbe);
335 network.sleeping = true;
336 network.sleepUntil = now + sleepProbe;
320 }
337 }
321 } catch (Throwable t) {
338 } catch (Throwable t) {
322 if (plugin != null) plugin.getLogger().warning("Crafter orchestration failed: " + t);
339 if (plugin != null) plugin.getLogger().warning("Crafter orchestration failed: " + t);
323 network.crafterDirty = true;
340 network.sleeping = true;
324 for (SourceCache source : network.sources) source.dirty = true;
341 network.sleepUntil = now + sleepProbe;
325 network.sleepUntil(now + sleepProbe);
326 }
342 }
327 }
343 }
328 }
344 }
@@ -358,16 +374,15 @@ public final class CrafterPipeManager implements Listener {
358 }
374 }
359 event.setCancelled(true);
375 event.setCancelled(true);
360 event.setResult(new ItemStack(Material.AIR));
376 event.setResult(new ItemStack(Material.AIR));
361 network.crafterDirty = true;
362 if (network.outgoing.destBlock != null) {
377 if (network.outgoing.destBlock != null) {
363 OptimizedTransferPlanner.invalidateBlock(plugin, network.outgoing.destBlock);
378 OptimizedTransferPlanner.invalidateBlock(plugin, network.outgoing.destBlock);
364 }
379 }
365 OptimizedTransferPlanner.invalidateBlock(plugin, block);
380 OptimizedTransferPlanner.invalidateBlock(plugin, block);
366 }
381 }
367
382
368 private enum RunResult { MOVED, NO_MOVE, STALE, CRAFT_FAILED }
383 private enum RunResult { MOVED, NO_MOVE, CRAFT_FAILED }
369
384
370 private static RunResult orchestrate(Object owner, Network network) {
385 private static RunResult tryCraft(Object owner, Network network) {
371 World world = Bukkit.getWorld(network.pos.world);
386 World world = Bukkit.getWorld(network.pos.world);
372 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return RunResult.NO_MOVE;
387 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return RunResult.NO_MOVE;
373
388
@@ -375,65 +390,56 @@ public final class CrafterPipeManager implements Listener {
375 if (block.getType() != Material.CRAFTER) return RunResult.NO_MOVE;
390 if (block.getType() != Material.CRAFTER) return RunResult.NO_MOVE;
376 if (isBusy(block)) return RunResult.NO_MOVE;
391 if (isBusy(block)) return RunResult.NO_MOVE;
377
392
378 running = network;
393 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
379 try {
394 applySlotLocksNow(network);
380 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
395 }
381 applySlotLocksNow(network);
382 }
383
396
384 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
397 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
385 if (crafterInv == null) return RunResult.NO_MOVE;
398 if (crafterInv == null) return RunResult.NO_MOVE;
386 refreshCrafterCache(network, crafterInv);
387
399
388 if (gridMatchesRecipe(network.crafterCache, network.recipe)) {
400 ItemStack[] grid = readGrid(crafterInv);
389 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
401 if (hasJunk(grid, network.recipe)) return RunResult.CRAFT_FAILED;
390 }
402 if (!gridMatchesRecipe(grid, network.recipe)) return RunResult.NO_MOVE;
391 if (!gridEmpty(network.crafterCache)) return RunResult.CRAFT_FAILED;
403
404 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
405 }
392
406
393 for (SourceCache source : network.sources) source.refresh();
407 private static ItemStack[] readGrid(Inventory inventory) {
394 Pull[] pulls = planPulls(network.sources, network.recipe);
408 ItemStack[] storage = inventory.getStorageContents();
395 if (pulls == null) return RunResult.NO_MOVE;
409 ItemStack[] grid = new ItemStack[9];
410 int limit = Math.min(9, storage.length);
411 for (int slot = 0; slot < limit; slot++) {
412 ItemStack item = storage[slot];
413 grid[slot] = validItem(item) ? item.clone() : null;
414 }
415 return grid;
416 }
396
417
397 List<Take> takes = new ArrayList<>(9);
418 private static boolean hasJunk(ItemStack[] grid, ItemStack[] recipe) {
398 ItemStack[] placed = new ItemStack[9];
419 for (int slot = 0; slot < 9; slot++) {
399 for (int slot = 0; slot < 9; slot++) {
420 ItemStack want = recipe[slot];
400 Pull pull = pulls[slot];
421 ItemStack have = grid[slot];
401 if (pull == null) continue;
422 if (want == null) {
402 Inventory live = pull.source.liveInventory();
423 if (validItem(have)) return true;
403 if (live == null) {
424 } else if (validItem(have) && !have.isSimilar(want)) {
404 restoreTakes(takes);
425 return true;
405 return RunResult.NO_MOVE;
406 }
407 ItemStack expected = pull.source.contents[pull.invSlot];
408 if (!slotMatches(live, pull.invSlot, expected)) {
409 pull.source.dirty = true;
410 restoreTakes(takes);
411 return RunResult.STALE;
412 }
413 ItemStack before = takeOne(live, pull.invSlot, network.recipe[slot]);
414 if (before == null) {
415 pull.source.dirty = true;
416 restoreTakes(takes);
417 return RunResult.STALE;
418 }
419 takes.add(new Take(live, pull.invSlot, before, pull.source, expected));
420 decrementCache(pull.source, pull.invSlot);
421 ItemStack one = before.clone();
422 one.setAmount(1);
423 placed[slot] = one;
424 }
426 }
427 }
428 return false;
429 }
425
430
426 writeGrid(crafterInv, placed);
431 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
427 network.crafterCache = cloneContents(placed);
432 if (grid == null) return false;
428 network.crafterDirty = false;
433 for (int slot = 0; slot < 9; slot++) {
429 for (SourceCache source : network.sources) {
434 ItemStack want = recipe[slot];
430 if (!source.dirty) OptimizedTransferPlanner.invalidateBlock(owner, source.block);
435 ItemStack have = grid[slot];
436 if (want == null) {
437 if (validItem(have)) return false;
438 } else if (!validItem(have) || !have.isSimilar(want)) {
439 return false;
431 }
440 }
432
433 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
434 } finally {
435 running = null;
436 }
441 }
442 return true;
437 }
443 }
438
444
439 private static boolean triggerCraft(Object owner, Network network, Block block) {
445 private static boolean triggerCraft(Object owner, Network network, Block block) {
@@ -454,7 +460,6 @@ public final class CrafterPipeManager implements Listener {
454 return false;
460 return false;
455 } finally {
461 } finally {
456 network.attemptingCraft = false;
462 network.attemptingCraft = false;
457 network.crafterDirty = true;
458 if (network.outgoing != null && network.outgoing.destBlock != null) {
463 if (network.outgoing != null && network.outgoing.destBlock != null) {
459 OptimizedTransferPlanner.invalidateBlock(owner, network.outgoing.destBlock);
464 OptimizedTransferPlanner.invalidateBlock(owner, network.outgoing.destBlock);
460 }
465 }
@@ -473,41 +478,6 @@ public final class CrafterPipeManager implements Listener {
473 }
478 }
474 }
479 }
475
480
476 private static void refreshCrafterCache(Network network, Inventory inventory) {
477 if (!network.crafterDirty && network.crafterCache != null) return;
478 ItemStack[] storage = inventory.getStorageContents();
479 ItemStack[] grid = new ItemStack[9];
480 int limit = Math.min(9, storage.length);
481 for (int slot = 0; slot < limit; slot++) {
482 ItemStack item = storage[slot];
483 grid[slot] = validItem(item) ? item.clone() : null;
484 }
485 network.crafterCache = grid;
486 network.crafterDirty = false;
487 }
488
489 private static boolean gridEmpty(ItemStack[] grid) {
490 if (grid == null) return true;
491 for (ItemStack item : grid) {
492 if (validItem(item)) return false;
493 }
494 return true;
495 }
496
497 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
498 if (grid == null) return false;
499 for (int slot = 0; slot < 9; slot++) {
500 ItemStack want = recipe[slot];
501 ItemStack have = slot < grid.length ? grid[slot] : null;
502 if (want == null) {
503 if (validItem(have)) return false;
504 } else if (!validItem(have) || !have.isSimilar(want)) {
505 return false;
506 }
507 }
508 return true;
509 }
510
511 private static boolean routeOutgoing(Object owner, PipeRef outgoing, ItemStack item) {
481 private static boolean routeOutgoing(Object owner, PipeRef outgoing, ItemStack item) {
512 try {
482 try {
513 if (!validItem(item) || outgoing == null) return false;
483 if (!validItem(item) || outgoing == null) return false;
@@ -598,6 +568,11 @@ public final class CrafterPipeManager implements Listener {
598 return false;
568 return false;
599 }
569 }
600
570
571 private static Network networkAt(Block block) {
572 if (block == null || block.getType() != Material.CRAFTER) return null;
573 return networks.get(CrafterPos.of(block));
574 }
575
601 private static void applySlotLocksNow(Network network) {
576 private static void applySlotLocksNow(Network network) {
602 World world = Bukkit.getWorld(network.pos.world);
577 World world = Bukkit.getWorld(network.pos.world);
603 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return;
578 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return;
@@ -620,101 +595,6 @@ public final class CrafterPipeManager implements Listener {
620 try { crafter.update(true, false); } catch (Throwable ignored) {}
595 try { crafter.update(true, false); } catch (Throwable ignored) {}
621 }
596 }
622
597
623 private static Pull[] planPulls(List<SourceCache> sources, ItemStack[] recipe) {
624 Pull[] pulls = new Pull[9];
625 int needed = 0;
626 int[][] reserved = new int[sources.size()][];
627 for (int i = 0; i < sources.size(); i++) {
628 ItemStack[] contents = sources.get(i).contents;
629 reserved[i] = new int[contents == null ? 0 : contents.length];
630 }
631 for (int slot = 0; slot < 9; slot++) {
632 ItemStack template = recipe[slot];
633 if (template == null) continue;
634 needed++;
635 Pull pull = null;
636 for (int s = 0; s < sources.size(); s++) {
637 SourceCache source = sources.get(s);
638 ItemStack[] contents = source.contents;
639 if (contents == null) continue;
640 for (int invSlot = 0; invSlot < contents.length; invSlot++) {
641 ItemStack stack = contents[invSlot];
642 if (!validItem(stack) || !stack.isSimilar(template)) continue;
643 if (stack.getAmount() <= reserved[s][invSlot]) continue;
644 reserved[s][invSlot]++;
645 pull = new Pull(source, invSlot);
646 break;
647 }
648 if (pull != null) break;
649 }
650 if (pull == null) return null;
651 pulls[slot] = pull;
652 }
653 return needed == 0 ? null : pulls;
654 }
655
656 private static boolean slotMatches(Inventory inventory, int slot, ItemStack expected) {
657 ItemStack actual = inventory.getItem(slot);
658 if (expected == null || expected.getType().isAir()) {
659 return actual == null || actual.getType().isAir();
660 }
661 if (actual == null || actual.getType().isAir()) return false;
662 return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
663 }
664
665 private static ItemStack takeOne(Inventory inventory, int slot, ItemStack template) {
666 ItemStack have = inventory.getItem(slot);
667 if (!validItem(have) || (template != null && !have.isSimilar(template))) return null;
668 ItemStack before = have.clone();
669 if (have.getAmount() <= 1) inventory.setItem(slot, null);
670 else {
671 ItemStack reduced = have.clone();
672 reduced.setAmount(have.getAmount() - 1);
673 inventory.setItem(slot, reduced);
674 }
675 return before;
676 }
677
678 private static void decrementCache(SourceCache source, int slot) {
679 if (source.contents == null || slot < 0 || slot >= source.contents.length) return;
680 ItemStack have = source.contents[slot];
681 if (!validItem(have)) return;
682 if (have.getAmount() <= 1) source.contents[slot] = null;
683 else {
684 ItemStack reduced = have.clone();
685 reduced.setAmount(have.getAmount() - 1);
686 source.contents[slot] = reduced;
687 }
688 }
689
690 private static void restoreTakes(List<Take> takes) {
691 for (int i = takes.size() - 1; i >= 0; i--) {
692 Take take = takes.get(i);
693 take.inventory.setItem(take.slot, take.before);
694 if (take.source.contents != null && take.slot < take.source.contents.length) {
695 take.source.contents[take.slot] = take.cachedBefore == null ? null : take.cachedBefore.clone();
696 }
697 }
698 }
699
700 private static void writeGrid(Inventory inventory, ItemStack[] placed) {
701 int limit = Math.min(9, inventory.getSize());
702 for (int slot = 0; slot < limit; slot++) {
703 ItemStack item = placed[slot];
704 inventory.setItem(slot, validItem(item) ? item.clone() : null);
705 }
706 }
707
708 private static ItemStack[] cloneContents(ItemStack[] input) {
709 ItemStack[] copy = new ItemStack[input.length];
710 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
711 return copy;
712 }
713
714 private record Pull(SourceCache source, int invSlot) {}
715
716 private record Take(Inventory inventory, int slot, ItemStack before, SourceCache source, ItemStack cachedBefore) {}
717
718 private static Crafter liveCrafter(Block block) {
598 private static Crafter liveCrafter(Block block) {
719 try {
599 try {
720 BlockState state = block.getState(false);
600 BlockState state = block.getState(false);
@@ -735,80 +615,7 @@ public final class CrafterPipeManager implements Listener {
735 private static void playTransferEffects(Network network) {
615 private static void playTransferEffects(Network network) {
736 if (!(plugin instanceof ContainerPipesPlugin pipes)) return;
616 if (!(plugin instanceof ContainerPipesPlugin pipes)) return;
737 if (network.outgoing != null) pipes.playTransferAnimation(network.outgoing.raw);
617 if (network.outgoing != null) pipes.playTransferAnimation(network.outgoing.raw);
738 for (SourceCache source : network.sources) {
618 for (PipeRef incoming : network.incoming) pipes.playTransferAnimation(incoming.raw);
739 for (PipeRef incoming : source.pipes) pipes.playTransferAnimation(incoming.raw);
740 }
741 }
742
743 private static void wakeMatching(Block block, Inventory inventory) {
744 CrafterPos pos = block == null ? null : CrafterPos.of(block);
745 for (Network network : networks.values()) {
746 if (network.orchestrator == null) continue;
747 if (network == running) {
748 network.crafterDirty = true;
749 continue;
750 }
751 if (pos != null && network.pos.equals(pos)) {
752 network.wake();
753 continue;
754 }
755 if (pos != null && network.outgoing != null && network.outgoing.destBlock != null
756 && CrafterPos.of(network.outgoing.destBlock).equals(pos)) {
757 network.wake();
758 continue;
759 }
760 if (matchesSource(network, block, inventory)) network.wake();
761 }
762 }
763
764 private static boolean matchesSource(Network network, Block block, Inventory inventory) {
765 Integer invX = null, invY = null, invZ = null;
766 World invWorld = null;
767 if (inventory != null) {
768 try {
769 var location = inventory.getLocation();
770 if (location != null && location.getWorld() != null) {
771 invWorld = location.getWorld();
772 invX = location.getBlockX();
773 invY = location.getBlockY();
774 invZ = location.getBlockZ();
775 }
776 } catch (Throwable ignored) {}
777 }
778 for (SourceCache source : network.sources) {
779 if (block != null && source.block.getWorld() == block.getWorld()
780 && source.block.getX() == block.getX()
781 && source.block.getY() == block.getY()
782 && source.block.getZ() == block.getZ()) {
783 return true;
784 }
785 if (invWorld != null && source.block.getWorld() == invWorld
786 && source.block.getX() == invX
787 && source.block.getY() == invY
788 && source.block.getZ() == invZ) {
789 return true;
790 }
791 }
792 return false;
793 }
794
795 private static void indexSources(Network network) {
796 network.sources.clear();
797 Map<String, SourceCache> byBlock = new LinkedHashMap<>();
798 for (PipeRef incoming : network.incoming) {
799 Block block = incoming.sourceBlock;
800 if (block == null) continue;
801 String key = block.getWorld().getUID() + ":" + block.getX() + "," + block.getY() + "," + block.getZ();
802 SourceCache cache = byBlock.get(key);
803 if (cache == null) {
804 cache = new SourceCache(block);
805 byBlock.put(key, cache);
806 }
807 cache.pipes.add(incoming);
808 }
809 network.sources.addAll(byBlock.values());
810 network.crafterDirty = true;
811 network.wake();
812 }
619 }
813
620
814 private static boolean stripIncomingFilters(Object owner) {
621 private static boolean stripIncomingFilters(Object owner) {
src/main/java/nl/timfalken/containerpipes/OptimizedTransferPlanner.java +18 −7
@@ -288,8 +288,7 @@ public final class OptimizedTransferPlanner {
288 288 for (Object rawConnection : raw.values()) {
289 289 try {
290 290 ConnectionView connection = ConnectionView.read(rawConnection);
291 if (CrafterPipeManager.isSlavedIncoming(connection.id)
292 || CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
291 if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
293 292 ContainerKey sourceKey = endpointKey(connection.source);
294 293 groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);
295 294 } catch (Throwable t) {
@@ -503,10 +502,19 @@ public final class OptimizedTransferPlanner {
503 502 Group(ContainerKey key) { this.key = key; }
504 503
505 504 void rebuildCache() {
505 filtered.clear();
506 unfiltered.clear();
507 reserved.clear();
508 destinationKeys.clear();
506 509 for (ConnectionView connection : connections) {
507 if (CrafterPipeManager.isSlavedIncoming(connection.id)) continue;
508 510 if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
509 if (connection.filters.isEmpty()) unfiltered.add(connection);
511 Block destinationBlock = blockAt(connection.destination);
512 EnumSet<Material> crafterRecipe = destinationBlock == null
513 ? null : CrafterPipeManager.recipeMaterials(destinationBlock);
514 if (crafterRecipe != null && !crafterRecipe.isEmpty()) {
515 filtered.add(connection);
516 reserved.addAll(crafterRecipe);
517 } else if (connection.filters.isEmpty()) unfiltered.add(connection);
510 518 else {
511 519 filtered.add(connection);
512 520 reserved.addAll(connection.filters);
@@ -808,6 +816,9 @@ public final class OptimizedTransferPlanner {
808 816 ignored -> new DestinationState(destination));
809 817 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
810 818 syncIncomingCache(destinationKey, state);
819 if (destination.getType() == InventoryType.CRAFTER) {
820 CrafterPipeManager.invalidateBlock(destinationBlock);
821 }
811 822 afterTransfer(connection, inventoryAt(connection.source), destination);
812 823 return new TransferResult(true, destinationKey);
813 824 }
@@ -850,10 +861,10 @@ public final class OptimizedTransferPlanner {
850 861 boolean insertOne(ItemStack source) {
851 862 if (inventory.getType() == InventoryType.CRAFTER) {
852 863 Block block = inventory.getLocation() == null ? null : inventory.getLocation().getBlock();
853 if (CrafterPipeManager.hasOrchestrators()) {
854 if (block != null && CrafterPipeManager.isOrchestrated(block)) return false;
855 if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;
864 if (block != null && CrafterPipeManager.isOrchestrated(block)) {
865 return CrafterPipeManager.insertRecipeItem(inventory, block, source);
856 866 }
867 if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;
857 868 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
858 869 }
859 870
@@ -288,8 +288,7 @@ public final class OptimizedTransferPlanner {
288 for (Object rawConnection : raw.values()) {
288 for (Object rawConnection : raw.values()) {
289 try {
289 try {
290 ConnectionView connection = ConnectionView.read(rawConnection);
290 ConnectionView connection = ConnectionView.read(rawConnection);
291 if (CrafterPipeManager.isSlavedIncoming(connection.id)
291 if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
292 || CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
293 ContainerKey sourceKey = endpointKey(connection.source);
292 ContainerKey sourceKey = endpointKey(connection.source);
294 groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);
293 groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);
295 } catch (Throwable t) {
294 } catch (Throwable t) {
@@ -503,10 +502,19 @@ public final class OptimizedTransferPlanner {
503 Group(ContainerKey key) { this.key = key; }
502 Group(ContainerKey key) { this.key = key; }
504
503
505 void rebuildCache() {
504 void rebuildCache() {
505 filtered.clear();
506 unfiltered.clear();
507 reserved.clear();
508 destinationKeys.clear();
506 for (ConnectionView connection : connections) {
509 for (ConnectionView connection : connections) {
507 if (CrafterPipeManager.isSlavedIncoming(connection.id)) continue;
508 if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
510 if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
509 if (connection.filters.isEmpty()) unfiltered.add(connection);
511 Block destinationBlock = blockAt(connection.destination);
512 EnumSet<Material> crafterRecipe = destinationBlock == null
513 ? null : CrafterPipeManager.recipeMaterials(destinationBlock);
514 if (crafterRecipe != null && !crafterRecipe.isEmpty()) {
515 filtered.add(connection);
516 reserved.addAll(crafterRecipe);
517 } else if (connection.filters.isEmpty()) unfiltered.add(connection);
510 else {
518 else {
511 filtered.add(connection);
519 filtered.add(connection);
512 reserved.addAll(connection.filters);
520 reserved.addAll(connection.filters);
@@ -808,6 +816,9 @@ public final class OptimizedTransferPlanner {
808 ignored -> new DestinationState(destination));
816 ignored -> new DestinationState(destination));
809 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
817 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
810 syncIncomingCache(destinationKey, state);
818 syncIncomingCache(destinationKey, state);
819 if (destination.getType() == InventoryType.CRAFTER) {
820 CrafterPipeManager.invalidateBlock(destinationBlock);
821 }
811 afterTransfer(connection, inventoryAt(connection.source), destination);
822 afterTransfer(connection, inventoryAt(connection.source), destination);
812 return new TransferResult(true, destinationKey);
823 return new TransferResult(true, destinationKey);
813 }
824 }
@@ -850,10 +861,10 @@ public final class OptimizedTransferPlanner {
850 boolean insertOne(ItemStack source) {
861 boolean insertOne(ItemStack source) {
851 if (inventory.getType() == InventoryType.CRAFTER) {
862 if (inventory.getType() == InventoryType.CRAFTER) {
852 Block block = inventory.getLocation() == null ? null : inventory.getLocation().getBlock();
863 Block block = inventory.getLocation() == null ? null : inventory.getLocation().getBlock();
853 if (CrafterPipeManager.hasOrchestrators()) {
864 if (block != null && CrafterPipeManager.isOrchestrated(block)) {
854 if (block != null && CrafterPipeManager.isOrchestrated(block)) return false;
865 return CrafterPipeManager.insertRecipeItem(inventory, block, source);
855 if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;
856 }
866 }
867 if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;
857 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
868 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
858 }
869 }
859
870