BlueGit

timfa containerpipes

Add powder-snow liquids and face-independent hopper-style endpoints.

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

timfa Tim Falken · pushed by timfa

Authored 2026-08-11 · 3 months ago

Hash
b625649bbf160016fdf1ebe60027d0e281efb785
Parent
367f8cfe
9 files changed +627 −79
README.md +39 −7
@@ -1,12 +1,44 @@
1 # ContainerPipes 1.7.0
1 # ContainerPipes 1.7.1
2 2
3 Adds two endpoint families on top of 1.6.4:
3 Builds on 1.7.0 (Crafter destinations + liquid cauldron pipes).
4 4
5 - **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
6 - **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
5 ## Powder snow liquids
7 6
8 Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
7 `POWDER_SNOW_CAULDRON` is a third transferable liquid, with the same 3-level `Levelled` behaviour as water:
9 8
10 Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
9 - one cauldron level moves per transfer interval
10 - empty `CAULDRON` ↔ powder snow levels work like water
11 - water, lava and powder snow never mix (incompatible destination → no transfer)
11 12
12 Existing connections.tsv and config.yml remain compatible.
13 Particle: `SNOWFLAKE` (water/lava still use `DRIPPING_WATER` / `DRIPPING_LAVA`).
14
15 ## Cauldron endpoint identity
16
17 A liquid endpoint is the **cauldron position**, not the current block material. The same pipe stays valid across:
18
19 `CAULDRON` ↔ `WATER_CAULDRON` ↔ `LAVA_CAULDRON` ↔ `POWDER_SNOW_CAULDRON`
20
21 ## Hopper-style containers (face-independent)
22
23 Pipes support the same container interactions hoppers do, but **slot choice does not depend on which face the pipe attaches to**. Incoming vs outgoing pipes plus Paper slot rules decide the behaviour.
24
25 | Endpoint | Behaviour |
26 |---|---|
27 | Chest / barrel / copper chest / hopper / dispenser / dropper / shelf / shulker | Normal storage (shulker-in-shulker blocked via `Tag.SHULKER_BOXES`) |
28 | Furnace / blast furnace / smoker | Insert: `canSmelt` then `isFuel`. Extract: result slot only |
29 | Crafter | Destination-only; live disabled slots |
30 | Brewing stand | Insert: ingredient → fuel (`Tag.ITEMS_BREWING_FUEL`) → bottles, each gated by Paper/NMS `canPlaceItem`. Extract: bottle slots only |
31 | Composter | Insert: `Material.isCompostable()` + `getCompostChance()`. Extract: bone meal at max level. Level cache only (no slot cache) |
32 | Chiseled bookshelf | Normal slot cache; insert gated by `Tag.ITEMS_BOOKSHELF_BOOKS` |
33 | Decorated pot | Single-item stack via `DecoratedPotInventory` |
34 | Jukebox | Insert if `DataComponentTypes.JUKEBOX_PLAYABLE`; extract when not playing |
35
36 Not supported (hoppers cannot either): ender chest, lectern. Minecarts/entities and redstone locking are ignored.
37
38 Item legality always comes from Paper APIs / datapack tags — not hardcoded item lists — so datapack changes stay compatible.
39
40 ## Still from 1.7.0
41
42 Liquid pipes: liquid → liquid only; no filter UI; shift + shears removes. Wakeups via `CauldronLevelChangeEvent` + cache + emergency probe.
43
44 Existing `connections.tsv` and `config.yml` remain compatible.
@@ -1,12 +1,44 @@
1# ContainerPipes 1.7.0
1# ContainerPipes 1.7.1
2
2
3Adds two endpoint families on top of 1.6.4:
3Builds on 1.7.0 (Crafter destinations + liquid cauldron pipes).
4
4
5- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
5## Powder snow liquids
6- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
7
6
8Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
7`POWDER_SNOW_CAULDRON` is a third transferable liquid, with the same 3-level `Levelled` behaviour as water:
9
8
10Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
9- one cauldron level moves per transfer interval
10- empty `CAULDRON` ↔ powder snow levels work like water
11- water, lava and powder snow never mix (incompatible destination → no transfer)
11
12
12Existing connections.tsv and config.yml remain compatible.
13Particle: `SNOWFLAKE` (water/lava still use `DRIPPING_WATER` / `DRIPPING_LAVA`).
14
15## Cauldron endpoint identity
16
17A liquid endpoint is the **cauldron position**, not the current block material. The same pipe stays valid across:
18
19`CAULDRON` ↔ `WATER_CAULDRON` ↔ `LAVA_CAULDRON` ↔ `POWDER_SNOW_CAULDRON`
20
21## Hopper-style containers (face-independent)
22
23Pipes support the same container interactions hoppers do, but **slot choice does not depend on which face the pipe attaches to**. Incoming vs outgoing pipes plus Paper slot rules decide the behaviour.
24
25| Endpoint | Behaviour |
26|---|---|
27| Chest / barrel / copper chest / hopper / dispenser / dropper / shelf / shulker | Normal storage (shulker-in-shulker blocked via `Tag.SHULKER_BOXES`) |
28| Furnace / blast furnace / smoker | Insert: `canSmelt` then `isFuel`. Extract: result slot only |
29| Crafter | Destination-only; live disabled slots |
30| Brewing stand | Insert: ingredient → fuel (`Tag.ITEMS_BREWING_FUEL`) → bottles, each gated by Paper/NMS `canPlaceItem`. Extract: bottle slots only |
31| Composter | Insert: `Material.isCompostable()` + `getCompostChance()`. Extract: bone meal at max level. Level cache only (no slot cache) |
32| Chiseled bookshelf | Normal slot cache; insert gated by `Tag.ITEMS_BOOKSHELF_BOOKS` |
33| Decorated pot | Single-item stack via `DecoratedPotInventory` |
34| Jukebox | Insert if `DataComponentTypes.JUKEBOX_PLAYABLE`; extract when not playing |
35
36Not supported (hoppers cannot either): ender chest, lectern. Minecarts/entities and redstone locking are ignored.
37
38Item legality always comes from Paper APIs / datapack tags — not hardcoded item lists — so datapack changes stay compatible.
39
40## Still from 1.7.0
41
42Liquid pipes: liquid → liquid only; no filter UI; shift + shears removes. Wakeups via `CauldronLevelChangeEvent` + cache + emergency probe.
43
44Existing `connections.tsv` and `config.yml` remain compatible.
build.gradle.kts +1 −1
@@ -1,6 +1,6 @@
1 1 plugins { java }
2 2 group = "nl.timfalken"
3 version = "1.7.0"
3 version = "1.7.1"
4 4 repositories {
5 5 maven {
6 6 name = "papermc"
@@ -1,6 +1,6 @@
1plugins { java }
1plugins { java }
2group = "nl.timfalken"
2group = "nl.timfalken"
3version = "1.7.0"
3version = "1.7.1"
4repositories {
4repositories {
5 maven {
5 maven {
6 name = "papermc"
6 name = "papermc"
src/README-1.7.0.md deleted +0 −12
@@ -1,12 +0,0 @@
1 # ContainerPipes 1.7.0
2
3 Adds two endpoint families on top of 1.6.4:
4
5 - **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
6 - **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
7
8 Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
9
10 Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
11
12 Existing connections.tsv and config.yml remain compatible.
@@ -1,12 +0,0 @@
1# ContainerPipes 1.7.0
2
3Adds two endpoint families on top of 1.6.4:
4
5- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
6- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
7
8Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
9
10Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
11
12Existing connections.tsv and config.yml remain compatible.
src/README-1.7.1.md added +44 −0
@@ -0,0 +1,44 @@
1 # ContainerPipes 1.7.1
2
3 Builds on 1.7.0 (Crafter destinations + liquid cauldron pipes).
4
5 ## Powder snow liquids
6
7 `POWDER_SNOW_CAULDRON` is a third transferable liquid, with the same 3-level `Levelled` behaviour as water:
8
9 - one cauldron level moves per transfer interval
10 - empty `CAULDRON` ↔ powder snow levels work like water
11 - water, lava and powder snow never mix (incompatible destination → no transfer)
12
13 Particle: `SNOWFLAKE` (water/lava still use `DRIPPING_WATER` / `DRIPPING_LAVA`).
14
15 ## Cauldron endpoint identity
16
17 A liquid endpoint is the **cauldron position**, not the current block material. The same pipe stays valid across:
18
19 `CAULDRON` ↔ `WATER_CAULDRON` ↔ `LAVA_CAULDRON` ↔ `POWDER_SNOW_CAULDRON`
20
21 ## Hopper-style containers (face-independent)
22
23 Pipes support the same container interactions hoppers do, but **slot choice does not depend on which face the pipe attaches to**. Incoming vs outgoing pipes plus Paper slot rules decide the behaviour.
24
25 | Endpoint | Behaviour |
26 |---|---|
27 | Chest / barrel / copper chest / hopper / dispenser / dropper / shelf / shulker | Normal storage (shulker-in-shulker blocked via `Tag.SHULKER_BOXES`) |
28 | Furnace / blast furnace / smoker | Insert: `canSmelt` then `isFuel`. Extract: result slot only |
29 | Crafter | Destination-only; live disabled slots |
30 | Brewing stand | Insert: ingredient → fuel (`Tag.ITEMS_BREWING_FUEL`) → bottles, each gated by Paper/NMS `canPlaceItem`. Extract: bottle slots only |
31 | Composter | Insert: `Material.isCompostable()` + `getCompostChance()`. Extract: bone meal at max level. Level cache only (no slot cache) |
32 | Chiseled bookshelf | Normal slot cache; insert gated by `Tag.ITEMS_BOOKSHELF_BOOKS` |
33 | Decorated pot | Single-item stack via `DecoratedPotInventory` |
34 | Jukebox | Insert if `DataComponentTypes.JUKEBOX_PLAYABLE`; extract when not playing |
35
36 Not supported (hoppers cannot either): ender chest, lectern. Minecarts/entities and redstone locking are ignored.
37
38 Item legality always comes from Paper APIs / datapack tags — not hardcoded item lists — so datapack changes stay compatible.
39
40 ## Still from 1.7.0
41
42 Liquid pipes: liquid → liquid only; no filter UI; shift + shears removes. Wakeups via `CauldronLevelChangeEvent` + cache + emergency probe.
43
44 Existing `connections.tsv` and `config.yml` remain compatible.
@@ -0,0 +1,44 @@
1# ContainerPipes 1.7.1
2
3Builds on 1.7.0 (Crafter destinations + liquid cauldron pipes).
4
5## Powder snow liquids
6
7`POWDER_SNOW_CAULDRON` is a third transferable liquid, with the same 3-level `Levelled` behaviour as water:
8
9- one cauldron level moves per transfer interval
10- empty `CAULDRON` ↔ powder snow levels work like water
11- water, lava and powder snow never mix (incompatible destination → no transfer)
12
13Particle: `SNOWFLAKE` (water/lava still use `DRIPPING_WATER` / `DRIPPING_LAVA`).
14
15## Cauldron endpoint identity
16
17A liquid endpoint is the **cauldron position**, not the current block material. The same pipe stays valid across:
18
19`CAULDRON` ↔ `WATER_CAULDRON` ↔ `LAVA_CAULDRON` ↔ `POWDER_SNOW_CAULDRON`
20
21## Hopper-style containers (face-independent)
22
23Pipes support the same container interactions hoppers do, but **slot choice does not depend on which face the pipe attaches to**. Incoming vs outgoing pipes plus Paper slot rules decide the behaviour.
24
25| Endpoint | Behaviour |
26|---|---|
27| Chest / barrel / copper chest / hopper / dispenser / dropper / shelf / shulker | Normal storage (shulker-in-shulker blocked via `Tag.SHULKER_BOXES`) |
28| Furnace / blast furnace / smoker | Insert: `canSmelt` then `isFuel`. Extract: result slot only |
29| Crafter | Destination-only; live disabled slots |
30| Brewing stand | Insert: ingredient → fuel (`Tag.ITEMS_BREWING_FUEL`) → bottles, each gated by Paper/NMS `canPlaceItem`. Extract: bottle slots only |
31| Composter | Insert: `Material.isCompostable()` + `getCompostChance()`. Extract: bone meal at max level. Level cache only (no slot cache) |
32| Chiseled bookshelf | Normal slot cache; insert gated by `Tag.ITEMS_BOOKSHELF_BOOKS` |
33| Decorated pot | Single-item stack via `DecoratedPotInventory` |
34| Jukebox | Insert if `DataComponentTypes.JUKEBOX_PLAYABLE`; extract when not playing |
35
36Not supported (hoppers cannot either): ender chest, lectern. Minecarts/entities and redstone locking are ignored.
37
38Item legality always comes from Paper APIs / datapack tags — not hardcoded item lists — so datapack changes stay compatible.
39
40## Still from 1.7.0
41
42Liquid pipes: liquid → liquid only; no filter UI; shift + shears removes. Wakeups via `CauldronLevelChangeEvent` + cache + emergency probe.
43
44Existing `connections.tsv` and `config.yml` remain compatible.
src/main/java/nl/timfalken/containerpipes/AdvancedEndpointsPatch.java +34 −16
@@ -378,8 +378,13 @@ public final class AdvancedEndpointsPatch {
378 378 if (!destination.accepts(source.type)) return false;
379 379
380 380 if (source.type == FluidType.WATER) {
381 setWaterLevel(sourceBlock, source.level - 1);
382 setWaterLevel(destinationBlock, destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
381 setLevelledCauldron(sourceBlock, "WATER_CAULDRON", source.level - 1);
382 setLevelledCauldron(destinationBlock, "WATER_CAULDRON",
383 destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
384 } else if (source.type == FluidType.POWDER_SNOW) {
385 setLevelledCauldron(sourceBlock, "POWDER_SNOW_CAULDRON", source.level - 1);
386 setLevelledCauldron(destinationBlock, "POWDER_SNOW_CAULDRON",
387 destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
383 388 } else if (source.type == FluidType.LAVA) {
384 389 setEmpty(sourceBlock);
385 390 setLava(destinationBlock);
@@ -399,9 +404,10 @@ public final class AdvancedEndpointsPatch {
399 404 return true;
400 405 }
401 406
402 void setWaterLevel(Object block, int level) throws Exception {
407 /** Water and powder snow share Levelled cauldron data (1..max, 0 = empty CAULDRON). */
408 void setLevelledCauldron(Object block, String filledMaterial, int level) throws Exception {
403 409 if (level <= 0) { setEmpty(block); return; }
404 if (!"WATER_CAULDRON".equals(materialName(block))) setBlockType(block, "WATER_CAULDRON");
410 if (!filledMaterial.equals(materialName(block))) setBlockType(block, filledMaterial);
405 411 Object data = call(block, "getBlockData");
406 412 call(data, "setLevel", new Class<?>[]{int.class}, level);
407 413 call(block, "setBlockData", new Class<?>[]{Class.forName("org.bukkit.block.data.BlockData", false, plugin.getClass().getClassLoader())}, data);
@@ -421,18 +427,20 @@ public final class AdvancedEndpointsPatch {
421 427 String name = materialName(block);
422 428 if ("CAULDRON".equals(name)) return new FluidState(FluidType.EMPTY, 0, 0);
423 429 if ("LAVA_CAULDRON".equals(name)) return new FluidState(FluidType.LAVA, 1, 1);
424 if ("WATER_CAULDRON".equals(name)) {
425 Object data = call(block, "getBlockData");
426 int level = ((Number) call(data, "getLevel")).intValue();
427 int max = ((Number) call(data, "getMaximumLevel")).intValue();
428 return new FluidState(FluidType.WATER, level, max);
429 }
430 // Keep a pipe attached if a cauldron temporarily contains an unsupported
431 // medium (e.g. powder snow), but never mix/transfer it as a liquid.
430 if ("WATER_CAULDRON".equals(name)) return readLevelledFluid(block, FluidType.WATER);
431 if ("POWDER_SNOW_CAULDRON".equals(name)) return readLevelledFluid(block, FluidType.POWDER_SNOW);
432 // Unknown cauldron variant: keep the pipe (same position family) but do not transfer.
432 433 if (isCauldronMaterial(name)) return new FluidState(FluidType.OTHER, 1, 1);
433 434 return new FluidState(FluidType.OTHER, 0, 0);
434 435 }
435 436
437 FluidState readLevelledFluid(Object block, FluidType type) throws Exception {
438 Object data = call(block, "getBlockData");
439 int level = ((Number) call(data, "getLevel")).intValue();
440 int max = ((Number) call(data, "getMaximumLevel")).intValue();
441 return new FluidState(type, level, max);
442 }
443
436 444 void scheduleWakeBlock(Object block, long delay) throws Exception {
437 445 Object server = call(plugin, "getServer");
438 446 Object scheduler = call(server, "getScheduler");
@@ -497,7 +505,11 @@ public final class AdvancedEndpointsPatch {
497 505
498 506 Object world = getWorld(connection.source.key.world);
499 507 if (world == null) return;
500 String particleName = type == FluidType.LAVA ? "DRIPPING_LAVA" : "DRIPPING_WATER";
508 String particleName = switch (type) {
509 case LAVA -> "DRIPPING_LAVA";
510 case POWDER_SNOW -> "SNOWFLAKE";
511 default -> "DRIPPING_WATER";
512 };
501 513 Class<?> particleClass = Class.forName("org.bukkit.Particle", false, plugin.getClass().getClassLoader());
502 514 @SuppressWarnings({"rawtypes","unchecked"})
503 515 Object particle = Enum.valueOf((Class<? extends Enum>) particleClass.asSubclass(Enum.class), particleName);
@@ -662,11 +674,13 @@ public final class AdvancedEndpointsPatch {
662 674 }
663 675 }
664 676
665 private enum FluidType { EMPTY, WATER, LAVA, OTHER }
677 private enum FluidType { EMPTY, WATER, LAVA, POWDER_SNOW, OTHER }
666 678 private record FluidState(FluidType type, int level, int max) {
667 boolean transferable() { return (type == FluidType.WATER || type == FluidType.LAVA) && level > 0; }
679 boolean transferable() {
680 return (type == FluidType.WATER || type == FluidType.LAVA || type == FluidType.POWDER_SNOW) && level > 0;
681 }
668 682 boolean accepts(FluidType incoming) {
669 if (incoming != FluidType.WATER && incoming != FluidType.LAVA) return false;
683 if (incoming != FluidType.WATER && incoming != FluidType.LAVA && incoming != FluidType.POWDER_SNOW) return false;
670 684 if (type == FluidType.EMPTY) return true;
671 685 if (type != incoming) return false;
672 686 return level < max;
@@ -698,6 +712,10 @@ public final class AdvancedEndpointsPatch {
698 712 };
699 713 }
700 714
715 /**
716 * All vanilla cauldron block types at a position are the same liquid endpoint.
717 * Empty ↔ water/lava/powder-snow swaps must not invalidate an existing pipe.
718 */
701 719 private static boolean isCauldronMaterial(String name) {
702 720 return "CAULDRON".equals(name) || "WATER_CAULDRON".equals(name)
703 721 || "LAVA_CAULDRON".equals(name) || "POWDER_SNOW_CAULDRON".equals(name);
@@ -378,8 +378,13 @@ public final class AdvancedEndpointsPatch {
378 if (!destination.accepts(source.type)) return false;
378 if (!destination.accepts(source.type)) return false;
379
379
380 if (source.type == FluidType.WATER) {
380 if (source.type == FluidType.WATER) {
381 setWaterLevel(sourceBlock, source.level - 1);
381 setLevelledCauldron(sourceBlock, "WATER_CAULDRON", source.level - 1);
382 setWaterLevel(destinationBlock, destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
382 setLevelledCauldron(destinationBlock, "WATER_CAULDRON",
383 destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
384 } else if (source.type == FluidType.POWDER_SNOW) {
385 setLevelledCauldron(sourceBlock, "POWDER_SNOW_CAULDRON", source.level - 1);
386 setLevelledCauldron(destinationBlock, "POWDER_SNOW_CAULDRON",
387 destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
383 } else if (source.type == FluidType.LAVA) {
388 } else if (source.type == FluidType.LAVA) {
384 setEmpty(sourceBlock);
389 setEmpty(sourceBlock);
385 setLava(destinationBlock);
390 setLava(destinationBlock);
@@ -399,9 +404,10 @@ public final class AdvancedEndpointsPatch {
399 return true;
404 return true;
400 }
405 }
401
406
402 void setWaterLevel(Object block, int level) throws Exception {
407 /** Water and powder snow share Levelled cauldron data (1..max, 0 = empty CAULDRON). */
408 void setLevelledCauldron(Object block, String filledMaterial, int level) throws Exception {
403 if (level <= 0) { setEmpty(block); return; }
409 if (level <= 0) { setEmpty(block); return; }
404 if (!"WATER_CAULDRON".equals(materialName(block))) setBlockType(block, "WATER_CAULDRON");
410 if (!filledMaterial.equals(materialName(block))) setBlockType(block, filledMaterial);
405 Object data = call(block, "getBlockData");
411 Object data = call(block, "getBlockData");
406 call(data, "setLevel", new Class<?>[]{int.class}, level);
412 call(data, "setLevel", new Class<?>[]{int.class}, level);
407 call(block, "setBlockData", new Class<?>[]{Class.forName("org.bukkit.block.data.BlockData", false, plugin.getClass().getClassLoader())}, data);
413 call(block, "setBlockData", new Class<?>[]{Class.forName("org.bukkit.block.data.BlockData", false, plugin.getClass().getClassLoader())}, data);
@@ -421,18 +427,20 @@ public final class AdvancedEndpointsPatch {
421 String name = materialName(block);
427 String name = materialName(block);
422 if ("CAULDRON".equals(name)) return new FluidState(FluidType.EMPTY, 0, 0);
428 if ("CAULDRON".equals(name)) return new FluidState(FluidType.EMPTY, 0, 0);
423 if ("LAVA_CAULDRON".equals(name)) return new FluidState(FluidType.LAVA, 1, 1);
429 if ("LAVA_CAULDRON".equals(name)) return new FluidState(FluidType.LAVA, 1, 1);
424 if ("WATER_CAULDRON".equals(name)) {
430 if ("WATER_CAULDRON".equals(name)) return readLevelledFluid(block, FluidType.WATER);
425 Object data = call(block, "getBlockData");
431 if ("POWDER_SNOW_CAULDRON".equals(name)) return readLevelledFluid(block, FluidType.POWDER_SNOW);
426 int level = ((Number) call(data, "getLevel")).intValue();
432 // Unknown cauldron variant: keep the pipe (same position family) but do not transfer.
427 int max = ((Number) call(data, "getMaximumLevel")).intValue();
428 return new FluidState(FluidType.WATER, level, max);
429 }
430 // Keep a pipe attached if a cauldron temporarily contains an unsupported
431 // medium (e.g. powder snow), but never mix/transfer it as a liquid.
432 if (isCauldronMaterial(name)) return new FluidState(FluidType.OTHER, 1, 1);
433 if (isCauldronMaterial(name)) return new FluidState(FluidType.OTHER, 1, 1);
433 return new FluidState(FluidType.OTHER, 0, 0);
434 return new FluidState(FluidType.OTHER, 0, 0);
434 }
435 }
435
436
437 FluidState readLevelledFluid(Object block, FluidType type) throws Exception {
438 Object data = call(block, "getBlockData");
439 int level = ((Number) call(data, "getLevel")).intValue();
440 int max = ((Number) call(data, "getMaximumLevel")).intValue();
441 return new FluidState(type, level, max);
442 }
443
436 void scheduleWakeBlock(Object block, long delay) throws Exception {
444 void scheduleWakeBlock(Object block, long delay) throws Exception {
437 Object server = call(plugin, "getServer");
445 Object server = call(plugin, "getServer");
438 Object scheduler = call(server, "getScheduler");
446 Object scheduler = call(server, "getScheduler");
@@ -497,7 +505,11 @@ public final class AdvancedEndpointsPatch {
497
505
498 Object world = getWorld(connection.source.key.world);
506 Object world = getWorld(connection.source.key.world);
499 if (world == null) return;
507 if (world == null) return;
500 String particleName = type == FluidType.LAVA ? "DRIPPING_LAVA" : "DRIPPING_WATER";
508 String particleName = switch (type) {
509 case LAVA -> "DRIPPING_LAVA";
510 case POWDER_SNOW -> "SNOWFLAKE";
511 default -> "DRIPPING_WATER";
512 };
501 Class<?> particleClass = Class.forName("org.bukkit.Particle", false, plugin.getClass().getClassLoader());
513 Class<?> particleClass = Class.forName("org.bukkit.Particle", false, plugin.getClass().getClassLoader());
502 @SuppressWarnings({"rawtypes","unchecked"})
514 @SuppressWarnings({"rawtypes","unchecked"})
503 Object particle = Enum.valueOf((Class<? extends Enum>) particleClass.asSubclass(Enum.class), particleName);
515 Object particle = Enum.valueOf((Class<? extends Enum>) particleClass.asSubclass(Enum.class), particleName);
@@ -662,11 +674,13 @@ public final class AdvancedEndpointsPatch {
662 }
674 }
663 }
675 }
664
676
665 private enum FluidType { EMPTY, WATER, LAVA, OTHER }
677 private enum FluidType { EMPTY, WATER, LAVA, POWDER_SNOW, OTHER }
666 private record FluidState(FluidType type, int level, int max) {
678 private record FluidState(FluidType type, int level, int max) {
667 boolean transferable() { return (type == FluidType.WATER || type == FluidType.LAVA) && level > 0; }
679 boolean transferable() {
680 return (type == FluidType.WATER || type == FluidType.LAVA || type == FluidType.POWDER_SNOW) && level > 0;
681 }
668 boolean accepts(FluidType incoming) {
682 boolean accepts(FluidType incoming) {
669 if (incoming != FluidType.WATER && incoming != FluidType.LAVA) return false;
683 if (incoming != FluidType.WATER && incoming != FluidType.LAVA && incoming != FluidType.POWDER_SNOW) return false;
670 if (type == FluidType.EMPTY) return true;
684 if (type == FluidType.EMPTY) return true;
671 if (type != incoming) return false;
685 if (type != incoming) return false;
672 return level < max;
686 return level < max;
@@ -698,6 +712,10 @@ public final class AdvancedEndpointsPatch {
698 };
712 };
699 }
713 }
700
714
715 /**
716 * All vanilla cauldron block types at a position are the same liquid endpoint.
717 * Empty ↔ water/lava/powder-snow swaps must not invalidate an existing pipe.
718 */
701 private static boolean isCauldronMaterial(String name) {
719 private static boolean isCauldronMaterial(String name) {
702 return "CAULDRON".equals(name) || "WATER_CAULDRON".equals(name)
720 return "CAULDRON".equals(name) || "WATER_CAULDRON".equals(name)
703 || "LAVA_CAULDRON".equals(name) || "POWDER_SNOW_CAULDRON".equals(name);
721 || "LAVA_CAULDRON".equals(name) || "POWDER_SNOW_CAULDRON".equals(name);
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java +9 −6
@@ -57,7 +57,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
57 57 loadConnections();
58 58 startTasks();
59 59 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
60 getLogger().info("ContainerPipes 1.7.0 enabled with " + connections.size() + " connection(s).");
60 getLogger().info("ContainerPipes 1.7.1 enabled with " + connections.size() + " connection(s).");
61 61 AdvancedEndpointsPatch.enable(this);
62 62 }
63 63
@@ -245,21 +245,24 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
245 245 private boolean destinationCanEverAccept(Connection connection, ItemStack item) {
246 246 World world = Bukkit.getWorld(connection.destination.world);
247 247 if (world == null || !world.isChunkLoaded(connection.destination.x >> 4, connection.destination.z >> 4)) return true;
248 Inventory destination = inventoryOf(world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z));
248 Block block = world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z);
249 if (HopperStyleEndpoints.isComposter(block)) return item.getType().isCompostable();
250 Inventory destination = inventoryOf(block);
249 251 if (destination == null) return false;
250 252 if (destination instanceof FurnaceInventory furnace) return furnace.canSmelt(item) || furnace.isFuel(item);
253 if (destination instanceof BrewerInventory) return true; // slot legality is decided live via Paper/NMS canPlaceItem
254 if (destination instanceof ChiseledBookshelfInventory) return HopperStyleEndpoints.isBookshelfBook(item);
255 if (destination instanceof JukeboxInventory) return item.hasData(io.papermc.paper.datacomponent.DataComponentTypes.JUKEBOX_PLAYABLE);
251 256 return true;
252 257 }
253 258
254 259 private Inventory inventoryOf(Block block) {
255 BlockState state = block.getState();
256 if (state instanceof Chest chest) return chest.getInventory();
257 if (state instanceof Container container) return container.getInventory();
258 return null;
260 return HopperStyleEndpoints.inventoryOf(block);
259 261 }
260 262
261 263 private boolean isAllowedContainer(Block block) {
262 264 if (AdvancedEndpointsPatch.isExtendedContainer(block)) return true;
265 if (HopperStyleEndpoints.isAllowed(block)) return true;
263 266 String n = block.getType().name();
264 267 if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;
265 268 return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;
@@ -57,7 +57,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
57 loadConnections();
57 loadConnections();
58 startTasks();
58 startTasks();
59 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
59 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
60 getLogger().info("ContainerPipes 1.7.0 enabled with " + connections.size() + " connection(s).");
60 getLogger().info("ContainerPipes 1.7.1 enabled with " + connections.size() + " connection(s).");
61 AdvancedEndpointsPatch.enable(this);
61 AdvancedEndpointsPatch.enable(this);
62 }
62 }
63
63
@@ -245,21 +245,24 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
245 private boolean destinationCanEverAccept(Connection connection, ItemStack item) {
245 private boolean destinationCanEverAccept(Connection connection, ItemStack item) {
246 World world = Bukkit.getWorld(connection.destination.world);
246 World world = Bukkit.getWorld(connection.destination.world);
247 if (world == null || !world.isChunkLoaded(connection.destination.x >> 4, connection.destination.z >> 4)) return true;
247 if (world == null || !world.isChunkLoaded(connection.destination.x >> 4, connection.destination.z >> 4)) return true;
248 Inventory destination = inventoryOf(world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z));
248 Block block = world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z);
249 if (HopperStyleEndpoints.isComposter(block)) return item.getType().isCompostable();
250 Inventory destination = inventoryOf(block);
249 if (destination == null) return false;
251 if (destination == null) return false;
250 if (destination instanceof FurnaceInventory furnace) return furnace.canSmelt(item) || furnace.isFuel(item);
252 if (destination instanceof FurnaceInventory furnace) return furnace.canSmelt(item) || furnace.isFuel(item);
253 if (destination instanceof BrewerInventory) return true; // slot legality is decided live via Paper/NMS canPlaceItem
254 if (destination instanceof ChiseledBookshelfInventory) return HopperStyleEndpoints.isBookshelfBook(item);
255 if (destination instanceof JukeboxInventory) return item.hasData(io.papermc.paper.datacomponent.DataComponentTypes.JUKEBOX_PLAYABLE);
251 return true;
256 return true;
252 }
257 }
253
258
254 private Inventory inventoryOf(Block block) {
259 private Inventory inventoryOf(Block block) {
255 BlockState state = block.getState();
260 return HopperStyleEndpoints.inventoryOf(block);
256 if (state instanceof Chest chest) return chest.getInventory();
257 if (state instanceof Container container) return container.getInventory();
258 return null;
259 }
261 }
260
262
261 private boolean isAllowedContainer(Block block) {
263 private boolean isAllowedContainer(Block block) {
262 if (AdvancedEndpointsPatch.isExtendedContainer(block)) return true;
264 if (AdvancedEndpointsPatch.isExtendedContainer(block)) return true;
265 if (HopperStyleEndpoints.isAllowed(block)) return true;
263 String n = block.getType().name();
266 String n = block.getType().name();
264 if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;
267 if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;
265 return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;
268 return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;
src/main/java/nl/timfalken/containerpipes/HopperStyleEndpoints.java added +315 −0
@@ -0,0 +1,315 @@
1 package nl.timfalken.containerpipes;
2
3 import org.bukkit.*;
4 import org.bukkit.block.Block;
5 import org.bukkit.block.BlockState;
6 import org.bukkit.block.Container;
7 import org.bukkit.block.Jukebox;
8 import org.bukkit.block.TileState;
9 import org.bukkit.block.data.BlockData;
10 import org.bukkit.block.data.Levelled;
11 import org.bukkit.inventory.*;
12 import org.bukkit.inventory.meta.BlockStateMeta;
13 import io.papermc.paper.datacomponent.DataComponentTypes;
14
15 import java.lang.reflect.Method;
16 import java.util.concurrent.ThreadLocalRandom;
17
18 /**
19 * Face-independent hopper-style rules for specialty containers.
20 *
21 * Item legality comes from Paper APIs and datapack tags (never hardcoded item lists),
22 * matching how furnace insertion already uses {@link FurnaceInventory#canSmelt}/{@link FurnaceInventory#isFuel}.
23 */
24 public final class HopperStyleEndpoints {
25 private HopperStyleEndpoints() {}
26
27 public static boolean isAllowed(Block block) {
28 if (block == null) return false;
29 Material type = block.getType();
30 if (type == Material.BREWING_STAND
31 || type == Material.COMPOSTER
32 || type == Material.CHISELED_BOOKSHELF
33 || type == Material.DECORATED_POT
34 || type == Material.JUKEBOX
35 || type.name().equals("SHELF")
36 || Tag.SHULKER_BOXES.isTagged(type)) {
37 return true;
38 }
39 return false;
40 }
41
42 public static boolean isComposter(Block block) {
43 return block != null && block.getType() == Material.COMPOSTER;
44 }
45
46 public static Inventory inventoryOf(Block block) {
47 if (block == null) return null;
48 if (isComposter(block)) return null;
49 BlockState state = block.getState();
50 if (state instanceof org.bukkit.block.Chest chest) return chest.getInventory();
51 if (state instanceof Container container) return container.getInventory();
52 if (state instanceof Jukebox jukebox) return jukebox.getInventory();
53 // Chiseled bookshelf / decorated pot / shelf implement TileStateInventoryHolder in Paper.
54 try {
55 Method getInventory = state.getClass().getMethod("getInventory");
56 Object inventory = getInventory.invoke(state);
57 if (inventory instanceof Inventory inv) return inv;
58 } catch (ReflectiveOperationException ignored) {}
59 return null;
60 }
61
62 public static Boolean tryInsertOne(Inventory inventory, ItemStack source) {
63 if (inventory == null || source == null || source.getType().isAir()) return false;
64 ItemStack one = source.clone();
65 one.setAmount(1);
66
67 if (inventory instanceof BrewerInventory brewer) return insertBrewing(brewer, one);
68 if (inventory instanceof DecoratedPotInventory pot) return insertDecoratedPot(pot, one);
69 if (inventory instanceof JukeboxInventory jukebox) return insertJukebox(jukebox, one);
70 if (isShulkerInventory(inventory)) {
71 if (isShulkerBoxItem(one)) return false;
72 return null; // normal merge/empty rules
73 }
74 return null;
75 }
76
77 /** Datapack tag gate for chiseled bookshelf; storage insert uses the normal container cache. */
78 public static boolean isBookshelfBook(ItemStack item) {
79 return item != null && Tag.ITEMS_BOOKSHELF_BOOKS.isTagged(item.getType());
80 }
81
82 public static boolean handlesExtract(Inventory inventory) {
83 return inventory instanceof BrewerInventory
84 || inventory instanceof JukeboxInventory;
85 }
86
87 /**
88 * Outgoing pipe from a specialty source. Returns the stack to move (amount 1 view)
89 * and the slot/index used for decrement, or null if nothing to extract.
90 */
91 public static Extract pickExtract(Inventory inventory) {
92 if (inventory instanceof BrewerInventory brewer) {
93 // Hopper-under behaviour: brew slots only (0..2), never ingredient/fuel.
94 for (int slot = 0; slot < 3; slot++) {
95 ItemStack stack = brewer.getItem(slot);
96 if (stack != null && !stack.getType().isAir() && stack.getAmount() > 0) {
97 return new Extract(stack, slot, ExtractKind.BREWER_BOTTLE);
98 }
99 }
100 return null;
101 }
102 if (inventory instanceof JukeboxInventory jukebox) {
103 ItemStack record = jukebox.getRecord();
104 if (record == null || record.getType().isAir()) return null;
105 Jukebox holder = jukebox.getHolder();
106 // Match hopper behaviour: only pull the disc once playback finished.
107 if (holder != null && holder.isPlaying()) return null;
108 return new Extract(record, 0, ExtractKind.JUKEBOX);
109 }
110 return null;
111 }
112
113 public static void decrementExtract(Inventory inventory, Extract extract) {
114 if (extract.kind() == ExtractKind.JUKEBOX && inventory instanceof JukeboxInventory jukebox) {
115 jukebox.setRecord(null);
116 return;
117 }
118 ItemStack stack = inventory.getItem(extract.slot());
119 if (stack == null) return;
120 if (stack.getAmount() <= 1) inventory.setItem(extract.slot(), null);
121 else {
122 ItemStack reduced = stack.clone();
123 reduced.setAmount(stack.getAmount() - 1);
124 inventory.setItem(extract.slot(), reduced);
125 }
126 }
127
128 public static boolean insertComposter(Block block, ItemStack source) {
129 if (!isComposter(block) || source == null || source.getType().isAir()) return false;
130 if (!source.getType().isCompostable()) return false;
131 BlockData data = block.getBlockData();
132 if (!(data instanceof Levelled levelled)) return false;
133 int level = levelled.getLevel();
134 int max = levelled.getMaximumLevel();
135 // Stage 8 is ready bone meal; hopper-like inserts stop until emptied.
136 if (level >= max) return false;
137
138 // Paper exposes compost success chance; datapacks that change compostables are reflected here.
139 float chance = source.getType().getCompostChance();
140 if (ThreadLocalRandom.current().nextFloat() < chance) {
141 levelled.setLevel(Math.min(max, level + 1));
142 block.setBlockData(levelled);
143 }
144 return true; // item always consumed when compostable and not full
145 }
146
147 public static boolean extractComposterBoneMeal(Block block) {
148 if (!isComposter(block)) return false;
149 BlockData data = block.getBlockData();
150 if (!(data instanceof Levelled levelled)) return false;
151 if (levelled.getLevel() < levelled.getMaximumLevel()) return false;
152 levelled.setLevel(0);
153 block.setBlockData(levelled);
154 return true;
155 }
156
157 public static int readComposterLevel(Block block) {
158 if (!isComposter(block)) return -1;
159 BlockData data = block.getBlockData();
160 if (!(data instanceof Levelled levelled)) return -1;
161 return levelled.getLevel();
162 }
163
164 public static int maxComposterLevel(Block block) {
165 if (!isComposter(block)) return -1;
166 BlockData data = block.getBlockData();
167 if (!(data instanceof Levelled levelled)) return -1;
168 return levelled.getMaximumLevel();
169 }
170
171 private static boolean insertBrewing(BrewerInventory brewer, ItemStack one) {
172 // Face-independent preference: ingredient → fuel → brew bottles.
173 ItemStack ingredient = brewer.getIngredient();
174 if (canPlaceInSlot(brewer, ingredientSlot(brewer), one) && canMerge(ingredient, one, brewer.getMaxStackSize())) {
175 ItemStack actual = brewer.getIngredient();
176 if (!same(ingredient, actual)) return false;
177 brewer.setIngredient(merge(actual, one));
178 return true;
179 }
180
181 ItemStack fuel = brewer.getFuel();
182 if (isBrewingFuel(one) && canMerge(fuel, one, brewer.getMaxStackSize())) {
183 // Prefer tag when present; still require hopper-equivalent slot acceptance.
184 if (!canPlaceInSlot(brewer, fuelSlot(brewer), one)) return false;
185 ItemStack actual = brewer.getFuel();
186 if (!same(fuel, actual)) return false;
187 brewer.setFuel(merge(actual, one));
188 return true;
189 }
190
191 for (int slot = 0; slot < 3; slot++) {
192 ItemStack bottle = brewer.getItem(slot);
193 if (!canPlaceInSlot(brewer, slot, one)) continue;
194 if (!canMerge(bottle, one, brewer.getMaxStackSize())) continue;
195 ItemStack actual = brewer.getItem(slot);
196 if (!same(bottle, actual)) return false;
197 brewer.setItem(slot, merge(actual, one));
198 return true;
199 }
200 return false;
201 }
202
203 private static boolean insertDecoratedPot(DecoratedPotInventory pot, ItemStack one) {
204 ItemStack existing = pot.getItem();
205 if (existing == null || existing.getType().isAir()) {
206 pot.setItem(one.clone());
207 return true;
208 }
209 if (!existing.isSimilar(one)) return false;
210 int max = Math.min(existing.getMaxStackSize(), pot.getMaxStackSize());
211 if (existing.getAmount() >= max) return false;
212 ItemStack merged = existing.clone();
213 merged.setAmount(existing.getAmount() + 1);
214 pot.setItem(merged);
215 return true;
216 }
217
218 private static boolean insertJukebox(JukeboxInventory jukebox, ItemStack one) {
219 if (jukebox.getRecord() != null && !jukebox.getRecord().getType().isAir()) return false;
220 if (!one.hasData(DataComponentTypes.JUKEBOX_PLAYABLE)) return false;
221 jukebox.setRecord(one.clone());
222 return true;
223 }
224
225 private static boolean isBrewingFuel(ItemStack item) {
226 Tag<Material> fuel = Tag.ITEMS_BREWING_FUEL;
227 return fuel != null && fuel.isTagged(item.getType());
228 }
229
230 private static boolean isShulkerInventory(Inventory inventory) {
231 InventoryHolder holder = inventory.getHolder();
232 if (!(holder instanceof BlockState state)) return false;
233 return Tag.SHULKER_BOXES.isTagged(state.getType());
234 }
235
236 private static boolean isShulkerBoxItem(ItemStack item) {
237 if (Tag.SHULKER_BOXES.isTagged(item.getType())) return true;
238 // Block-state items (e.g. shulker in creative middle-click form) still count.
239 if (item.getItemMeta() instanceof BlockStateMeta meta && meta.getBlockState() instanceof TileState) {
240 return Tag.SHULKER_BOXES.isTagged(meta.getBlockState().getType());
241 }
242 return false;
243 }
244
245 /**
246 * Uses the same NMS container rule hoppers use when Paper exposes it via CraftInventory.
247 * Falls back to permissive only when reflection is unavailable (should not happen on Paper).
248 */
249 private static boolean canPlaceInSlot(Inventory inventory, int slot, ItemStack stack) {
250 if (slot < 0) return false;
251 try {
252 Method getInventory = inventory.getClass().getMethod("getInventory");
253 Object container = getInventory.invoke(inventory);
254 Object nmsStack = asNmsCopy(stack);
255 for (Method method : container.getClass().getMethods()) {
256 if (!"canPlaceItem".equals(method.getName()) || method.getParameterCount() != 2) continue;
257 Object result = method.invoke(container, slot, nmsStack);
258 if (result instanceof Boolean allowed) return allowed;
259 }
260 } catch (Throwable ignored) {}
261 // Fallback: empty or similar stack only (never invent item-type allowlists).
262 ItemStack existing = inventory.getItem(slot);
263 return existing == null || existing.getType().isAir() || existing.isSimilar(stack);
264 }
265
266 private static Object asNmsCopy(ItemStack stack) throws Exception {
267 ClassNotFoundException last = null;
268 for (String name : new String[]{
269 "org.bukkit.craftbukkit.inventory.CraftItemStack",
270 "org.bukkit.craftbukkit.v1_21_R6.inventory.CraftItemStack",
271 "org.bukkit.craftbukkit.v1_21_R5.inventory.CraftItemStack"
272 }) {
273 try {
274 Class<?> craft = Class.forName(name);
275 Method method = craft.getMethod("asNMSCopy", ItemStack.class);
276 return method.invoke(null, stack);
277 } catch (ClassNotFoundException ex) {
278 last = ex;
279 }
280 }
281 if (last != null) throw last;
282 throw new ClassNotFoundException("CraftItemStack");
283 }
284
285 private static int ingredientSlot(BrewerInventory brewer) {
286 // BrewerInventory storage order on Paper: bottles 0-2, ingredient 3, fuel 4.
287 return Math.min(3, Math.max(0, brewer.getSize() - 2));
288 }
289
290 private static int fuelSlot(BrewerInventory brewer) {
291 return Math.min(4, Math.max(0, brewer.getSize() - 1));
292 }
293
294 private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {
295 return existing == null || existing.getType().isAir()
296 || (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));
297 }
298
299 private static ItemStack merge(ItemStack existing, ItemStack add) {
300 if (existing == null || existing.getType().isAir()) return add.clone();
301 ItemStack result = existing.clone();
302 result.setAmount(existing.getAmount() + add.getAmount());
303 return result;
304 }
305
306 private static boolean same(ItemStack expected, ItemStack actual) {
307 boolean expectedEmpty = expected == null || expected.getType().isAir();
308 boolean actualEmpty = actual == null || actual.getType().isAir();
309 if (expectedEmpty || actualEmpty) return expectedEmpty == actualEmpty;
310 return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
311 }
312
313 public enum ExtractKind { BREWER_BOTTLE, JUKEBOX }
314 public record Extract(ItemStack stack, int slot, ExtractKind kind) {}
315 }
@@ -0,0 +1,315 @@
1package nl.timfalken.containerpipes;
2
3import org.bukkit.*;
4import org.bukkit.block.Block;
5import org.bukkit.block.BlockState;
6import org.bukkit.block.Container;
7import org.bukkit.block.Jukebox;
8import org.bukkit.block.TileState;
9import org.bukkit.block.data.BlockData;
10import org.bukkit.block.data.Levelled;
11import org.bukkit.inventory.*;
12import org.bukkit.inventory.meta.BlockStateMeta;
13import io.papermc.paper.datacomponent.DataComponentTypes;
14
15import java.lang.reflect.Method;
16import java.util.concurrent.ThreadLocalRandom;
17
18/**
19 * Face-independent hopper-style rules for specialty containers.
20 *
21 * Item legality comes from Paper APIs and datapack tags (never hardcoded item lists),
22 * matching how furnace insertion already uses {@link FurnaceInventory#canSmelt}/{@link FurnaceInventory#isFuel}.
23 */
24public final class HopperStyleEndpoints {
25 private HopperStyleEndpoints() {}
26
27 public static boolean isAllowed(Block block) {
28 if (block == null) return false;
29 Material type = block.getType();
30 if (type == Material.BREWING_STAND
31 || type == Material.COMPOSTER
32 || type == Material.CHISELED_BOOKSHELF
33 || type == Material.DECORATED_POT
34 || type == Material.JUKEBOX
35 || type.name().equals("SHELF")
36 || Tag.SHULKER_BOXES.isTagged(type)) {
37 return true;
38 }
39 return false;
40 }
41
42 public static boolean isComposter(Block block) {
43 return block != null && block.getType() == Material.COMPOSTER;
44 }
45
46 public static Inventory inventoryOf(Block block) {
47 if (block == null) return null;
48 if (isComposter(block)) return null;
49 BlockState state = block.getState();
50 if (state instanceof org.bukkit.block.Chest chest) return chest.getInventory();
51 if (state instanceof Container container) return container.getInventory();
52 if (state instanceof Jukebox jukebox) return jukebox.getInventory();
53 // Chiseled bookshelf / decorated pot / shelf implement TileStateInventoryHolder in Paper.
54 try {
55 Method getInventory = state.getClass().getMethod("getInventory");
56 Object inventory = getInventory.invoke(state);
57 if (inventory instanceof Inventory inv) return inv;
58 } catch (ReflectiveOperationException ignored) {}
59 return null;
60 }
61
62 public static Boolean tryInsertOne(Inventory inventory, ItemStack source) {
63 if (inventory == null || source == null || source.getType().isAir()) return false;
64 ItemStack one = source.clone();
65 one.setAmount(1);
66
67 if (inventory instanceof BrewerInventory brewer) return insertBrewing(brewer, one);
68 if (inventory instanceof DecoratedPotInventory pot) return insertDecoratedPot(pot, one);
69 if (inventory instanceof JukeboxInventory jukebox) return insertJukebox(jukebox, one);
70 if (isShulkerInventory(inventory)) {
71 if (isShulkerBoxItem(one)) return false;
72 return null; // normal merge/empty rules
73 }
74 return null;
75 }
76
77 /** Datapack tag gate for chiseled bookshelf; storage insert uses the normal container cache. */
78 public static boolean isBookshelfBook(ItemStack item) {
79 return item != null && Tag.ITEMS_BOOKSHELF_BOOKS.isTagged(item.getType());
80 }
81
82 public static boolean handlesExtract(Inventory inventory) {
83 return inventory instanceof BrewerInventory
84 || inventory instanceof JukeboxInventory;
85 }
86
87 /**
88 * Outgoing pipe from a specialty source. Returns the stack to move (amount 1 view)
89 * and the slot/index used for decrement, or null if nothing to extract.
90 */
91 public static Extract pickExtract(Inventory inventory) {
92 if (inventory instanceof BrewerInventory brewer) {
93 // Hopper-under behaviour: brew slots only (0..2), never ingredient/fuel.
94 for (int slot = 0; slot < 3; slot++) {
95 ItemStack stack = brewer.getItem(slot);
96 if (stack != null && !stack.getType().isAir() && stack.getAmount() > 0) {
97 return new Extract(stack, slot, ExtractKind.BREWER_BOTTLE);
98 }
99 }
100 return null;
101 }
102 if (inventory instanceof JukeboxInventory jukebox) {
103 ItemStack record = jukebox.getRecord();
104 if (record == null || record.getType().isAir()) return null;
105 Jukebox holder = jukebox.getHolder();
106 // Match hopper behaviour: only pull the disc once playback finished.
107 if (holder != null && holder.isPlaying()) return null;
108 return new Extract(record, 0, ExtractKind.JUKEBOX);
109 }
110 return null;
111 }
112
113 public static void decrementExtract(Inventory inventory, Extract extract) {
114 if (extract.kind() == ExtractKind.JUKEBOX && inventory instanceof JukeboxInventory jukebox) {
115 jukebox.setRecord(null);
116 return;
117 }
118 ItemStack stack = inventory.getItem(extract.slot());
119 if (stack == null) return;
120 if (stack.getAmount() <= 1) inventory.setItem(extract.slot(), null);
121 else {
122 ItemStack reduced = stack.clone();
123 reduced.setAmount(stack.getAmount() - 1);
124 inventory.setItem(extract.slot(), reduced);
125 }
126 }
127
128 public static boolean insertComposter(Block block, ItemStack source) {
129 if (!isComposter(block) || source == null || source.getType().isAir()) return false;
130 if (!source.getType().isCompostable()) return false;
131 BlockData data = block.getBlockData();
132 if (!(data instanceof Levelled levelled)) return false;
133 int level = levelled.getLevel();
134 int max = levelled.getMaximumLevel();
135 // Stage 8 is ready bone meal; hopper-like inserts stop until emptied.
136 if (level >= max) return false;
137
138 // Paper exposes compost success chance; datapacks that change compostables are reflected here.
139 float chance = source.getType().getCompostChance();
140 if (ThreadLocalRandom.current().nextFloat() < chance) {
141 levelled.setLevel(Math.min(max, level + 1));
142 block.setBlockData(levelled);
143 }
144 return true; // item always consumed when compostable and not full
145 }
146
147 public static boolean extractComposterBoneMeal(Block block) {
148 if (!isComposter(block)) return false;
149 BlockData data = block.getBlockData();
150 if (!(data instanceof Levelled levelled)) return false;
151 if (levelled.getLevel() < levelled.getMaximumLevel()) return false;
152 levelled.setLevel(0);
153 block.setBlockData(levelled);
154 return true;
155 }
156
157 public static int readComposterLevel(Block block) {
158 if (!isComposter(block)) return -1;
159 BlockData data = block.getBlockData();
160 if (!(data instanceof Levelled levelled)) return -1;
161 return levelled.getLevel();
162 }
163
164 public static int maxComposterLevel(Block block) {
165 if (!isComposter(block)) return -1;
166 BlockData data = block.getBlockData();
167 if (!(data instanceof Levelled levelled)) return -1;
168 return levelled.getMaximumLevel();
169 }
170
171 private static boolean insertBrewing(BrewerInventory brewer, ItemStack one) {
172 // Face-independent preference: ingredient → fuel → brew bottles.
173 ItemStack ingredient = brewer.getIngredient();
174 if (canPlaceInSlot(brewer, ingredientSlot(brewer), one) && canMerge(ingredient, one, brewer.getMaxStackSize())) {
175 ItemStack actual = brewer.getIngredient();
176 if (!same(ingredient, actual)) return false;
177 brewer.setIngredient(merge(actual, one));
178 return true;
179 }
180
181 ItemStack fuel = brewer.getFuel();
182 if (isBrewingFuel(one) && canMerge(fuel, one, brewer.getMaxStackSize())) {
183 // Prefer tag when present; still require hopper-equivalent slot acceptance.
184 if (!canPlaceInSlot(brewer, fuelSlot(brewer), one)) return false;
185 ItemStack actual = brewer.getFuel();
186 if (!same(fuel, actual)) return false;
187 brewer.setFuel(merge(actual, one));
188 return true;
189 }
190
191 for (int slot = 0; slot < 3; slot++) {
192 ItemStack bottle = brewer.getItem(slot);
193 if (!canPlaceInSlot(brewer, slot, one)) continue;
194 if (!canMerge(bottle, one, brewer.getMaxStackSize())) continue;
195 ItemStack actual = brewer.getItem(slot);
196 if (!same(bottle, actual)) return false;
197 brewer.setItem(slot, merge(actual, one));
198 return true;
199 }
200 return false;
201 }
202
203 private static boolean insertDecoratedPot(DecoratedPotInventory pot, ItemStack one) {
204 ItemStack existing = pot.getItem();
205 if (existing == null || existing.getType().isAir()) {
206 pot.setItem(one.clone());
207 return true;
208 }
209 if (!existing.isSimilar(one)) return false;
210 int max = Math.min(existing.getMaxStackSize(), pot.getMaxStackSize());
211 if (existing.getAmount() >= max) return false;
212 ItemStack merged = existing.clone();
213 merged.setAmount(existing.getAmount() + 1);
214 pot.setItem(merged);
215 return true;
216 }
217
218 private static boolean insertJukebox(JukeboxInventory jukebox, ItemStack one) {
219 if (jukebox.getRecord() != null && !jukebox.getRecord().getType().isAir()) return false;
220 if (!one.hasData(DataComponentTypes.JUKEBOX_PLAYABLE)) return false;
221 jukebox.setRecord(one.clone());
222 return true;
223 }
224
225 private static boolean isBrewingFuel(ItemStack item) {
226 Tag<Material> fuel = Tag.ITEMS_BREWING_FUEL;
227 return fuel != null && fuel.isTagged(item.getType());
228 }
229
230 private static boolean isShulkerInventory(Inventory inventory) {
231 InventoryHolder holder = inventory.getHolder();
232 if (!(holder instanceof BlockState state)) return false;
233 return Tag.SHULKER_BOXES.isTagged(state.getType());
234 }
235
236 private static boolean isShulkerBoxItem(ItemStack item) {
237 if (Tag.SHULKER_BOXES.isTagged(item.getType())) return true;
238 // Block-state items (e.g. shulker in creative middle-click form) still count.
239 if (item.getItemMeta() instanceof BlockStateMeta meta && meta.getBlockState() instanceof TileState) {
240 return Tag.SHULKER_BOXES.isTagged(meta.getBlockState().getType());
241 }
242 return false;
243 }
244
245 /**
246 * Uses the same NMS container rule hoppers use when Paper exposes it via CraftInventory.
247 * Falls back to permissive only when reflection is unavailable (should not happen on Paper).
248 */
249 private static boolean canPlaceInSlot(Inventory inventory, int slot, ItemStack stack) {
250 if (slot < 0) return false;
251 try {
252 Method getInventory = inventory.getClass().getMethod("getInventory");
253 Object container = getInventory.invoke(inventory);
254 Object nmsStack = asNmsCopy(stack);
255 for (Method method : container.getClass().getMethods()) {
256 if (!"canPlaceItem".equals(method.getName()) || method.getParameterCount() != 2) continue;
257 Object result = method.invoke(container, slot, nmsStack);
258 if (result instanceof Boolean allowed) return allowed;
259 }
260 } catch (Throwable ignored) {}
261 // Fallback: empty or similar stack only (never invent item-type allowlists).
262 ItemStack existing = inventory.getItem(slot);
263 return existing == null || existing.getType().isAir() || existing.isSimilar(stack);
264 }
265
266 private static Object asNmsCopy(ItemStack stack) throws Exception {
267 ClassNotFoundException last = null;
268 for (String name : new String[]{
269 "org.bukkit.craftbukkit.inventory.CraftItemStack",
270 "org.bukkit.craftbukkit.v1_21_R6.inventory.CraftItemStack",
271 "org.bukkit.craftbukkit.v1_21_R5.inventory.CraftItemStack"
272 }) {
273 try {
274 Class<?> craft = Class.forName(name);
275 Method method = craft.getMethod("asNMSCopy", ItemStack.class);
276 return method.invoke(null, stack);
277 } catch (ClassNotFoundException ex) {
278 last = ex;
279 }
280 }
281 if (last != null) throw last;
282 throw new ClassNotFoundException("CraftItemStack");
283 }
284
285 private static int ingredientSlot(BrewerInventory brewer) {
286 // BrewerInventory storage order on Paper: bottles 0-2, ingredient 3, fuel 4.
287 return Math.min(3, Math.max(0, brewer.getSize() - 2));
288 }
289
290 private static int fuelSlot(BrewerInventory brewer) {
291 return Math.min(4, Math.max(0, brewer.getSize() - 1));
292 }
293
294 private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {
295 return existing == null || existing.getType().isAir()
296 || (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));
297 }
298
299 private static ItemStack merge(ItemStack existing, ItemStack add) {
300 if (existing == null || existing.getType().isAir()) return add.clone();
301 ItemStack result = existing.clone();
302 result.setAmount(existing.getAmount() + add.getAmount());
303 return result;
304 }
305
306 private static boolean same(ItemStack expected, ItemStack actual) {
307 boolean expectedEmpty = expected == null || expected.getType().isAir();
308 boolean actualEmpty = actual == null || actual.getType().isAir();
309 if (expectedEmpty || actualEmpty) return expectedEmpty == actualEmpty;
310 return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
311 }
312
313 public enum ExtractKind { BREWER_BOTTLE, JUKEBOX }
314 public record Extract(ItemStack stack, int slot, ExtractKind kind) {}
315}
src/main/java/nl/timfalken/containerpipes/OptimizedTransferPlanner.java +184 −36
@@ -10,10 +10,14 @@ import org.bukkit.block.Chest;
10 10 import org.bukkit.block.Container;
11 11 import org.bukkit.block.DoubleChest;
12 12 import org.bukkit.configuration.file.FileConfiguration;
13 import org.bukkit.inventory.BrewerInventory;
14 import org.bukkit.inventory.ChiseledBookshelfInventory;
15 import org.bukkit.inventory.DecoratedPotInventory;
13 16 import org.bukkit.inventory.FurnaceInventory;
14 17 import org.bukkit.inventory.Inventory;
15 18 import org.bukkit.inventory.InventoryHolder;
16 19 import org.bukkit.inventory.ItemStack;
20 import org.bukkit.inventory.JukeboxInventory;
17 21
18 22 import java.lang.reflect.*;
19 23 import java.util.*;
@@ -303,6 +307,13 @@ public final class OptimizedTransferPlanner {
303 307 "org.bukkit.event.inventory.FurnaceExtractEvent",
304 308 "org.bukkit.event.inventory.FurnaceBurnEvent",
305 309 "org.bukkit.event.block.BlockCookEvent",
310 "org.bukkit.event.inventory.BrewEvent",
311 "org.bukkit.event.inventory.BrewingStandFuelEvent",
312 "io.papermc.paper.event.block.CompostItemEvent",
313 "io.papermc.paper.event.entity.EntityCompostItemEvent",
314 // Bookshelf / pot / jukebox / composter bone-meal often change via
315 // right-click without opening an inventory GUI.
316 "org.bukkit.event.player.PlayerInteractEvent",
306 317 "org.bukkit.event.world.ChunkLoadEvent",
307 318 "org.bukkit.event.world.ChunkUnloadEvent"
308 319 };
@@ -346,12 +357,17 @@ public final class OptimizedTransferPlanner {
346 357 Inventory inventory = (Inventory) call(event, "getInventory");
347 358 schedule(() -> wakeInventory(inventory), 1L);
348 359 } else if (name.endsWith("FurnaceSmeltEvent") || name.endsWith("FurnaceExtractEvent")
349 || name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")) {
360 || name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")
361 || name.endsWith("BrewEvent") || name.endsWith("BrewingStandFuelEvent")
362 || name.endsWith("CompostItemEvent") || name.endsWith("EntityCompostItemEvent")) {
350 363 Block block = (Block) call(event, "getBlock");
351 schedule(() -> {
352 Inventory inventory = inventoryOf(block);
353 if (inventory != null) wakeInventory(inventory);
354 }, 1L);
364 schedule(() -> wakeBlock(block), 1L);
365 } else if (name.endsWith("PlayerInteractEvent")) {
366 Object action = call(event, "getAction");
367 String actionName = String.valueOf(action);
368 if (!actionName.contains("RIGHT_CLICK_BLOCK") && !actionName.contains("LEFT_CLICK_BLOCK")) return;
369 Object clicked = call(event, "getClickedBlock");
370 if (clicked instanceof Block block) schedule(() -> wakeBlock(block), 1L);
355 371 } else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {
356 372 // Double-chest canonical identities can change as either half loads.
357 373 lastConnectionCount = -1;
@@ -363,6 +379,17 @@ public final class OptimizedTransferPlanner {
363 379 }
364 380 }
365 381
382 void wakeBlock(Block block) {
383 if (block == null) return;
384 if (HopperStyleEndpoints.isComposter(block) || HopperStyleEndpoints.isAllowed(block)
385 || block.getState() instanceof Container) {
386 wakeKeyInternal(new ContainerKey(block.getWorld().getUID(),
387 pack(block.getX(), block.getY(), block.getZ())));
388 }
389 Inventory inventory = inventoryOf(block);
390 if (inventory != null) wakeInventory(inventory);
391 }
392
366 393 void schedule(Runnable runnable, long delay) throws Exception {
367 394 Object scheduler = call(call(plugin, "getServer"), "getScheduler");
368 395 Class<?> pluginInterface = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
@@ -401,8 +428,15 @@ public final class OptimizedTransferPlanner {
401 428 }
402 429
403 430 void prepareCycleBudget() {
431 Block sourceBlock = blockAt(key);
432 if (HopperStyleEndpoints.isComposter(sourceBlock)) {
433 cycleBudget = null;
434 sourceCache = null;
435 return;
436 }
404 437 Inventory source = inventoryAt(connections.get(0).source);
405 if (source == null || source instanceof FurnaceInventory) {
438 if (source == null || source instanceof FurnaceInventory || source instanceof BrewerInventory
439 || source instanceof JukeboxInventory) {
406 440 cycleBudget = null;
407 441 return;
408 442 }
@@ -443,7 +477,8 @@ public final class OptimizedTransferPlanner {
443 477 }
444 478
445 479 boolean refreshRealInventoryIfChanged(Inventory source) {
446 if (source instanceof FurnaceInventory) return false;
480 if (source instanceof FurnaceInventory || source instanceof BrewerInventory
481 || source instanceof JukeboxInventory) return false;
447 482 ItemStack[] actual = source.getStorageContents();
448 483 if (sourceCache == null || actual.length != sourceCache.length) {
449 484 sourceCache = cloneContents(actual);
@@ -479,6 +514,11 @@ public final class OptimizedTransferPlanner {
479 514 }
480 515
481 516 RunResult run() {
517 Block sourceBlock = blockAt(key);
518 if (HopperStyleEndpoints.isComposter(sourceBlock)) {
519 return runComposterSource(sourceBlock);
520 }
521
482 522 Inventory source = inventoryAt(connections.get(0).source);
483 523 if (source == null) return RunResult.NO_MOVE;
484 524
@@ -502,6 +542,28 @@ public final class OptimizedTransferPlanner {
502 542 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
503 543 }
504 544
545 // Brewing stands / jukeboxes: extract only hopper-legal slots, live (no cache).
546 if (HopperStyleEndpoints.handlesExtract(source)) {
547 boolean moved = false;
548 Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());
549 for (ConnectionView connection : filtered) {
550 if (used.contains(connection.raw)) continue;
551 HopperStyleEndpoints.Extract extract = HopperStyleEndpoints.pickExtract(source);
552 if (extract == null || !allowed(connection, extract.stack(), true, reserved)) continue;
553 TransferResult result = transferSpecialtyExtract(connection, source, extract, key);
554 if (result.moved) { used.add(connection.raw); moved = true; }
555 }
556 for (ConnectionView connection : unfiltered) {
557 if (used.contains(connection.raw)) continue;
558 HopperStyleEndpoints.Extract extract = HopperStyleEndpoints.pickExtract(source);
559 if (extract == null || !allowed(connection, extract.stack(), false, reserved)) continue;
560 TransferResult result = transferSpecialtyExtract(connection, source, extract, key);
561 if (result.moved) { used.add(connection.raw); moved = true; }
562 }
563 cacheDirty = true;
564 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
565 }
566
505 567 if (cycleBudget == null || cacheDirty || sourceCache == null) {
506 568 prepareCycleBudget();
507 569 }
@@ -558,6 +620,36 @@ public final class OptimizedTransferPlanner {
558 620 }
559 621 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
560 622 }
623
624 RunResult runComposterSource(Block sourceBlock) {
625 // Simple level cache: only stage 8 yields bone meal.
626 if (HopperStyleEndpoints.readComposterLevel(sourceBlock)
627 < HopperStyleEndpoints.maxComposterLevel(sourceBlock)) {
628 return RunResult.NO_MOVE;
629 }
630 ItemStack boneMeal = new ItemStack(Material.BONE_MEAL, 1);
631 boolean moved = false;
632 Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());
633 for (ConnectionView connection : filtered) {
634 if (used.contains(connection.raw) || !allowed(connection, boneMeal, true, reserved)) continue;
635 if (!transferIntoDestination(connection, boneMeal, key).moved) continue;
636 if (!HopperStyleEndpoints.extractComposterBoneMeal(sourceBlock)) break;
637 used.add(connection.raw);
638 moved = true;
639 break; // one bone meal per cycle
640 }
641 if (!moved) {
642 for (ConnectionView connection : unfiltered) {
643 if (used.contains(connection.raw) || !allowed(connection, boneMeal, false, reserved)) continue;
644 if (!transferIntoDestination(connection, boneMeal, key).moved) continue;
645 if (!HopperStyleEndpoints.extractComposterBoneMeal(sourceBlock)) break;
646 used.add(connection.raw);
647 moved = true;
648 break;
649 }
650 }
651 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
652 }
561 653 }
562 654
563 655 ItemStack[] cloneContents(ItemStack[] input) {
@@ -579,45 +671,59 @@ public final class OptimizedTransferPlanner {
579 671
580 672 TransferResult transferFurnaceOutput(ConnectionView connection, FurnaceInventory source, ContainerKey sourceKey) {
581 673 ItemStack output = source.getResult();
582 Inventory destination = inventoryAt(connection.destination);
583 if (destination == null || output == null || output.getType().isAir()) return TransferResult.NO_MOVE;
584
585 // Furnace output used to bypass cycleDestinations and write directly to
586 // the Bukkit inventory. That left a destination source-group with a
587 // stale slot cache, so freshly produced items could remain invisible to
588 // its outgoing pipes until an unrelated event or topology refresh.
589 // Route every internal insertion through the same DestinationState so
590 // multiple incoming normal/furnace pipes share one authoritative
591 // cycle-local view and downstream caches are updated transactionally.
592 ContainerKey destinationKey = inventoryKey(destination);
593 if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
594 DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,
595 ignored -> new DestinationState(destination));
596 if (!state.insertOne(output)) return TransferResult.NO_MOVE;
597
674 if (output == null || output.getType().isAir()) return TransferResult.NO_MOVE;
675 TransferResult result = transferIntoDestination(connection, output, sourceKey);
676 if (!result.moved()) return TransferResult.NO_MOVE;
598 677 decrementFurnace(source);
599 syncIncomingCache(destinationKey, state);
600 afterTransfer(connection, source, destination);
601 return new TransferResult(true, destinationKey);
678 return result;
679 }
680
681 TransferResult transferSpecialtyExtract(ConnectionView connection, Inventory source,
682 HopperStyleEndpoints.Extract extract, ContainerKey sourceKey) {
683 TransferResult result = transferIntoDestination(connection, extract.stack(), sourceKey);
684 if (!result.moved()) return TransferResult.NO_MOVE;
685 HopperStyleEndpoints.decrementExtract(source, extract);
686 return result;
602 687 }
603 688
604 689 TransferResult transferCached(ConnectionView connection, ItemStack source,
605 690 Map<ContainerKey, DestinationState> destinations, ContainerKey sourceKey) {
606 Inventory destination = inventoryAt(connection.destination);
691 return transferIntoDestination(connection, source, sourceKey);
692 }
693
694 TransferResult transferIntoDestination(ConnectionView connection, ItemStack source, ContainerKey sourceKey) {
695 Block destinationBlock = blockAt(connection.destination);
696 if (destinationBlock == null) return TransferResult.NO_MOVE;
697
698 if (HopperStyleEndpoints.isComposter(destinationBlock)) {
699 ContainerKey destinationKey = new ContainerKey(destinationBlock.getWorld().getUID(),
700 pack(destinationBlock.getX(), destinationBlock.getY(), destinationBlock.getZ()));
701 if (destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
702 if (!HopperStyleEndpoints.insertComposter(destinationBlock, source)) return TransferResult.NO_MOVE;
703 wakeKeyInternal(destinationKey);
704 afterTransfer(connection, inventoryAt(connection.source), null);
705 return new TransferResult(true, destinationKey);
706 }
707
708 Inventory destination = inventoryOf(destinationBlock);
607 709 if (destination == null) return TransferResult.NO_MOVE;
608 710 ContainerKey destinationKey = inventoryKey(destination);
609 711 if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
610 DestinationState state = destinations.computeIfAbsent(destinationKey,
712 DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,
611 713 ignored -> new DestinationState(destination));
612 714 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
613 715 syncIncomingCache(destinationKey, state);
614 afterTransfer(connection, null, destination);
716 afterTransfer(connection, inventoryAt(connection.source), destination);
615 717 return new TransferResult(true, destinationKey);
616 718 }
617 719
618 720 void syncIncomingCache(ContainerKey destinationKey, DestinationState state) {
619 721 Group destinationGroup = groups.get(destinationKey);
620 if (destinationGroup != null && !(state.inventory instanceof FurnaceInventory)) {
722 if (destinationGroup != null
723 && !(state.inventory instanceof FurnaceInventory)
724 && !(state.inventory instanceof BrewerInventory)
725 && !(state.inventory instanceof JukeboxInventory)
726 && state.storage != null) {
621 727 // DestinationState owns this cycle-local array. Reusing it avoids
622 728 // cloning the entire destination after every inserted item.
623 729 destinationGroup.sourceCache = state.storage;
@@ -632,7 +738,12 @@ public final class OptimizedTransferPlanner {
632 738
633 739 DestinationState(Inventory inventory) {
634 740 this.inventory = inventory;
635 this.storage = inventory instanceof FurnaceInventory ? null : cloneContents(inventory.getStorageContents());
741 this.storage = inventory instanceof FurnaceInventory
742 || inventory instanceof BrewerInventory
743 || inventory instanceof JukeboxInventory
744 || inventory instanceof DecoratedPotInventory
745 ? null
746 : cloneContents(inventory.getStorageContents());
636 747 }
637 748
638 749 /**
@@ -648,9 +759,18 @@ public final class OptimizedTransferPlanner {
648 759 if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {
649 760 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
650 761 }
762
763 Boolean specialty = HopperStyleEndpoints.tryInsertOne(inventory, source);
764 if (specialty != null) return specialty;
765
651 766 ItemStack one = source.clone();
652 767 one.setAmount(1);
653 768
769 // Chiseled bookshelf uses the normal slot cache; only the datapack book tag differs.
770 if (inventory instanceof ChiseledBookshelfInventory && !HopperStyleEndpoints.isBookshelfBook(one)) {
771 return false;
772 }
773
654 774 // Furnace slots are never cached: read the real input/fuel slot for
655 775 // every attempt, so external furnace mutations cannot be overwritten.
656 776 if (inventory instanceof FurnaceInventory furnace) {
@@ -673,6 +793,8 @@ public final class OptimizedTransferPlanner {
673 793 return false;
674 794 }
675 795
796 if (storage == null) storage = cloneContents(inventory.getStorageContents());
797
676 798 // Normally attempt 0 succeeds with one getItem() validation. A second
677 799 // pass is only needed after a detected stale destination cache.
678 800 for (int attempt = 0; attempt < 2; attempt++) {
@@ -739,7 +861,7 @@ public final class OptimizedTransferPlanner {
739 861
740 862 void afterTransfer(ConnectionView connection, Inventory source, Inventory destination) {
741 863 ContainerKey sourceKey = source == null ? null : inventoryKey(source);
742 ContainerKey destinationKey = inventoryKey(destination);
864 ContainerKey destinationKey = destination == null ? null : inventoryKey(destination);
743 865 if (sourceKey != null) wakeKeyInternal(sourceKey);
744 866 if (destinationKey != null) wakeKeyInternal(destinationKey);
745 867
@@ -759,10 +881,21 @@ public final class OptimizedTransferPlanner {
759 881 }
760 882
761 883 Inventory inventoryOf(Block block) {
762 BlockState state = block.getState();
763 if (state instanceof Chest chest) return chest.getInventory();
764 if (state instanceof Container container) return container.getInventory();
765 return null;
884 return HopperStyleEndpoints.inventoryOf(block);
885 }
886
887 Block blockAt(ContainerKey key) {
888 World world = Bukkit.getWorld(key.world());
889 if (world == null) return null;
890 int x = unpackX(key.packed()), y = unpackY(key.packed()), z = unpackZ(key.packed());
891 if (!world.isChunkLoaded(x >> 4, z >> 4)) return null;
892 return world.getBlockAt(x, y, z);
893 }
894
895 Block blockAt(EndpointView endpoint) {
896 World world = Bukkit.getWorld(endpoint.world);
897 if (world == null || !world.isChunkLoaded(endpoint.x >> 4, endpoint.z >> 4)) return null;
898 return world.getBlockAt(endpoint.x, endpoint.y, endpoint.z);
766 899 }
767 900
768 901 ContainerKey endpointKey(EndpointView endpoint) {
@@ -871,6 +1004,21 @@ public final class OptimizedTransferPlanner {
871 1004 return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFFL);
872 1005 }
873 1006
1007 private static int unpackX(long packed) {
1008 int x = (int) (packed >> 38);
1009 return x >= 0x2000000 ? x - 0x4000000 : x;
1010 }
1011
1012 private static int unpackY(long packed) {
1013 int y = (int) (packed & 0xFFF);
1014 return y >= 0x800 ? y - 0x1000 : y;
1015 }
1016
1017 private static int unpackZ(long packed) {
1018 int z = (int) ((packed >> 12) & 0x3FFFFFF);
1019 return z >= 0x2000000 ? z - 0x4000000 : z;
1020 }
1021
874 1022 private static Object field(Object target, String name) throws Exception {
875 1023 FieldKey key = new FieldKey(target.getClass(), name);
876 1024 Field field = FIELDS.get(key);
@@ -10,10 +10,14 @@ import org.bukkit.block.Chest;
10import org.bukkit.block.Container;
10import org.bukkit.block.Container;
11import org.bukkit.block.DoubleChest;
11import org.bukkit.block.DoubleChest;
12import org.bukkit.configuration.file.FileConfiguration;
12import org.bukkit.configuration.file.FileConfiguration;
13import org.bukkit.inventory.BrewerInventory;
14import org.bukkit.inventory.ChiseledBookshelfInventory;
15import org.bukkit.inventory.DecoratedPotInventory;
13import org.bukkit.inventory.FurnaceInventory;
16import org.bukkit.inventory.FurnaceInventory;
14import org.bukkit.inventory.Inventory;
17import org.bukkit.inventory.Inventory;
15import org.bukkit.inventory.InventoryHolder;
18import org.bukkit.inventory.InventoryHolder;
16import org.bukkit.inventory.ItemStack;
19import org.bukkit.inventory.ItemStack;
20import org.bukkit.inventory.JukeboxInventory;
17
21
18import java.lang.reflect.*;
22import java.lang.reflect.*;
19import java.util.*;
23import java.util.*;
@@ -303,6 +307,13 @@ public final class OptimizedTransferPlanner {
303 "org.bukkit.event.inventory.FurnaceExtractEvent",
307 "org.bukkit.event.inventory.FurnaceExtractEvent",
304 "org.bukkit.event.inventory.FurnaceBurnEvent",
308 "org.bukkit.event.inventory.FurnaceBurnEvent",
305 "org.bukkit.event.block.BlockCookEvent",
309 "org.bukkit.event.block.BlockCookEvent",
310 "org.bukkit.event.inventory.BrewEvent",
311 "org.bukkit.event.inventory.BrewingStandFuelEvent",
312 "io.papermc.paper.event.block.CompostItemEvent",
313 "io.papermc.paper.event.entity.EntityCompostItemEvent",
314 // Bookshelf / pot / jukebox / composter bone-meal often change via
315 // right-click without opening an inventory GUI.
316 "org.bukkit.event.player.PlayerInteractEvent",
306 "org.bukkit.event.world.ChunkLoadEvent",
317 "org.bukkit.event.world.ChunkLoadEvent",
307 "org.bukkit.event.world.ChunkUnloadEvent"
318 "org.bukkit.event.world.ChunkUnloadEvent"
308 };
319 };
@@ -346,12 +357,17 @@ public final class OptimizedTransferPlanner {
346 Inventory inventory = (Inventory) call(event, "getInventory");
357 Inventory inventory = (Inventory) call(event, "getInventory");
347 schedule(() -> wakeInventory(inventory), 1L);
358 schedule(() -> wakeInventory(inventory), 1L);
348 } else if (name.endsWith("FurnaceSmeltEvent") || name.endsWith("FurnaceExtractEvent")
359 } else if (name.endsWith("FurnaceSmeltEvent") || name.endsWith("FurnaceExtractEvent")
349 || name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")) {
360 || name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")
361 || name.endsWith("BrewEvent") || name.endsWith("BrewingStandFuelEvent")
362 || name.endsWith("CompostItemEvent") || name.endsWith("EntityCompostItemEvent")) {
350 Block block = (Block) call(event, "getBlock");
363 Block block = (Block) call(event, "getBlock");
351 schedule(() -> {
364 schedule(() -> wakeBlock(block), 1L);
352 Inventory inventory = inventoryOf(block);
365 } else if (name.endsWith("PlayerInteractEvent")) {
353 if (inventory != null) wakeInventory(inventory);
366 Object action = call(event, "getAction");
354 }, 1L);
367 String actionName = String.valueOf(action);
368 if (!actionName.contains("RIGHT_CLICK_BLOCK") && !actionName.contains("LEFT_CLICK_BLOCK")) return;
369 Object clicked = call(event, "getClickedBlock");
370 if (clicked instanceof Block block) schedule(() -> wakeBlock(block), 1L);
355 } else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {
371 } else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {
356 // Double-chest canonical identities can change as either half loads.
372 // Double-chest canonical identities can change as either half loads.
357 lastConnectionCount = -1;
373 lastConnectionCount = -1;
@@ -363,6 +379,17 @@ public final class OptimizedTransferPlanner {
363 }
379 }
364 }
380 }
365
381
382 void wakeBlock(Block block) {
383 if (block == null) return;
384 if (HopperStyleEndpoints.isComposter(block) || HopperStyleEndpoints.isAllowed(block)
385 || block.getState() instanceof Container) {
386 wakeKeyInternal(new ContainerKey(block.getWorld().getUID(),
387 pack(block.getX(), block.getY(), block.getZ())));
388 }
389 Inventory inventory = inventoryOf(block);
390 if (inventory != null) wakeInventory(inventory);
391 }
392
366 void schedule(Runnable runnable, long delay) throws Exception {
393 void schedule(Runnable runnable, long delay) throws Exception {
367 Object scheduler = call(call(plugin, "getServer"), "getScheduler");
394 Object scheduler = call(call(plugin, "getServer"), "getScheduler");
368 Class<?> pluginInterface = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
395 Class<?> pluginInterface = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
@@ -401,8 +428,15 @@ public final class OptimizedTransferPlanner {
401 }
428 }
402
429
403 void prepareCycleBudget() {
430 void prepareCycleBudget() {
431 Block sourceBlock = blockAt(key);
432 if (HopperStyleEndpoints.isComposter(sourceBlock)) {
433 cycleBudget = null;
434 sourceCache = null;
435 return;
436 }
404 Inventory source = inventoryAt(connections.get(0).source);
437 Inventory source = inventoryAt(connections.get(0).source);
405 if (source == null || source instanceof FurnaceInventory) {
438 if (source == null || source instanceof FurnaceInventory || source instanceof BrewerInventory
439 || source instanceof JukeboxInventory) {
406 cycleBudget = null;
440 cycleBudget = null;
407 return;
441 return;
408 }
442 }
@@ -443,7 +477,8 @@ public final class OptimizedTransferPlanner {
443 }
477 }
444
478
445 boolean refreshRealInventoryIfChanged(Inventory source) {
479 boolean refreshRealInventoryIfChanged(Inventory source) {
446 if (source instanceof FurnaceInventory) return false;
480 if (source instanceof FurnaceInventory || source instanceof BrewerInventory
481 || source instanceof JukeboxInventory) return false;
447 ItemStack[] actual = source.getStorageContents();
482 ItemStack[] actual = source.getStorageContents();
448 if (sourceCache == null || actual.length != sourceCache.length) {
483 if (sourceCache == null || actual.length != sourceCache.length) {
449 sourceCache = cloneContents(actual);
484 sourceCache = cloneContents(actual);
@@ -479,6 +514,11 @@ public final class OptimizedTransferPlanner {
479 }
514 }
480
515
481 RunResult run() {
516 RunResult run() {
517 Block sourceBlock = blockAt(key);
518 if (HopperStyleEndpoints.isComposter(sourceBlock)) {
519 return runComposterSource(sourceBlock);
520 }
521
482 Inventory source = inventoryAt(connections.get(0).source);
522 Inventory source = inventoryAt(connections.get(0).source);
483 if (source == null) return RunResult.NO_MOVE;
523 if (source == null) return RunResult.NO_MOVE;
484
524
@@ -502,6 +542,28 @@ public final class OptimizedTransferPlanner {
502 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
542 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
503 }
543 }
504
544
545 // Brewing stands / jukeboxes: extract only hopper-legal slots, live (no cache).
546 if (HopperStyleEndpoints.handlesExtract(source)) {
547 boolean moved = false;
548 Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());
549 for (ConnectionView connection : filtered) {
550 if (used.contains(connection.raw)) continue;
551 HopperStyleEndpoints.Extract extract = HopperStyleEndpoints.pickExtract(source);
552 if (extract == null || !allowed(connection, extract.stack(), true, reserved)) continue;
553 TransferResult result = transferSpecialtyExtract(connection, source, extract, key);
554 if (result.moved) { used.add(connection.raw); moved = true; }
555 }
556 for (ConnectionView connection : unfiltered) {
557 if (used.contains(connection.raw)) continue;
558 HopperStyleEndpoints.Extract extract = HopperStyleEndpoints.pickExtract(source);
559 if (extract == null || !allowed(connection, extract.stack(), false, reserved)) continue;
560 TransferResult result = transferSpecialtyExtract(connection, source, extract, key);
561 if (result.moved) { used.add(connection.raw); moved = true; }
562 }
563 cacheDirty = true;
564 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
565 }
566
505 if (cycleBudget == null || cacheDirty || sourceCache == null) {
567 if (cycleBudget == null || cacheDirty || sourceCache == null) {
506 prepareCycleBudget();
568 prepareCycleBudget();
507 }
569 }
@@ -558,6 +620,36 @@ public final class OptimizedTransferPlanner {
558 }
620 }
559 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
621 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
560 }
622 }
623
624 RunResult runComposterSource(Block sourceBlock) {
625 // Simple level cache: only stage 8 yields bone meal.
626 if (HopperStyleEndpoints.readComposterLevel(sourceBlock)
627 < HopperStyleEndpoints.maxComposterLevel(sourceBlock)) {
628 return RunResult.NO_MOVE;
629 }
630 ItemStack boneMeal = new ItemStack(Material.BONE_MEAL, 1);
631 boolean moved = false;
632 Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());
633 for (ConnectionView connection : filtered) {
634 if (used.contains(connection.raw) || !allowed(connection, boneMeal, true, reserved)) continue;
635 if (!transferIntoDestination(connection, boneMeal, key).moved) continue;
636 if (!HopperStyleEndpoints.extractComposterBoneMeal(sourceBlock)) break;
637 used.add(connection.raw);
638 moved = true;
639 break; // one bone meal per cycle
640 }
641 if (!moved) {
642 for (ConnectionView connection : unfiltered) {
643 if (used.contains(connection.raw) || !allowed(connection, boneMeal, false, reserved)) continue;
644 if (!transferIntoDestination(connection, boneMeal, key).moved) continue;
645 if (!HopperStyleEndpoints.extractComposterBoneMeal(sourceBlock)) break;
646 used.add(connection.raw);
647 moved = true;
648 break;
649 }
650 }
651 return moved ? RunResult.MOVED : RunResult.NO_MOVE;
652 }
561 }
653 }
562
654
563 ItemStack[] cloneContents(ItemStack[] input) {
655 ItemStack[] cloneContents(ItemStack[] input) {
@@ -579,45 +671,59 @@ public final class OptimizedTransferPlanner {
579
671
580 TransferResult transferFurnaceOutput(ConnectionView connection, FurnaceInventory source, ContainerKey sourceKey) {
672 TransferResult transferFurnaceOutput(ConnectionView connection, FurnaceInventory source, ContainerKey sourceKey) {
581 ItemStack output = source.getResult();
673 ItemStack output = source.getResult();
582 Inventory destination = inventoryAt(connection.destination);
674 if (output == null || output.getType().isAir()) return TransferResult.NO_MOVE;
583 if (destination == null || output == null || output.getType().isAir()) return TransferResult.NO_MOVE;
675 TransferResult result = transferIntoDestination(connection, output, sourceKey);
584
676 if (!result.moved()) return TransferResult.NO_MOVE;
585 // Furnace output used to bypass cycleDestinations and write directly to
586 // the Bukkit inventory. That left a destination source-group with a
587 // stale slot cache, so freshly produced items could remain invisible to
588 // its outgoing pipes until an unrelated event or topology refresh.
589 // Route every internal insertion through the same DestinationState so
590 // multiple incoming normal/furnace pipes share one authoritative
591 // cycle-local view and downstream caches are updated transactionally.
592 ContainerKey destinationKey = inventoryKey(destination);
593 if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
594 DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,
595 ignored -> new DestinationState(destination));
596 if (!state.insertOne(output)) return TransferResult.NO_MOVE;
597
598 decrementFurnace(source);
677 decrementFurnace(source);
599 syncIncomingCache(destinationKey, state);
678 return result;
600 afterTransfer(connection, source, destination);
679 }
601 return new TransferResult(true, destinationKey);
680
681 TransferResult transferSpecialtyExtract(ConnectionView connection, Inventory source,
682 HopperStyleEndpoints.Extract extract, ContainerKey sourceKey) {
683 TransferResult result = transferIntoDestination(connection, extract.stack(), sourceKey);
684 if (!result.moved()) return TransferResult.NO_MOVE;
685 HopperStyleEndpoints.decrementExtract(source, extract);
686 return result;
602 }
687 }
603
688
604 TransferResult transferCached(ConnectionView connection, ItemStack source,
689 TransferResult transferCached(ConnectionView connection, ItemStack source,
605 Map<ContainerKey, DestinationState> destinations, ContainerKey sourceKey) {
690 Map<ContainerKey, DestinationState> destinations, ContainerKey sourceKey) {
606 Inventory destination = inventoryAt(connection.destination);
691 return transferIntoDestination(connection, source, sourceKey);
692 }
693
694 TransferResult transferIntoDestination(ConnectionView connection, ItemStack source, ContainerKey sourceKey) {
695 Block destinationBlock = blockAt(connection.destination);
696 if (destinationBlock == null) return TransferResult.NO_MOVE;
697
698 if (HopperStyleEndpoints.isComposter(destinationBlock)) {
699 ContainerKey destinationKey = new ContainerKey(destinationBlock.getWorld().getUID(),
700 pack(destinationBlock.getX(), destinationBlock.getY(), destinationBlock.getZ()));
701 if (destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
702 if (!HopperStyleEndpoints.insertComposter(destinationBlock, source)) return TransferResult.NO_MOVE;
703 wakeKeyInternal(destinationKey);
704 afterTransfer(connection, inventoryAt(connection.source), null);
705 return new TransferResult(true, destinationKey);
706 }
707
708 Inventory destination = inventoryOf(destinationBlock);
607 if (destination == null) return TransferResult.NO_MOVE;
709 if (destination == null) return TransferResult.NO_MOVE;
608 ContainerKey destinationKey = inventoryKey(destination);
710 ContainerKey destinationKey = inventoryKey(destination);
609 if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
711 if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
610 DestinationState state = destinations.computeIfAbsent(destinationKey,
712 DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,
611 ignored -> new DestinationState(destination));
713 ignored -> new DestinationState(destination));
612 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
714 if (!state.insertOne(source)) return TransferResult.NO_MOVE;
613 syncIncomingCache(destinationKey, state);
715 syncIncomingCache(destinationKey, state);
614 afterTransfer(connection, null, destination);
716 afterTransfer(connection, inventoryAt(connection.source), destination);
615 return new TransferResult(true, destinationKey);
717 return new TransferResult(true, destinationKey);
616 }
718 }
617
719
618 void syncIncomingCache(ContainerKey destinationKey, DestinationState state) {
720 void syncIncomingCache(ContainerKey destinationKey, DestinationState state) {
619 Group destinationGroup = groups.get(destinationKey);
721 Group destinationGroup = groups.get(destinationKey);
620 if (destinationGroup != null && !(state.inventory instanceof FurnaceInventory)) {
722 if (destinationGroup != null
723 && !(state.inventory instanceof FurnaceInventory)
724 && !(state.inventory instanceof BrewerInventory)
725 && !(state.inventory instanceof JukeboxInventory)
726 && state.storage != null) {
621 // DestinationState owns this cycle-local array. Reusing it avoids
727 // DestinationState owns this cycle-local array. Reusing it avoids
622 // cloning the entire destination after every inserted item.
728 // cloning the entire destination after every inserted item.
623 destinationGroup.sourceCache = state.storage;
729 destinationGroup.sourceCache = state.storage;
@@ -632,7 +738,12 @@ public final class OptimizedTransferPlanner {
632
738
633 DestinationState(Inventory inventory) {
739 DestinationState(Inventory inventory) {
634 this.inventory = inventory;
740 this.inventory = inventory;
635 this.storage = inventory instanceof FurnaceInventory ? null : cloneContents(inventory.getStorageContents());
741 this.storage = inventory instanceof FurnaceInventory
742 || inventory instanceof BrewerInventory
743 || inventory instanceof JukeboxInventory
744 || inventory instanceof DecoratedPotInventory
745 ? null
746 : cloneContents(inventory.getStorageContents());
636 }
747 }
637
748
638 /**
749 /**
@@ -648,9 +759,18 @@ public final class OptimizedTransferPlanner {
648 if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {
759 if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {
649 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
760 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
650 }
761 }
762
763 Boolean specialty = HopperStyleEndpoints.tryInsertOne(inventory, source);
764 if (specialty != null) return specialty;
765
651 ItemStack one = source.clone();
766 ItemStack one = source.clone();
652 one.setAmount(1);
767 one.setAmount(1);
653
768
769 // Chiseled bookshelf uses the normal slot cache; only the datapack book tag differs.
770 if (inventory instanceof ChiseledBookshelfInventory && !HopperStyleEndpoints.isBookshelfBook(one)) {
771 return false;
772 }
773
654 // Furnace slots are never cached: read the real input/fuel slot for
774 // Furnace slots are never cached: read the real input/fuel slot for
655 // every attempt, so external furnace mutations cannot be overwritten.
775 // every attempt, so external furnace mutations cannot be overwritten.
656 if (inventory instanceof FurnaceInventory furnace) {
776 if (inventory instanceof FurnaceInventory furnace) {
@@ -673,6 +793,8 @@ public final class OptimizedTransferPlanner {
673 return false;
793 return false;
674 }
794 }
675
795
796 if (storage == null) storage = cloneContents(inventory.getStorageContents());
797
676 // Normally attempt 0 succeeds with one getItem() validation. A second
798 // Normally attempt 0 succeeds with one getItem() validation. A second
677 // pass is only needed after a detected stale destination cache.
799 // pass is only needed after a detected stale destination cache.
678 for (int attempt = 0; attempt < 2; attempt++) {
800 for (int attempt = 0; attempt < 2; attempt++) {
@@ -739,7 +861,7 @@ public final class OptimizedTransferPlanner {
739
861
740 void afterTransfer(ConnectionView connection, Inventory source, Inventory destination) {
862 void afterTransfer(ConnectionView connection, Inventory source, Inventory destination) {
741 ContainerKey sourceKey = source == null ? null : inventoryKey(source);
863 ContainerKey sourceKey = source == null ? null : inventoryKey(source);
742 ContainerKey destinationKey = inventoryKey(destination);
864 ContainerKey destinationKey = destination == null ? null : inventoryKey(destination);
743 if (sourceKey != null) wakeKeyInternal(sourceKey);
865 if (sourceKey != null) wakeKeyInternal(sourceKey);
744 if (destinationKey != null) wakeKeyInternal(destinationKey);
866 if (destinationKey != null) wakeKeyInternal(destinationKey);
745
867
@@ -759,10 +881,21 @@ public final class OptimizedTransferPlanner {
759 }
881 }
760
882
761 Inventory inventoryOf(Block block) {
883 Inventory inventoryOf(Block block) {
762 BlockState state = block.getState();
884 return HopperStyleEndpoints.inventoryOf(block);
763 if (state instanceof Chest chest) return chest.getInventory();
885 }
764 if (state instanceof Container container) return container.getInventory();
886
765 return null;
887 Block blockAt(ContainerKey key) {
888 World world = Bukkit.getWorld(key.world());
889 if (world == null) return null;
890 int x = unpackX(key.packed()), y = unpackY(key.packed()), z = unpackZ(key.packed());
891 if (!world.isChunkLoaded(x >> 4, z >> 4)) return null;
892 return world.getBlockAt(x, y, z);
893 }
894
895 Block blockAt(EndpointView endpoint) {
896 World world = Bukkit.getWorld(endpoint.world);
897 if (world == null || !world.isChunkLoaded(endpoint.x >> 4, endpoint.z >> 4)) return null;
898 return world.getBlockAt(endpoint.x, endpoint.y, endpoint.z);
766 }
899 }
767
900
768 ContainerKey endpointKey(EndpointView endpoint) {
901 ContainerKey endpointKey(EndpointView endpoint) {
@@ -871,6 +1004,21 @@ public final class OptimizedTransferPlanner {
871 return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFFL);
1004 return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFFL);
872 }
1005 }
873
1006
1007 private static int unpackX(long packed) {
1008 int x = (int) (packed >> 38);
1009 return x >= 0x2000000 ? x - 0x4000000 : x;
1010 }
1011
1012 private static int unpackY(long packed) {
1013 int y = (int) (packed & 0xFFF);
1014 return y >= 0x800 ? y - 0x1000 : y;
1015 }
1016
1017 private static int unpackZ(long packed) {
1018 int z = (int) ((packed >> 12) & 0x3FFFFFF);
1019 return z >= 0x2000000 ? z - 0x4000000 : z;
1020 }
1021
874 private static Object field(Object target, String name) throws Exception {
1022 private static Object field(Object target, String name) throws Exception {
875 FieldKey key = new FieldKey(target.getClass(), name);
1023 FieldKey key = new FieldKey(target.getClass(), name);
876 Field field = FIELDS.get(key);
1024 Field field = FIELDS.get(key);
src/main/resources/plugin.yml +1 −1
@@ -1,5 +1,5 @@
1 1 name: ContainerPipes
2 version: '1.7.0'
2 version: '1.7.1'
3 3 main: nl.timfalken.containerpipes.ContainerPipesPlugin
4 4 api-version: '26.2'
5 5 author: Tim Falken
@@ -1,5 +1,5 @@
1name: ContainerPipes
1name: ContainerPipes
2version: '1.7.0'
2version: '1.7.1'
3main: nl.timfalken.containerpipes.ContainerPipesPlugin
3main: nl.timfalken.containerpipes.ContainerPipesPlugin
4api-version: '26.2'
4api-version: '26.2'
5author: Tim Falken
5author: Tim Falken