BlueGit

timfa copperfarmer

Add Copper Lumberers and convert vanilla golems with a copper hoe or axe.

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

timfa Tim Falken · pushed by timfa

Authored 2026-08-22 · 2 months ago

Hash
7d7e70fccca4bc4fde0ff9a45c97c226b51254f7
Parent
756d30be
12 files changed +1290 −110
src/main/java/nl/timfalken/copperfarmer/BlockRef.java added +27 −0
@@ -0,0 +1,27 @@
1 package nl.timfalken.copperfarmer;
2
3 import org.bukkit.Bukkit;
4 import org.bukkit.World;
5 import org.bukkit.block.Block;
6
7 import java.util.UUID;
8
9 record BlockRef(UUID worldId, int x, int y, int z) {
10 static BlockRef of(Block block) {
11 return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
12 }
13
14 int chunkX() {
15 return x >> 4;
16 }
17
18 int chunkZ() {
19 return z >> 4;
20 }
21
22 Block blockIfLoaded() {
23 World world = Bukkit.getWorld(worldId);
24 if (world == null || !world.isChunkLoaded(chunkX(), chunkZ())) return null;
25 return world.getBlockAt(x, y, z);
26 }
27 }
@@ -0,0 +1,27 @@
1package nl.timfalken.copperfarmer;
2
3import org.bukkit.Bukkit;
4import org.bukkit.World;
5import org.bukkit.block.Block;
6
7import java.util.UUID;
8
9record BlockRef(UUID worldId, int x, int y, int z) {
10 static BlockRef of(Block block) {
11 return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
12 }
13
14 int chunkX() {
15 return x >> 4;
16 }
17
18 int chunkZ() {
19 return z >> 4;
20 }
21
22 Block blockIfLoaded() {
23 World world = Bukkit.getWorld(worldId);
24 if (world == null || !world.isChunkLoaded(chunkX(), chunkZ())) return null;
25 return world.getBlockAt(x, y, z);
26 }
27}
src/main/java/nl/timfalken/copperfarmer/CopperFarmerPlugin.java +27 −6
@@ -27,16 +27,22 @@ public final class CopperFarmerPlugin extends JavaPlugin {
27 27 crops = new CropRegistry();
28 28 itemCodec = new FarmerItemCodec(keys);
29 29 registerFarmerRecipe();
30 registerLumbererRecipe();
30 31
31 32 seedRecipes = new SeedRecipeCache(this, crops.seedMaterials());
33 TreeRegistry trees = new TreeRegistry();
34 TreeIndex treeIndex = new TreeIndex(this, trees);
32 35
33 manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec);
34 getServer().getPluginManager().registerEvents(new FarmerListener(this, keys, manager, itemCodec), this);
36 manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec, treeIndex, trees);
37 getServer().getPluginManager().registerEvents(
38 new FarmerListener(this, keys, manager, itemCodec, treeIndex),
39 this
40 );
35 41
36 42 // Register tagged golems that were already loaded before this plugin enabled.
37 43 for (World world : Bukkit.getWorlds()) {
38 44 for (Entity entity : world.getEntities()) {
39 if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) manager.register(golem);
45 if (entity instanceof CopperGolem golem && manager.isWorker(golem)) manager.register(golem);
40 46 }
41 47 }
42 48
@@ -59,7 +65,8 @@ public final class CopperFarmerPlugin extends JavaPlugin {
59 65
60 66 private void registerFarmerRecipe() {
61 67 Bukkit.removeRecipe(keys.recipe);
62 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE));
68 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE), Material.COPPER_GOLEM_STATUE,
69 WorkerRole.FARMER);
63 70 ShapelessRecipe recipe = new ShapelessRecipe(keys.recipe, result);
64 71 recipe.addIngredient(CopperStatueVariant.recipeChoice());
65 72 recipe.addIngredient(Material.COPPER_HOE);
@@ -67,11 +74,25 @@ public final class CopperFarmerPlugin extends JavaPlugin {
67 74 getLogger().warning("Failed to register Copper Farmer crafting recipe.");
68 75 return;
69 76 }
70 // After a plugin reload the recipe exists server-side, but online players may
71 // not have rediscovered it until they reconnect.
72 77 for (Player player : Bukkit.getOnlinePlayers()) {
73 78 player.discoverRecipe(keys.recipe);
74 79 }
75 80 }
76 81
82 private void registerLumbererRecipe() {
83 Bukkit.removeRecipe(keys.lumbererRecipe);
84 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_AXE), Material.COPPER_GOLEM_STATUE,
85 WorkerRole.LUMBERER);
86 ShapelessRecipe recipe = new ShapelessRecipe(keys.lumbererRecipe, result);
87 recipe.addIngredient(CopperStatueVariant.recipeChoice());
88 recipe.addIngredient(Material.COPPER_AXE);
89 if (!Bukkit.addRecipe(recipe)) {
90 getLogger().warning("Failed to register Copper Lumberer crafting recipe.");
91 return;
92 }
93 for (Player player : Bukkit.getOnlinePlayers()) {
94 player.discoverRecipe(keys.lumbererRecipe);
95 }
96 }
97
77 98 }
@@ -27,16 +27,22 @@ public final class CopperFarmerPlugin extends JavaPlugin {
27 crops = new CropRegistry();
27 crops = new CropRegistry();
28 itemCodec = new FarmerItemCodec(keys);
28 itemCodec = new FarmerItemCodec(keys);
29 registerFarmerRecipe();
29 registerFarmerRecipe();
30 registerLumbererRecipe();
30
31
31 seedRecipes = new SeedRecipeCache(this, crops.seedMaterials());
32 seedRecipes = new SeedRecipeCache(this, crops.seedMaterials());
33 TreeRegistry trees = new TreeRegistry();
34 TreeIndex treeIndex = new TreeIndex(this, trees);
32
35
33 manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec);
36 manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec, treeIndex, trees);
34 getServer().getPluginManager().registerEvents(new FarmerListener(this, keys, manager, itemCodec), this);
37 getServer().getPluginManager().registerEvents(
38 new FarmerListener(this, keys, manager, itemCodec, treeIndex),
39 this
40 );
35
41
36 // Register tagged golems that were already loaded before this plugin enabled.
42 // Register tagged golems that were already loaded before this plugin enabled.
37 for (World world : Bukkit.getWorlds()) {
43 for (World world : Bukkit.getWorlds()) {
38 for (Entity entity : world.getEntities()) {
44 for (Entity entity : world.getEntities()) {
39 if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) manager.register(golem);
45 if (entity instanceof CopperGolem golem && manager.isWorker(golem)) manager.register(golem);
40 }
46 }
41 }
47 }
42
48
@@ -59,7 +65,8 @@ public final class CopperFarmerPlugin extends JavaPlugin {
59
65
60 private void registerFarmerRecipe() {
66 private void registerFarmerRecipe() {
61 Bukkit.removeRecipe(keys.recipe);
67 Bukkit.removeRecipe(keys.recipe);
62 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE));
68 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE), Material.COPPER_GOLEM_STATUE,
69 WorkerRole.FARMER);
63 ShapelessRecipe recipe = new ShapelessRecipe(keys.recipe, result);
70 ShapelessRecipe recipe = new ShapelessRecipe(keys.recipe, result);
64 recipe.addIngredient(CopperStatueVariant.recipeChoice());
71 recipe.addIngredient(CopperStatueVariant.recipeChoice());
65 recipe.addIngredient(Material.COPPER_HOE);
72 recipe.addIngredient(Material.COPPER_HOE);
@@ -67,11 +74,25 @@ public final class CopperFarmerPlugin extends JavaPlugin {
67 getLogger().warning("Failed to register Copper Farmer crafting recipe.");
74 getLogger().warning("Failed to register Copper Farmer crafting recipe.");
68 return;
75 return;
69 }
76 }
70 // After a plugin reload the recipe exists server-side, but online players may
71 // not have rediscovered it until they reconnect.
72 for (Player player : Bukkit.getOnlinePlayers()) {
77 for (Player player : Bukkit.getOnlinePlayers()) {
73 player.discoverRecipe(keys.recipe);
78 player.discoverRecipe(keys.recipe);
74 }
79 }
75 }
80 }
76
81
82 private void registerLumbererRecipe() {
83 Bukkit.removeRecipe(keys.lumbererRecipe);
84 ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_AXE), Material.COPPER_GOLEM_STATUE,
85 WorkerRole.LUMBERER);
86 ShapelessRecipe recipe = new ShapelessRecipe(keys.lumbererRecipe, result);
87 recipe.addIngredient(CopperStatueVariant.recipeChoice());
88 recipe.addIngredient(Material.COPPER_AXE);
89 if (!Bukkit.addRecipe(recipe)) {
90 getLogger().warning("Failed to register Copper Lumberer crafting recipe.");
91 return;
92 }
93 for (Player player : Bukkit.getOnlinePlayers()) {
94 player.discoverRecipe(keys.lumbererRecipe);
95 }
96 }
97
77}
98}
src/main/java/nl/timfalken/copperfarmer/DetectedTree.java added +107 −0
@@ -0,0 +1,107 @@
1 package nl.timfalken.copperfarmer;
2
3 import org.bukkit.World;
4 import org.bukkit.block.Block;
5
6 import java.util.ArrayList;
7 import java.util.Comparator;
8 import java.util.List;
9 import java.util.UUID;
10
11 final class DetectedTree {
12 private final UUID id;
13 private final TreeRegistry.Species species;
14 private final List<BlockRef> logs;
15 private final List<BlockRef> plantSpots;
16 private UUID claimedBy;
17
18 DetectedTree(TreeRegistry.Species species, List<BlockRef> logs, List<BlockRef> plantSpots) {
19 this.id = UUID.randomUUID();
20 this.species = species;
21 this.logs = List.copyOf(logs);
22 this.plantSpots = List.copyOf(plantSpots);
23 }
24
25 UUID id() {
26 return id;
27 }
28
29 TreeRegistry.Species species() {
30 return species;
31 }
32
33 List<BlockRef> logs() {
34 return logs;
35 }
36
37 List<BlockRef> plantSpots() {
38 return plantSpots;
39 }
40
41 List<BlockRef> chopOrder() {
42 List<BlockRef> order = new ArrayList<>(logs);
43 order.sort(Comparator.comparingInt(BlockRef::y).reversed()
44 .thenComparingInt(BlockRef::x)
45 .thenComparingInt(BlockRef::z));
46 return order;
47 }
48
49 List<BlockRef> standOrder() {
50 List<BlockRef> order = new ArrayList<>(logs);
51 order.sort(Comparator.comparingInt(BlockRef::y)
52 .thenComparingInt(BlockRef::x)
53 .thenComparingInt(BlockRef::z));
54 return order;
55 }
56
57 boolean hasLogWithin(Block origin, int radius) {
58 if (origin == null) return false;
59 UUID worldId = origin.getWorld().getUID();
60 int radiusSquared = radius * radius;
61 for (BlockRef log : logs) {
62 if (!log.worldId().equals(worldId)) continue;
63 int dx = log.x() - origin.getX();
64 int dy = log.y() - origin.getY();
65 int dz = log.z() - origin.getZ();
66 if (dx * dx + dy * dy + dz * dz <= radiusSquared) return true;
67 }
68 return false;
69 }
70
71 boolean touchesChunk(UUID worldId, int chunkX, int chunkZ) {
72 for (BlockRef log : logs) {
73 if (log.worldId().equals(worldId) && log.chunkX() == chunkX && log.chunkZ() == chunkZ) {
74 return true;
75 }
76 }
77 return false;
78 }
79
80 UUID claimedBy() {
81 return claimedBy;
82 }
83
84 boolean claim(UUID golemId) {
85 if (claimedBy != null && !claimedBy.equals(golemId)) return false;
86 claimedBy = golemId;
87 return true;
88 }
89
90 void release(UUID golemId) {
91 if (golemId.equals(claimedBy)) claimedBy = null;
92 }
93
94 boolean isAvailableFor(UUID golemId) {
95 return claimedBy == null || claimedBy.equals(golemId);
96 }
97
98 boolean stillPresent(World world) {
99 if (world == null) return false;
100 for (BlockRef log : logs) {
101 Block block = log.blockIfLoaded();
102 if (block == null) continue;
103 if (!species.isLog(block.getType())) return false;
104 }
105 return true;
106 }
107 }
@@ -0,0 +1,107 @@
1package nl.timfalken.copperfarmer;
2
3import org.bukkit.World;
4import org.bukkit.block.Block;
5
6import java.util.ArrayList;
7import java.util.Comparator;
8import java.util.List;
9import java.util.UUID;
10
11final class DetectedTree {
12 private final UUID id;
13 private final TreeRegistry.Species species;
14 private final List<BlockRef> logs;
15 private final List<BlockRef> plantSpots;
16 private UUID claimedBy;
17
18 DetectedTree(TreeRegistry.Species species, List<BlockRef> logs, List<BlockRef> plantSpots) {
19 this.id = UUID.randomUUID();
20 this.species = species;
21 this.logs = List.copyOf(logs);
22 this.plantSpots = List.copyOf(plantSpots);
23 }
24
25 UUID id() {
26 return id;
27 }
28
29 TreeRegistry.Species species() {
30 return species;
31 }
32
33 List<BlockRef> logs() {
34 return logs;
35 }
36
37 List<BlockRef> plantSpots() {
38 return plantSpots;
39 }
40
41 List<BlockRef> chopOrder() {
42 List<BlockRef> order = new ArrayList<>(logs);
43 order.sort(Comparator.comparingInt(BlockRef::y).reversed()
44 .thenComparingInt(BlockRef::x)
45 .thenComparingInt(BlockRef::z));
46 return order;
47 }
48
49 List<BlockRef> standOrder() {
50 List<BlockRef> order = new ArrayList<>(logs);
51 order.sort(Comparator.comparingInt(BlockRef::y)
52 .thenComparingInt(BlockRef::x)
53 .thenComparingInt(BlockRef::z));
54 return order;
55 }
56
57 boolean hasLogWithin(Block origin, int radius) {
58 if (origin == null) return false;
59 UUID worldId = origin.getWorld().getUID();
60 int radiusSquared = radius * radius;
61 for (BlockRef log : logs) {
62 if (!log.worldId().equals(worldId)) continue;
63 int dx = log.x() - origin.getX();
64 int dy = log.y() - origin.getY();
65 int dz = log.z() - origin.getZ();
66 if (dx * dx + dy * dy + dz * dz <= radiusSquared) return true;
67 }
68 return false;
69 }
70
71 boolean touchesChunk(UUID worldId, int chunkX, int chunkZ) {
72 for (BlockRef log : logs) {
73 if (log.worldId().equals(worldId) && log.chunkX() == chunkX && log.chunkZ() == chunkZ) {
74 return true;
75 }
76 }
77 return false;
78 }
79
80 UUID claimedBy() {
81 return claimedBy;
82 }
83
84 boolean claim(UUID golemId) {
85 if (claimedBy != null && !claimedBy.equals(golemId)) return false;
86 claimedBy = golemId;
87 return true;
88 }
89
90 void release(UUID golemId) {
91 if (golemId.equals(claimedBy)) claimedBy = null;
92 }
93
94 boolean isAvailableFor(UUID golemId) {
95 return claimedBy == null || claimedBy.equals(golemId);
96 }
97
98 boolean stillPresent(World world) {
99 if (world == null) return false;
100 for (BlockRef log : logs) {
101 Block block = log.blockIfLoaded();
102 if (block == null) continue;
103 if (!species.isLog(block.getType())) return false;
104 }
105 return true;
106 }
107}
src/main/java/nl/timfalken/copperfarmer/FarmerItemCodec.java +36 −17
@@ -14,24 +14,29 @@ final class FarmerItemCodec {
14 14 }
15 15
16 16 ItemStack createStatue(ItemStack sourceTool) {
17 return createStatue(sourceTool, Material.COPPER_GOLEM_STATUE);
17 return createStatue(sourceTool, Material.COPPER_GOLEM_STATUE, WorkerRole.FARMER);
18 18 }
19 19
20 20 ItemStack createStatue(ItemStack sourceTool, Material statueType) {
21 ItemStack tool = normalizeTool(sourceTool);
21 return createStatue(sourceTool, statueType, WorkerRole.FARMER);
22 }
23
24 ItemStack createStatue(ItemStack sourceTool, Material statueType, WorkerRole role) {
25 WorkerRole resolved = role == null ? WorkerRole.FARMER : role;
26 ItemStack tool = normalizeTool(sourceTool, resolved);
22 27 Material type = CopperStatueVariant.isStatue(statueType) ? statueType : Material.COPPER_GOLEM_STATUE;
23 28 ItemStack item = new ItemStack(type);
24 29 item.editMeta(meta -> {
25 meta.setItemName("Copper Farmer Golem");
30 meta.setItemName(resolved.displayName());
26 31 PersistentDataContainer pdc = meta.getPersistentDataContainer();
27 FarmerPersistence.stampItem(pdc, keys);
32 FarmerPersistence.stampItem(pdc, keys, resolved);
28 33 pdc.set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
29 34 });
30 35 return item;
31 36 }
32 37
33 38 ItemStack createStatue(FarmerPersistence.FarmerSnapshot snapshot, Material statueType) {
34 ItemStack item = createStatue(decodeTool(snapshot.tool()), statueType);
39 ItemStack item = createStatue(decodeTool(snapshot.tool(), snapshot.role()), statueType, snapshot.role());
35 40 item.editMeta(meta -> snapshot.apply(meta.getPersistentDataContainer(), keys));
36 41 return item;
37 42 }
@@ -41,37 +46,51 @@ final class FarmerItemCodec {
41 46 && FarmerPersistence.isFarmerItem(item.getPersistentDataContainer(), keys);
42 47 }
43 48
49 boolean isLumbererItem(ItemStack item) {
50 return item != null && !item.isEmpty()
51 && FarmerPersistence.isLumbererItem(item.getPersistentDataContainer(), keys);
52 }
53
54 boolean isWorkerItem(ItemStack item) {
55 return isFarmerItem(item) || isLumbererItem(item);
56 }
57
44 58 ItemStack readTool(ItemStack farmerItem) {
45 if (farmerItem == null || farmerItem.isEmpty()) return defaultTool();
46 return decodeTool(farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY));
59 if (farmerItem == null || farmerItem.isEmpty()) return defaultTool(WorkerRole.FARMER);
60 WorkerRole role = FarmerPersistence.roleOf(farmerItem.getPersistentDataContainer(), keys);
61 return decodeTool(farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY), role);
47 62 }
48 63
49 64 ItemStack readTool(CopperGolem golem) {
50 return decodeTool(golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY));
65 WorkerRole role = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
66 return decodeTool(golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY), role);
51 67 }
52 68
53 69 void storeTool(CopperGolem golem, ItemStack sourceTool) {
54 ItemStack tool = normalizeTool(sourceTool);
70 WorkerRole role = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
71 if (role == null) role = WorkerRole.FARMER;
72 ItemStack tool = normalizeTool(sourceTool, role);
55 73 golem.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
56 74 }
57 75
58 private ItemStack decodeTool(byte[] bytes) {
59 if (bytes == null || bytes.length == 0) return defaultTool();
76 private ItemStack decodeTool(byte[] bytes, WorkerRole role) {
77 WorkerRole resolved = role == null ? WorkerRole.FARMER : role;
78 if (bytes == null || bytes.length == 0) return defaultTool(resolved);
60 79 try {
61 return normalizeTool(ItemStack.deserializeBytes(bytes));
80 return normalizeTool(ItemStack.deserializeBytes(bytes), resolved);
62 81 } catch (RuntimeException ex) {
63 return defaultTool();
82 return defaultTool(resolved);
64 83 }
65 84 }
66 85
67 private ItemStack normalizeTool(ItemStack source) {
68 if (source == null || source.isEmpty() || source.getType() != Material.COPPER_HOE) return defaultTool();
86 private ItemStack normalizeTool(ItemStack source, WorkerRole role) {
87 if (source == null || source.isEmpty() || source.getType() != role.toolType()) return defaultTool(role);
69 88 ItemStack copy = source.clone();
70 89 copy.setAmount(1);
71 90 return copy;
72 91 }
73 92
74 private ItemStack defaultTool() {
75 return new ItemStack(Material.COPPER_HOE);
93 private ItemStack defaultTool(WorkerRole role) {
94 return new ItemStack(role.toolType());
76 95 }
77 96 }
@@ -14,24 +14,29 @@ final class FarmerItemCodec {
14 }
14 }
15
15
16 ItemStack createStatue(ItemStack sourceTool) {
16 ItemStack createStatue(ItemStack sourceTool) {
17 return createStatue(sourceTool, Material.COPPER_GOLEM_STATUE);
17 return createStatue(sourceTool, Material.COPPER_GOLEM_STATUE, WorkerRole.FARMER);
18 }
18 }
19
19
20 ItemStack createStatue(ItemStack sourceTool, Material statueType) {
20 ItemStack createStatue(ItemStack sourceTool, Material statueType) {
21 ItemStack tool = normalizeTool(sourceTool);
21 return createStatue(sourceTool, statueType, WorkerRole.FARMER);
22 }
23
24 ItemStack createStatue(ItemStack sourceTool, Material statueType, WorkerRole role) {
25 WorkerRole resolved = role == null ? WorkerRole.FARMER : role;
26 ItemStack tool = normalizeTool(sourceTool, resolved);
22 Material type = CopperStatueVariant.isStatue(statueType) ? statueType : Material.COPPER_GOLEM_STATUE;
27 Material type = CopperStatueVariant.isStatue(statueType) ? statueType : Material.COPPER_GOLEM_STATUE;
23 ItemStack item = new ItemStack(type);
28 ItemStack item = new ItemStack(type);
24 item.editMeta(meta -> {
29 item.editMeta(meta -> {
25 meta.setItemName("Copper Farmer Golem");
30 meta.setItemName(resolved.displayName());
26 PersistentDataContainer pdc = meta.getPersistentDataContainer();
31 PersistentDataContainer pdc = meta.getPersistentDataContainer();
27 FarmerPersistence.stampItem(pdc, keys);
32 FarmerPersistence.stampItem(pdc, keys, resolved);
28 pdc.set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
33 pdc.set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
29 });
34 });
30 return item;
35 return item;
31 }
36 }
32
37
33 ItemStack createStatue(FarmerPersistence.FarmerSnapshot snapshot, Material statueType) {
38 ItemStack createStatue(FarmerPersistence.FarmerSnapshot snapshot, Material statueType) {
34 ItemStack item = createStatue(decodeTool(snapshot.tool()), statueType);
39 ItemStack item = createStatue(decodeTool(snapshot.tool(), snapshot.role()), statueType, snapshot.role());
35 item.editMeta(meta -> snapshot.apply(meta.getPersistentDataContainer(), keys));
40 item.editMeta(meta -> snapshot.apply(meta.getPersistentDataContainer(), keys));
36 return item;
41 return item;
37 }
42 }
@@ -41,37 +46,51 @@ final class FarmerItemCodec {
41 && FarmerPersistence.isFarmerItem(item.getPersistentDataContainer(), keys);
46 && FarmerPersistence.isFarmerItem(item.getPersistentDataContainer(), keys);
42 }
47 }
43
48
49 boolean isLumbererItem(ItemStack item) {
50 return item != null && !item.isEmpty()
51 && FarmerPersistence.isLumbererItem(item.getPersistentDataContainer(), keys);
52 }
53
54 boolean isWorkerItem(ItemStack item) {
55 return isFarmerItem(item) || isLumbererItem(item);
56 }
57
44 ItemStack readTool(ItemStack farmerItem) {
58 ItemStack readTool(ItemStack farmerItem) {
45 if (farmerItem == null || farmerItem.isEmpty()) return defaultTool();
59 if (farmerItem == null || farmerItem.isEmpty()) return defaultTool(WorkerRole.FARMER);
46 return decodeTool(farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY));
60 WorkerRole role = FarmerPersistence.roleOf(farmerItem.getPersistentDataContainer(), keys);
61 return decodeTool(farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY), role);
47 }
62 }
48
63
49 ItemStack readTool(CopperGolem golem) {
64 ItemStack readTool(CopperGolem golem) {
50 return decodeTool(golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY));
65 WorkerRole role = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
66 return decodeTool(golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY), role);
51 }
67 }
52
68
53 void storeTool(CopperGolem golem, ItemStack sourceTool) {
69 void storeTool(CopperGolem golem, ItemStack sourceTool) {
54 ItemStack tool = normalizeTool(sourceTool);
70 WorkerRole role = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
71 if (role == null) role = WorkerRole.FARMER;
72 ItemStack tool = normalizeTool(sourceTool, role);
55 golem.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
73 golem.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
56 }
74 }
57
75
58 private ItemStack decodeTool(byte[] bytes) {
76 private ItemStack decodeTool(byte[] bytes, WorkerRole role) {
59 if (bytes == null || bytes.length == 0) return defaultTool();
77 WorkerRole resolved = role == null ? WorkerRole.FARMER : role;
78 if (bytes == null || bytes.length == 0) return defaultTool(resolved);
60 try {
79 try {
61 return normalizeTool(ItemStack.deserializeBytes(bytes));
80 return normalizeTool(ItemStack.deserializeBytes(bytes), resolved);
62 } catch (RuntimeException ex) {
81 } catch (RuntimeException ex) {
63 return defaultTool();
82 return defaultTool(resolved);
64 }
83 }
65 }
84 }
66
85
67 private ItemStack normalizeTool(ItemStack source) {
86 private ItemStack normalizeTool(ItemStack source, WorkerRole role) {
68 if (source == null || source.isEmpty() || source.getType() != Material.COPPER_HOE) return defaultTool();
87 if (source == null || source.isEmpty() || source.getType() != role.toolType()) return defaultTool(role);
69 ItemStack copy = source.clone();
88 ItemStack copy = source.clone();
70 copy.setAmount(1);
89 copy.setAmount(1);
71 return copy;
90 return copy;
72 }
91 }
73
92
74 private ItemStack defaultTool() {
93 private ItemStack defaultTool(WorkerRole role) {
75 return new ItemStack(Material.COPPER_HOE);
94 return new ItemStack(role.toolType());
76 }
95 }
77}
96}
src/main/java/nl/timfalken/copperfarmer/FarmerKeys.java +6 −0
@@ -6,6 +6,8 @@ import org.bukkit.plugin.Plugin;
6 6 final class FarmerKeys {
7 7 final NamespacedKey farmerItem;
8 8 final NamespacedKey farmerEntity;
9 final NamespacedKey lumbererItem;
10 final NamespacedKey lumbererEntity;
9 11 final NamespacedKey cargo;
10 12 final NamespacedKey tool;
11 13 final NamespacedKey chestWorld;
@@ -13,10 +15,13 @@ final class FarmerKeys {
13 15 final NamespacedKey chestY;
14 16 final NamespacedKey chestZ;
15 17 final NamespacedKey recipe;
18 final NamespacedKey lumbererRecipe;
16 19
17 20 FarmerKeys(Plugin plugin) {
18 21 farmerItem = new NamespacedKey(plugin, "farmer_item");
19 22 farmerEntity = new NamespacedKey(plugin, "farmer_entity");
23 lumbererItem = new NamespacedKey(plugin, "lumberer_item");
24 lumbererEntity = new NamespacedKey(plugin, "lumberer_entity");
20 25 cargo = new NamespacedKey(plugin, "cargo");
21 26 tool = new NamespacedKey(plugin, "tool");
22 27 chestWorld = new NamespacedKey(plugin, "chest_world");
@@ -24,5 +29,6 @@ final class FarmerKeys {
24 29 chestY = new NamespacedKey(plugin, "chest_y");
25 30 chestZ = new NamespacedKey(plugin, "chest_z");
26 31 recipe = new NamespacedKey(plugin, "farmer_statue");
32 lumbererRecipe = new NamespacedKey(plugin, "lumberer_statue");
27 33 }
28 34 }
@@ -6,6 +6,8 @@ import org.bukkit.plugin.Plugin;
6final class FarmerKeys {
6final class FarmerKeys {
7 final NamespacedKey farmerItem;
7 final NamespacedKey farmerItem;
8 final NamespacedKey farmerEntity;
8 final NamespacedKey farmerEntity;
9 final NamespacedKey lumbererItem;
10 final NamespacedKey lumbererEntity;
9 final NamespacedKey cargo;
11 final NamespacedKey cargo;
10 final NamespacedKey tool;
12 final NamespacedKey tool;
11 final NamespacedKey chestWorld;
13 final NamespacedKey chestWorld;
@@ -13,10 +15,13 @@ final class FarmerKeys {
13 final NamespacedKey chestY;
15 final NamespacedKey chestY;
14 final NamespacedKey chestZ;
16 final NamespacedKey chestZ;
15 final NamespacedKey recipe;
17 final NamespacedKey recipe;
18 final NamespacedKey lumbererRecipe;
16
19
17 FarmerKeys(Plugin plugin) {
20 FarmerKeys(Plugin plugin) {
18 farmerItem = new NamespacedKey(plugin, "farmer_item");
21 farmerItem = new NamespacedKey(plugin, "farmer_item");
19 farmerEntity = new NamespacedKey(plugin, "farmer_entity");
22 farmerEntity = new NamespacedKey(plugin, "farmer_entity");
23 lumbererItem = new NamespacedKey(plugin, "lumberer_item");
24 lumbererEntity = new NamespacedKey(plugin, "lumberer_entity");
20 cargo = new NamespacedKey(plugin, "cargo");
25 cargo = new NamespacedKey(plugin, "cargo");
21 tool = new NamespacedKey(plugin, "tool");
26 tool = new NamespacedKey(plugin, "tool");
22 chestWorld = new NamespacedKey(plugin, "chest_world");
27 chestWorld = new NamespacedKey(plugin, "chest_world");
@@ -24,5 +29,6 @@ final class FarmerKeys {
24 chestY = new NamespacedKey(plugin, "chest_y");
29 chestY = new NamespacedKey(plugin, "chest_y");
25 chestZ = new NamespacedKey(plugin, "chest_z");
30 chestZ = new NamespacedKey(plugin, "chest_z");
26 recipe = new NamespacedKey(plugin, "farmer_statue");
31 recipe = new NamespacedKey(plugin, "farmer_statue");
32 lumbererRecipe = new NamespacedKey(plugin, "lumberer_statue");
27 }
33 }
28}
34}
src/main/java/nl/timfalken/copperfarmer/FarmerListener.java +116 −48
@@ -1,5 +1,6 @@
1 1 package nl.timfalken.copperfarmer;
2 2
3 import org.bukkit.GameMode;
3 4 import org.bukkit.Location;
4 5 import org.bukkit.Material;
5 6 import org.bukkit.Tag;
@@ -12,6 +13,7 @@ import org.bukkit.event.EventHandler;
12 13 import org.bukkit.event.EventPriority;
13 14 import org.bukkit.event.Listener;
14 15 import org.bukkit.event.block.Action;
16 import org.bukkit.event.block.BlockBreakEvent;
15 17 import org.bukkit.event.block.BlockDropItemEvent;
16 18 import org.bukkit.event.block.BlockPlaceEvent;
17 19 import org.bukkit.event.block.CrafterCraftEvent;
@@ -26,6 +28,7 @@ import org.bukkit.event.player.PlayerInteractEvent;
26 28 import org.bukkit.event.player.PlayerJoinEvent;
27 29 import org.bukkit.event.world.EntitiesLoadEvent;
28 30 import org.bukkit.event.world.EntitiesUnloadEvent;
31 import org.bukkit.event.world.StructureGrowEvent;
29 32 import org.bukkit.inventory.EntityEquipment;
30 33 import org.bukkit.inventory.InventoryHolder;
31 34 import org.bukkit.inventory.ItemStack;
@@ -43,18 +46,27 @@ final class FarmerListener implements Listener {
43 46 private final FarmerKeys keys;
44 47 private final FarmerManager manager;
45 48 private final FarmerItemCodec itemCodec;
49 private final TreeIndex treeIndex;
46 50 private final Set<UUID> petrifying = new HashSet<>();
47 51
48 FarmerListener(Plugin plugin, FarmerKeys keys, FarmerManager manager, FarmerItemCodec itemCodec) {
52 FarmerListener(
53 Plugin plugin,
54 FarmerKeys keys,
55 FarmerManager manager,
56 FarmerItemCodec itemCodec,
57 TreeIndex treeIndex
58 ) {
49 59 this.plugin = plugin;
50 60 this.keys = keys;
51 61 this.manager = manager;
52 62 this.itemCodec = itemCodec;
63 this.treeIndex = treeIndex;
53 64 }
54 65
55 66 @EventHandler
56 67 public void onPlayerJoin(PlayerJoinEvent event) {
57 68 event.getPlayer().discoverRecipe(keys.recipe);
69 event.getPlayer().discoverRecipe(keys.lumbererRecipe);
58 70 }
59 71
60 72 @EventHandler(priority = EventPriority.HIGHEST)
@@ -85,8 +97,8 @@ final class FarmerListener implements Listener {
85 97 }
86 98
87 99 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
88 public void onFarmerStatuePlaced(BlockPlaceEvent event) {
89 if (!itemCodec.isFarmerItem(event.getItemInHand())) return;
100 public void onWorkerStatuePlaced(BlockPlaceEvent event) {
101 if (!itemCodec.isWorkerItem(event.getItemInHand())) return;
90 102
91 103 Block placed = event.getBlockPlaced();
92 104 CopperStatueVariant variant = CopperStatueVariant.from(placed.getType());
@@ -97,6 +109,7 @@ final class FarmerListener implements Listener {
97 109 FarmerPersistence.capture(placedItem.getPersistentDataContainer(), keys),
98 110 placed.getLocation()
99 111 );
112 WorkerRole role = snapshot.role();
100 113
101 114 Location location = placed.getLocation();
102 115 plugin.getServer().getScheduler().runTask(plugin, () -> {
@@ -107,20 +120,21 @@ final class FarmerListener implements Listener {
107 120 Location spawn = location.clone().add(0.5, 0.0, 0.5);
108 121 CopperGolem golem = location.getWorld().spawn(spawn, CopperGolem.class, entity -> {
109 122 PersistentDataContainer pdc = entity.getPersistentDataContainer();
110 FarmerPersistence.stampEntity(pdc, keys);
123 FarmerPersistence.stampEntity(pdc, keys, role);
111 124 snapshot.apply(pdc, keys);
112 125 variant.applyTo(entity);
113 FarmerManager.persistFarmer(entity);
126 FarmerManager.persistWorker(entity, role);
114 127 });
115 128 manager.register(golem);
116 129 });
117 130 }
118 131
119 132 @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
120 public void onFarmerPetrify(EntityChangeBlockEvent event) {
121 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
133 public void onWorkerPetrify(EntityChangeBlockEvent event) {
134 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
122 135 if (!CopperStatueVariant.isStatue(event.getTo())) return;
123 136
137 WorkerRole role = manager.roleOf(golem);
124 138 petrifying.add(golem.getUniqueId());
125 139 EntityEquipment equipment = golem.getEquipment();
126 140 if (equipment != null) equipment.setItemInMainHand(null);
@@ -139,13 +153,37 @@ final class FarmerListener implements Listener {
139 153 Location location = event.getBlock().getLocation();
140 154 plugin.getServer().getScheduler().runTask(plugin, () -> {
141 155 petrifying.remove(golem.getUniqueId());
142 writeSnapshotToStatue(location.getBlock(), snapshot);
156 writeSnapshotToStatue(location.getBlock(), snapshot, role);
143 157 });
144 158 }
145 159
146 160 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
147 public void onFarmerInteract(PlayerInteractEntityEvent event) {
148 if (!(event.getRightClicked() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
161 public void onVanillaGolemConvert(PlayerInteractEntityEvent event) {
162 if (!(event.getRightClicked() instanceof CopperGolem golem) || manager.isWorker(golem)) return;
163
164 ItemStack used = event.getPlayer().getInventory().getItem(event.getHand());
165 WorkerRole role = roleFromConversionTool(used);
166 if (role == null || isNameTag(used)) return;
167
168 event.setCancelled(true);
169
170 ItemStack tool = used.clone();
171 tool.setAmount(1);
172 if (event.getPlayer().getGameMode() != GameMode.CREATIVE) {
173 used.setAmount(used.getAmount() - 1);
174 }
175
176 PersistentDataContainer pdc = golem.getPersistentDataContainer();
177 FarmerPersistence.stampEntity(pdc, keys, role);
178 itemCodec.storeTool(golem, tool);
179 FarmerManager.persistWorker(golem, role);
180 manager.register(golem);
181 manager.resyncHeldItem(golem, event.getPlayer());
182 }
183
184 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
185 public void onWorkerInteract(PlayerInteractEntityEvent event) {
186 if (!(event.getRightClicked() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
149 187
150 188 ItemStack used = event.getPlayer().getInventory().getItem(event.getHand());
151 189 if (isOxidationTool(used) || isNameTag(used)) return;
@@ -155,8 +193,8 @@ final class FarmerListener implements Listener {
155 193 }
156 194
157 195 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
158 public void onFarmerDropItem(EntityDropItemEvent event) {
159 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
196 public void onWorkerDropItem(EntityDropItemEvent event) {
197 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
160 198 event.setCancelled(true);
161 199 manager.resyncHeldItem(golem);
162 200 }
@@ -165,7 +203,7 @@ final class FarmerListener implements Listener {
165 203 public void onStatueWaxOrScrape(PlayerInteractEvent event) {
166 204 if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
167 205 Block block = event.getClickedBlock();
168 if (block == null || !FarmerPersistence.isFarmerStatue(block, keys)) return;
206 if (block == null || !FarmerPersistence.isWorkerStatue(block, keys)) return;
169 207 ItemStack item = event.getItem();
170 208 if (!isOxidationTool(item)) return;
171 209
@@ -177,26 +215,26 @@ final class FarmerListener implements Listener {
177 215 }
178 216
179 217 @EventHandler(ignoreCancelled = true)
180 public void onFarmerStatueDrops(BlockDropItemEvent event) {
218 public void onWorkerStatueDrops(BlockDropItemEvent event) {
181 219 if (!(event.getBlockState() instanceof CopperGolemStatue statue)) return;
182 if (!FarmerPersistence.isFarmerEntity(statue.getPersistentDataContainer(), keys)) return;
220 if (!FarmerPersistence.isWorkerEntity(statue.getPersistentDataContainer(), keys)) return;
183 221
184 222 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys)
185 223 .withoutCargo();
186 ItemStack farmer = itemCodec.createStatue(snapshot, event.getBlockState().getType());
224 ItemStack worker = itemCodec.createStatue(snapshot, event.getBlockState().getType());
187 225 var drops = event.getItems();
188 226 if (drops.isEmpty()) {
189 event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.5, 0.5), farmer);
227 event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.5, 0.5), worker);
190 228 return;
191 229 }
192 drops.getFirst().setItemStack(farmer);
230 drops.getFirst().setItemStack(worker);
193 231 while (drops.size() > 1) drops.remove(1);
194 232 }
195 233
196 234 @EventHandler
197 235 public void onEntitiesLoad(EntitiesLoadEvent event) {
198 236 for (Entity entity : event.getEntities()) {
199 if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) {
237 if (entity instanceof CopperGolem golem && manager.isWorker(golem)) {
200 238 manager.register(golem);
201 239 }
202 240 }
@@ -205,26 +243,26 @@ final class FarmerListener implements Listener {
205 243 @EventHandler
206 244 public void onEntitiesUnload(EntitiesUnloadEvent event) {
207 245 for (Entity entity : event.getEntities()) {
208 if (manager.isFarmer(entity)) manager.unregister(entity);
246 if (manager.isWorker(entity)) manager.unregister(entity);
209 247 }
210 248 }
211 249
212 250 @EventHandler(priority = EventPriority.MONITOR)
213 public void onFarmerRemoved(EntityRemoveEvent event) {
214 if (!manager.isFarmer(event.getEntity())) return;
251 public void onWorkerRemoved(EntityRemoveEvent event) {
252 if (!manager.isWorker(event.getEntity())) return;
215 253 EntityRemoveEvent.Cause cause = event.getCause();
216 254 if (cause == EntityRemoveEvent.Cause.UNLOAD
217 255 || cause == EntityRemoveEvent.Cause.DEATH
218 256 || cause == EntityRemoveEvent.Cause.TRANSFORMATION) {
219 257 return;
220 258 }
221 plugin.getLogger().warning("Farmer golem removed (" + cause + ") at "
259 plugin.getLogger().warning("Worker golem removed (" + cause + ") at "
222 260 + formatLocation(event.getEntity().getLocation()));
223 261 }
224 262
225 263 @EventHandler(priority = EventPriority.HIGHEST)
226 264 public void onDeath(EntityDeathEvent event) {
227 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
265 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
228 266 if (petrifying.remove(golem.getUniqueId())) {
229 267 event.getDrops().clear();
230 268 event.setDroppedExp(0);
@@ -233,40 +271,59 @@ final class FarmerListener implements Listener {
233 271 event.getDrops().addAll(manager.deathDrops(golem));
234 272 }
235 273
274 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
275 public void onTreeGrow(StructureGrowEvent event) {
276 treeIndex.onStructureGrow(event);
277 }
278
279 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
280 public void onLogBroken(BlockBreakEvent event) {
281 treeIndex.onBlockChanged(event.getBlock());
282 }
283
236 284 private ItemStack craftResult(Recipe recipe, ItemStack[] contents, ItemStack vanillaResult) {
237 if (isFarmerRecipe(recipe)) return farmerResultFrom(contents);
238 return preserveFarmerOnStatueResult(contents, vanillaResult);
285 if (isFarmerRecipe(recipe)) {
286 if (itemCodec.isLumbererItem(findStatue(contents))) return new ItemStack(Material.AIR);
287 return workerResultFrom(contents, WorkerRole.FARMER, Material.COPPER_HOE);
288 }
289 if (isLumbererRecipe(recipe)) {
290 if (itemCodec.isFarmerItem(findStatue(contents))) return new ItemStack(Material.AIR);
291 return workerResultFrom(contents, WorkerRole.LUMBERER, Material.COPPER_AXE);
292 }
293 return preserveWorkerOnStatueResult(contents, vanillaResult);
239 294 }
240 295
241 private ItemStack preserveFarmerOnStatueResult(ItemStack[] contents, ItemStack vanillaResult) {
296 private ItemStack preserveWorkerOnStatueResult(ItemStack[] contents, ItemStack vanillaResult) {
242 297 if (vanillaResult == null || !CopperStatueVariant.isStatue(vanillaResult.getType())) return null;
243 ItemStack farmer = findFarmerStatue(contents);
244 if (farmer == null) return null;
298 ItemStack worker = findWorkerStatue(contents);
299 if (worker == null) return null;
245 300 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(
246 farmer.getPersistentDataContainer(),
301 worker.getPersistentDataContainer(),
247 302 keys
248 303 );
249 304 return itemCodec.createStatue(snapshot, vanillaResult.getType());
250 305 }
251 306
252 private ItemStack farmerResultFrom(ItemStack[] contents) {
253 ItemStack hoe = findCopperHoe(contents);
307 private ItemStack workerResultFrom(ItemStack[] contents, WorkerRole role, Material toolType) {
308 ItemStack tool = findTool(contents, toolType);
254 309 ItemStack statue = findStatue(contents);
255 if (hoe == null || statue == null) return null;
256 if (!itemCodec.isFarmerItem(statue)) {
257 return itemCodec.createStatue(hoe, statue.getType());
310 if (tool == null || statue == null) return null;
311 if (!itemCodec.isWorkerItem(statue)) {
312 return itemCodec.createStatue(tool, statue.getType(), role);
258 313 }
259 314
260 315 FarmerPersistence.FarmerSnapshot existing = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys);
261 ItemStack withNewHoe = itemCodec.createStatue(hoe, statue.getType());
262 FarmerPersistence.FarmerSnapshot hoeOnly = FarmerPersistence.capture(withNewHoe.getPersistentDataContainer(), keys);
316 if (existing.role() != role) return null;
317 ItemStack withNewTool = itemCodec.createStatue(tool, statue.getType(), role);
318 FarmerPersistence.FarmerSnapshot toolOnly = FarmerPersistence.capture(withNewTool.getPersistentDataContainer(), keys);
263 319 return itemCodec.createStatue(new FarmerPersistence.FarmerSnapshot(
264 hoeOnly.tool(),
320 toolOnly.tool(),
265 321 existing.cargo(),
266 322 existing.chestWorld(),
267 323 existing.chestX(),
268 324 existing.chestY(),
269 existing.chestZ()
325 existing.chestZ(),
326 role
270 327 ), statue.getType());
271 328 }
272 329
@@ -290,32 +347,39 @@ final class FarmerListener implements Listener {
290 347 private void restoreAfterVanillaConversion(Location location, FarmerPersistence.FarmerSnapshot snapshot) {
291 348 Block block = location.getBlock();
292 349 if (block.getState() instanceof CopperGolemStatue statue) {
293 writeSnapshotToStatue(block, snapshot);
350 writeSnapshotToStatue(block, snapshot, snapshot.role());
294 351 return;
295 352 }
296 353
297 354 Location center = location.clone().add(0.5, 0.0, 0.5);
298 355 for (Entity entity : location.getWorld().getNearbyEntities(center, 0.75, 1.0, 0.75)) {
299 356 if (!(entity instanceof CopperGolem golem)) continue;
300 if (manager.isFarmer(golem) || FarmerPersistence.isFarmerEntity(golem.getPersistentDataContainer(), keys)) {
357 if (manager.isWorker(golem) || FarmerPersistence.isWorkerEntity(golem.getPersistentDataContainer(), keys)) {
301 358 continue;
302 359 }
303 360 PersistentDataContainer pdc = golem.getPersistentDataContainer();
304 FarmerPersistence.stampEntity(pdc, keys);
361 FarmerPersistence.stampEntity(pdc, keys, snapshot.role());
305 362 snapshot.apply(pdc, keys);
306 363 manager.register(golem);
307 364 return;
308 365 }
309 366 }
310 367
311 private void writeSnapshotToStatue(Block block, FarmerPersistence.FarmerSnapshot snapshot) {
368 private void writeSnapshotToStatue(Block block, FarmerPersistence.FarmerSnapshot snapshot, WorkerRole role) {
312 369 if (!(block.getState() instanceof CopperGolemStatue statue)) return;
313 370 PersistentDataContainer pdc = statue.getPersistentDataContainer();
314 FarmerPersistence.stampEntity(pdc, keys);
371 FarmerPersistence.stampEntity(pdc, keys, role);
315 372 snapshot.apply(pdc, keys);
316 373 statue.update();
317 374 }
318 375
376 private WorkerRole roleFromConversionTool(ItemStack item) {
377 if (item == null || item.isEmpty()) return null;
378 if (item.getType() == Material.COPPER_HOE) return WorkerRole.FARMER;
379 if (item.getType() == Material.COPPER_AXE) return WorkerRole.LUMBERER;
380 return null;
381 }
382
319 383 private boolean isOxidationTool(ItemStack item) {
320 384 if (item == null || item.isEmpty()) return false;
321 385 return item.getType() == Material.HONEYCOMB || Tag.ITEMS_AXES.isTagged(item.getType());
@@ -337,10 +401,14 @@ final class FarmerListener implements Listener {
337 401 return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.recipe);
338 402 }
339 403
340 private ItemStack findCopperHoe(ItemStack[] contents) {
404 private boolean isLumbererRecipe(Recipe recipe) {
405 return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.lumbererRecipe);
406 }
407
408 private ItemStack findTool(ItemStack[] contents, Material type) {
341 409 if (contents == null) return null;
342 410 for (ItemStack item : contents) {
343 if (item == null || item.isEmpty() || item.getType() != Material.COPPER_HOE) continue;
411 if (item == null || item.isEmpty() || item.getType() != type) continue;
344 412 ItemStack copy = item.clone();
345 413 copy.setAmount(1);
346 414 return copy;
@@ -348,9 +416,9 @@ final class FarmerListener implements Listener {
348 416 return null;
349 417 }
350 418
351 private ItemStack findFarmerStatue(ItemStack[] contents) {
419 private ItemStack findWorkerStatue(ItemStack[] contents) {
352 420 ItemStack statue = findStatue(contents);
353 return itemCodec.isFarmerItem(statue) ? statue : null;
421 return itemCodec.isWorkerItem(statue) ? statue : null;
354 422 }
355 423
356 424 private ItemStack findStatue(ItemStack[] contents) {
@@ -1,5 +1,6 @@
1package nl.timfalken.copperfarmer;
1package nl.timfalken.copperfarmer;
2
2
3import org.bukkit.GameMode;
3import org.bukkit.Location;
4import org.bukkit.Location;
4import org.bukkit.Material;
5import org.bukkit.Material;
5import org.bukkit.Tag;
6import org.bukkit.Tag;
@@ -12,6 +13,7 @@ import org.bukkit.event.EventHandler;
12import org.bukkit.event.EventPriority;
13import org.bukkit.event.EventPriority;
13import org.bukkit.event.Listener;
14import org.bukkit.event.Listener;
14import org.bukkit.event.block.Action;
15import org.bukkit.event.block.Action;
16import org.bukkit.event.block.BlockBreakEvent;
15import org.bukkit.event.block.BlockDropItemEvent;
17import org.bukkit.event.block.BlockDropItemEvent;
16import org.bukkit.event.block.BlockPlaceEvent;
18import org.bukkit.event.block.BlockPlaceEvent;
17import org.bukkit.event.block.CrafterCraftEvent;
19import org.bukkit.event.block.CrafterCraftEvent;
@@ -26,6 +28,7 @@ import org.bukkit.event.player.PlayerInteractEvent;
26import org.bukkit.event.player.PlayerJoinEvent;
28import org.bukkit.event.player.PlayerJoinEvent;
27import org.bukkit.event.world.EntitiesLoadEvent;
29import org.bukkit.event.world.EntitiesLoadEvent;
28import org.bukkit.event.world.EntitiesUnloadEvent;
30import org.bukkit.event.world.EntitiesUnloadEvent;
31import org.bukkit.event.world.StructureGrowEvent;
29import org.bukkit.inventory.EntityEquipment;
32import org.bukkit.inventory.EntityEquipment;
30import org.bukkit.inventory.InventoryHolder;
33import org.bukkit.inventory.InventoryHolder;
31import org.bukkit.inventory.ItemStack;
34import org.bukkit.inventory.ItemStack;
@@ -43,18 +46,27 @@ final class FarmerListener implements Listener {
43 private final FarmerKeys keys;
46 private final FarmerKeys keys;
44 private final FarmerManager manager;
47 private final FarmerManager manager;
45 private final FarmerItemCodec itemCodec;
48 private final FarmerItemCodec itemCodec;
49 private final TreeIndex treeIndex;
46 private final Set<UUID> petrifying = new HashSet<>();
50 private final Set<UUID> petrifying = new HashSet<>();
47
51
48 FarmerListener(Plugin plugin, FarmerKeys keys, FarmerManager manager, FarmerItemCodec itemCodec) {
52 FarmerListener(
53 Plugin plugin,
54 FarmerKeys keys,
55 FarmerManager manager,
56 FarmerItemCodec itemCodec,
57 TreeIndex treeIndex
58 ) {
49 this.plugin = plugin;
59 this.plugin = plugin;
50 this.keys = keys;
60 this.keys = keys;
51 this.manager = manager;
61 this.manager = manager;
52 this.itemCodec = itemCodec;
62 this.itemCodec = itemCodec;
63 this.treeIndex = treeIndex;
53 }
64 }
54
65
55 @EventHandler
66 @EventHandler
56 public void onPlayerJoin(PlayerJoinEvent event) {
67 public void onPlayerJoin(PlayerJoinEvent event) {
57 event.getPlayer().discoverRecipe(keys.recipe);
68 event.getPlayer().discoverRecipe(keys.recipe);
69 event.getPlayer().discoverRecipe(keys.lumbererRecipe);
58 }
70 }
59
71
60 @EventHandler(priority = EventPriority.HIGHEST)
72 @EventHandler(priority = EventPriority.HIGHEST)
@@ -85,8 +97,8 @@ final class FarmerListener implements Listener {
85 }
97 }
86
98
87 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
99 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
88 public void onFarmerStatuePlaced(BlockPlaceEvent event) {
100 public void onWorkerStatuePlaced(BlockPlaceEvent event) {
89 if (!itemCodec.isFarmerItem(event.getItemInHand())) return;
101 if (!itemCodec.isWorkerItem(event.getItemInHand())) return;
90
102
91 Block placed = event.getBlockPlaced();
103 Block placed = event.getBlockPlaced();
92 CopperStatueVariant variant = CopperStatueVariant.from(placed.getType());
104 CopperStatueVariant variant = CopperStatueVariant.from(placed.getType());
@@ -97,6 +109,7 @@ final class FarmerListener implements Listener {
97 FarmerPersistence.capture(placedItem.getPersistentDataContainer(), keys),
109 FarmerPersistence.capture(placedItem.getPersistentDataContainer(), keys),
98 placed.getLocation()
110 placed.getLocation()
99 );
111 );
112 WorkerRole role = snapshot.role();
100
113
101 Location location = placed.getLocation();
114 Location location = placed.getLocation();
102 plugin.getServer().getScheduler().runTask(plugin, () -> {
115 plugin.getServer().getScheduler().runTask(plugin, () -> {
@@ -107,20 +120,21 @@ final class FarmerListener implements Listener {
107 Location spawn = location.clone().add(0.5, 0.0, 0.5);
120 Location spawn = location.clone().add(0.5, 0.0, 0.5);
108 CopperGolem golem = location.getWorld().spawn(spawn, CopperGolem.class, entity -> {
121 CopperGolem golem = location.getWorld().spawn(spawn, CopperGolem.class, entity -> {
109 PersistentDataContainer pdc = entity.getPersistentDataContainer();
122 PersistentDataContainer pdc = entity.getPersistentDataContainer();
110 FarmerPersistence.stampEntity(pdc, keys);
123 FarmerPersistence.stampEntity(pdc, keys, role);
111 snapshot.apply(pdc, keys);
124 snapshot.apply(pdc, keys);
112 variant.applyTo(entity);
125 variant.applyTo(entity);
113 FarmerManager.persistFarmer(entity);
126 FarmerManager.persistWorker(entity, role);
114 });
127 });
115 manager.register(golem);
128 manager.register(golem);
116 });
129 });
117 }
130 }
118
131
119 @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
132 @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
120 public void onFarmerPetrify(EntityChangeBlockEvent event) {
133 public void onWorkerPetrify(EntityChangeBlockEvent event) {
121 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
134 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
122 if (!CopperStatueVariant.isStatue(event.getTo())) return;
135 if (!CopperStatueVariant.isStatue(event.getTo())) return;
123
136
137 WorkerRole role = manager.roleOf(golem);
124 petrifying.add(golem.getUniqueId());
138 petrifying.add(golem.getUniqueId());
125 EntityEquipment equipment = golem.getEquipment();
139 EntityEquipment equipment = golem.getEquipment();
126 if (equipment != null) equipment.setItemInMainHand(null);
140 if (equipment != null) equipment.setItemInMainHand(null);
@@ -139,13 +153,37 @@ final class FarmerListener implements Listener {
139 Location location = event.getBlock().getLocation();
153 Location location = event.getBlock().getLocation();
140 plugin.getServer().getScheduler().runTask(plugin, () -> {
154 plugin.getServer().getScheduler().runTask(plugin, () -> {
141 petrifying.remove(golem.getUniqueId());
155 petrifying.remove(golem.getUniqueId());
142 writeSnapshotToStatue(location.getBlock(), snapshot);
156 writeSnapshotToStatue(location.getBlock(), snapshot, role);
143 });
157 });
144 }
158 }
145
159
146 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
160 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
147 public void onFarmerInteract(PlayerInteractEntityEvent event) {
161 public void onVanillaGolemConvert(PlayerInteractEntityEvent event) {
148 if (!(event.getRightClicked() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
162 if (!(event.getRightClicked() instanceof CopperGolem golem) || manager.isWorker(golem)) return;
163
164 ItemStack used = event.getPlayer().getInventory().getItem(event.getHand());
165 WorkerRole role = roleFromConversionTool(used);
166 if (role == null || isNameTag(used)) return;
167
168 event.setCancelled(true);
169
170 ItemStack tool = used.clone();
171 tool.setAmount(1);
172 if (event.getPlayer().getGameMode() != GameMode.CREATIVE) {
173 used.setAmount(used.getAmount() - 1);
174 }
175
176 PersistentDataContainer pdc = golem.getPersistentDataContainer();
177 FarmerPersistence.stampEntity(pdc, keys, role);
178 itemCodec.storeTool(golem, tool);
179 FarmerManager.persistWorker(golem, role);
180 manager.register(golem);
181 manager.resyncHeldItem(golem, event.getPlayer());
182 }
183
184 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
185 public void onWorkerInteract(PlayerInteractEntityEvent event) {
186 if (!(event.getRightClicked() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
149
187
150 ItemStack used = event.getPlayer().getInventory().getItem(event.getHand());
188 ItemStack used = event.getPlayer().getInventory().getItem(event.getHand());
151 if (isOxidationTool(used) || isNameTag(used)) return;
189 if (isOxidationTool(used) || isNameTag(used)) return;
@@ -155,8 +193,8 @@ final class FarmerListener implements Listener {
155 }
193 }
156
194
157 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
195 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
158 public void onFarmerDropItem(EntityDropItemEvent event) {
196 public void onWorkerDropItem(EntityDropItemEvent event) {
159 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
197 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
160 event.setCancelled(true);
198 event.setCancelled(true);
161 manager.resyncHeldItem(golem);
199 manager.resyncHeldItem(golem);
162 }
200 }
@@ -165,7 +203,7 @@ final class FarmerListener implements Listener {
165 public void onStatueWaxOrScrape(PlayerInteractEvent event) {
203 public void onStatueWaxOrScrape(PlayerInteractEvent event) {
166 if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
204 if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
167 Block block = event.getClickedBlock();
205 Block block = event.getClickedBlock();
168 if (block == null || !FarmerPersistence.isFarmerStatue(block, keys)) return;
206 if (block == null || !FarmerPersistence.isWorkerStatue(block, keys)) return;
169 ItemStack item = event.getItem();
207 ItemStack item = event.getItem();
170 if (!isOxidationTool(item)) return;
208 if (!isOxidationTool(item)) return;
171
209
@@ -177,26 +215,26 @@ final class FarmerListener implements Listener {
177 }
215 }
178
216
179 @EventHandler(ignoreCancelled = true)
217 @EventHandler(ignoreCancelled = true)
180 public void onFarmerStatueDrops(BlockDropItemEvent event) {
218 public void onWorkerStatueDrops(BlockDropItemEvent event) {
181 if (!(event.getBlockState() instanceof CopperGolemStatue statue)) return;
219 if (!(event.getBlockState() instanceof CopperGolemStatue statue)) return;
182 if (!FarmerPersistence.isFarmerEntity(statue.getPersistentDataContainer(), keys)) return;
220 if (!FarmerPersistence.isWorkerEntity(statue.getPersistentDataContainer(), keys)) return;
183
221
184 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys)
222 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys)
185 .withoutCargo();
223 .withoutCargo();
186 ItemStack farmer = itemCodec.createStatue(snapshot, event.getBlockState().getType());
224 ItemStack worker = itemCodec.createStatue(snapshot, event.getBlockState().getType());
187 var drops = event.getItems();
225 var drops = event.getItems();
188 if (drops.isEmpty()) {
226 if (drops.isEmpty()) {
189 event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.5, 0.5), farmer);
227 event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.5, 0.5), worker);
190 return;
228 return;
191 }
229 }
192 drops.getFirst().setItemStack(farmer);
230 drops.getFirst().setItemStack(worker);
193 while (drops.size() > 1) drops.remove(1);
231 while (drops.size() > 1) drops.remove(1);
194 }
232 }
195
233
196 @EventHandler
234 @EventHandler
197 public void onEntitiesLoad(EntitiesLoadEvent event) {
235 public void onEntitiesLoad(EntitiesLoadEvent event) {
198 for (Entity entity : event.getEntities()) {
236 for (Entity entity : event.getEntities()) {
199 if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) {
237 if (entity instanceof CopperGolem golem && manager.isWorker(golem)) {
200 manager.register(golem);
238 manager.register(golem);
201 }
239 }
202 }
240 }
@@ -205,26 +243,26 @@ final class FarmerListener implements Listener {
205 @EventHandler
243 @EventHandler
206 public void onEntitiesUnload(EntitiesUnloadEvent event) {
244 public void onEntitiesUnload(EntitiesUnloadEvent event) {
207 for (Entity entity : event.getEntities()) {
245 for (Entity entity : event.getEntities()) {
208 if (manager.isFarmer(entity)) manager.unregister(entity);
246 if (manager.isWorker(entity)) manager.unregister(entity);
209 }
247 }
210 }
248 }
211
249
212 @EventHandler(priority = EventPriority.MONITOR)
250 @EventHandler(priority = EventPriority.MONITOR)
213 public void onFarmerRemoved(EntityRemoveEvent event) {
251 public void onWorkerRemoved(EntityRemoveEvent event) {
214 if (!manager.isFarmer(event.getEntity())) return;
252 if (!manager.isWorker(event.getEntity())) return;
215 EntityRemoveEvent.Cause cause = event.getCause();
253 EntityRemoveEvent.Cause cause = event.getCause();
216 if (cause == EntityRemoveEvent.Cause.UNLOAD
254 if (cause == EntityRemoveEvent.Cause.UNLOAD
217 || cause == EntityRemoveEvent.Cause.DEATH
255 || cause == EntityRemoveEvent.Cause.DEATH
218 || cause == EntityRemoveEvent.Cause.TRANSFORMATION) {
256 || cause == EntityRemoveEvent.Cause.TRANSFORMATION) {
219 return;
257 return;
220 }
258 }
221 plugin.getLogger().warning("Farmer golem removed (" + cause + ") at "
259 plugin.getLogger().warning("Worker golem removed (" + cause + ") at "
222 + formatLocation(event.getEntity().getLocation()));
260 + formatLocation(event.getEntity().getLocation()));
223 }
261 }
224
262
225 @EventHandler(priority = EventPriority.HIGHEST)
263 @EventHandler(priority = EventPriority.HIGHEST)
226 public void onDeath(EntityDeathEvent event) {
264 public void onDeath(EntityDeathEvent event) {
227 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
265 if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isWorker(golem)) return;
228 if (petrifying.remove(golem.getUniqueId())) {
266 if (petrifying.remove(golem.getUniqueId())) {
229 event.getDrops().clear();
267 event.getDrops().clear();
230 event.setDroppedExp(0);
268 event.setDroppedExp(0);
@@ -233,40 +271,59 @@ final class FarmerListener implements Listener {
233 event.getDrops().addAll(manager.deathDrops(golem));
271 event.getDrops().addAll(manager.deathDrops(golem));
234 }
272 }
235
273
274 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
275 public void onTreeGrow(StructureGrowEvent event) {
276 treeIndex.onStructureGrow(event);
277 }
278
279 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
280 public void onLogBroken(BlockBreakEvent event) {
281 treeIndex.onBlockChanged(event.getBlock());
282 }
283
236 private ItemStack craftResult(Recipe recipe, ItemStack[] contents, ItemStack vanillaResult) {
284 private ItemStack craftResult(Recipe recipe, ItemStack[] contents, ItemStack vanillaResult) {
237 if (isFarmerRecipe(recipe)) return farmerResultFrom(contents);
285 if (isFarmerRecipe(recipe)) {
238 return preserveFarmerOnStatueResult(contents, vanillaResult);
286 if (itemCodec.isLumbererItem(findStatue(contents))) return new ItemStack(Material.AIR);
287 return workerResultFrom(contents, WorkerRole.FARMER, Material.COPPER_HOE);
288 }
289 if (isLumbererRecipe(recipe)) {
290 if (itemCodec.isFarmerItem(findStatue(contents))) return new ItemStack(Material.AIR);
291 return workerResultFrom(contents, WorkerRole.LUMBERER, Material.COPPER_AXE);
292 }
293 return preserveWorkerOnStatueResult(contents, vanillaResult);
239 }
294 }
240
295
241 private ItemStack preserveFarmerOnStatueResult(ItemStack[] contents, ItemStack vanillaResult) {
296 private ItemStack preserveWorkerOnStatueResult(ItemStack[] contents, ItemStack vanillaResult) {
242 if (vanillaResult == null || !CopperStatueVariant.isStatue(vanillaResult.getType())) return null;
297 if (vanillaResult == null || !CopperStatueVariant.isStatue(vanillaResult.getType())) return null;
243 ItemStack farmer = findFarmerStatue(contents);
298 ItemStack worker = findWorkerStatue(contents);
244 if (farmer == null) return null;
299 if (worker == null) return null;
245 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(
300 FarmerPersistence.FarmerSnapshot snapshot = FarmerPersistence.capture(
246 farmer.getPersistentDataContainer(),
301 worker.getPersistentDataContainer(),
247 keys
302 keys
248 );
303 );
249 return itemCodec.createStatue(snapshot, vanillaResult.getType());
304 return itemCodec.createStatue(snapshot, vanillaResult.getType());
250 }
305 }
251
306
252 private ItemStack farmerResultFrom(ItemStack[] contents) {
307 private ItemStack workerResultFrom(ItemStack[] contents, WorkerRole role, Material toolType) {
253 ItemStack hoe = findCopperHoe(contents);
308 ItemStack tool = findTool(contents, toolType);
254 ItemStack statue = findStatue(contents);
309 ItemStack statue = findStatue(contents);
255 if (hoe == null || statue == null) return null;
310 if (tool == null || statue == null) return null;
256 if (!itemCodec.isFarmerItem(statue)) {
311 if (!itemCodec.isWorkerItem(statue)) {
257 return itemCodec.createStatue(hoe, statue.getType());
312 return itemCodec.createStatue(tool, statue.getType(), role);
258 }
313 }
259
314
260 FarmerPersistence.FarmerSnapshot existing = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys);
315 FarmerPersistence.FarmerSnapshot existing = FarmerPersistence.capture(statue.getPersistentDataContainer(), keys);
261 ItemStack withNewHoe = itemCodec.createStatue(hoe, statue.getType());
316 if (existing.role() != role) return null;
262 FarmerPersistence.FarmerSnapshot hoeOnly = FarmerPersistence.capture(withNewHoe.getPersistentDataContainer(), keys);
317 ItemStack withNewTool = itemCodec.createStatue(tool, statue.getType(), role);
318 FarmerPersistence.FarmerSnapshot toolOnly = FarmerPersistence.capture(withNewTool.getPersistentDataContainer(), keys);
263 return itemCodec.createStatue(new FarmerPersistence.FarmerSnapshot(
319 return itemCodec.createStatue(new FarmerPersistence.FarmerSnapshot(
264 hoeOnly.tool(),
320 toolOnly.tool(),
265 existing.cargo(),
321 existing.cargo(),
266 existing.chestWorld(),
322 existing.chestWorld(),
267 existing.chestX(),
323 existing.chestX(),
268 existing.chestY(),
324 existing.chestY(),
269 existing.chestZ()
325 existing.chestZ(),
326 role
270 ), statue.getType());
327 ), statue.getType());
271 }
328 }
272
329
@@ -290,32 +347,39 @@ final class FarmerListener implements Listener {
290 private void restoreAfterVanillaConversion(Location location, FarmerPersistence.FarmerSnapshot snapshot) {
347 private void restoreAfterVanillaConversion(Location location, FarmerPersistence.FarmerSnapshot snapshot) {
291 Block block = location.getBlock();
348 Block block = location.getBlock();
292 if (block.getState() instanceof CopperGolemStatue statue) {
349 if (block.getState() instanceof CopperGolemStatue statue) {
293 writeSnapshotToStatue(block, snapshot);
350 writeSnapshotToStatue(block, snapshot, snapshot.role());
294 return;
351 return;
295 }
352 }
296
353
297 Location center = location.clone().add(0.5, 0.0, 0.5);
354 Location center = location.clone().add(0.5, 0.0, 0.5);
298 for (Entity entity : location.getWorld().getNearbyEntities(center, 0.75, 1.0, 0.75)) {
355 for (Entity entity : location.getWorld().getNearbyEntities(center, 0.75, 1.0, 0.75)) {
299 if (!(entity instanceof CopperGolem golem)) continue;
356 if (!(entity instanceof CopperGolem golem)) continue;
300 if (manager.isFarmer(golem) || FarmerPersistence.isFarmerEntity(golem.getPersistentDataContainer(), keys)) {
357 if (manager.isWorker(golem) || FarmerPersistence.isWorkerEntity(golem.getPersistentDataContainer(), keys)) {
301 continue;
358 continue;
302 }
359 }
303 PersistentDataContainer pdc = golem.getPersistentDataContainer();
360 PersistentDataContainer pdc = golem.getPersistentDataContainer();
304 FarmerPersistence.stampEntity(pdc, keys);
361 FarmerPersistence.stampEntity(pdc, keys, snapshot.role());
305 snapshot.apply(pdc, keys);
362 snapshot.apply(pdc, keys);
306 manager.register(golem);
363 manager.register(golem);
307 return;
364 return;
308 }
365 }
309 }
366 }
310
367
311 private void writeSnapshotToStatue(Block block, FarmerPersistence.FarmerSnapshot snapshot) {
368 private void writeSnapshotToStatue(Block block, FarmerPersistence.FarmerSnapshot snapshot, WorkerRole role) {
312 if (!(block.getState() instanceof CopperGolemStatue statue)) return;
369 if (!(block.getState() instanceof CopperGolemStatue statue)) return;
313 PersistentDataContainer pdc = statue.getPersistentDataContainer();
370 PersistentDataContainer pdc = statue.getPersistentDataContainer();
314 FarmerPersistence.stampEntity(pdc, keys);
371 FarmerPersistence.stampEntity(pdc, keys, role);
315 snapshot.apply(pdc, keys);
372 snapshot.apply(pdc, keys);
316 statue.update();
373 statue.update();
317 }
374 }
318
375
376 private WorkerRole roleFromConversionTool(ItemStack item) {
377 if (item == null || item.isEmpty()) return null;
378 if (item.getType() == Material.COPPER_HOE) return WorkerRole.FARMER;
379 if (item.getType() == Material.COPPER_AXE) return WorkerRole.LUMBERER;
380 return null;
381 }
382
319 private boolean isOxidationTool(ItemStack item) {
383 private boolean isOxidationTool(ItemStack item) {
320 if (item == null || item.isEmpty()) return false;
384 if (item == null || item.isEmpty()) return false;
321 return item.getType() == Material.HONEYCOMB || Tag.ITEMS_AXES.isTagged(item.getType());
385 return item.getType() == Material.HONEYCOMB || Tag.ITEMS_AXES.isTagged(item.getType());
@@ -337,10 +401,14 @@ final class FarmerListener implements Listener {
337 return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.recipe);
401 return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.recipe);
338 }
402 }
339
403
340 private ItemStack findCopperHoe(ItemStack[] contents) {
404 private boolean isLumbererRecipe(Recipe recipe) {
405 return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.lumbererRecipe);
406 }
407
408 private ItemStack findTool(ItemStack[] contents, Material type) {
341 if (contents == null) return null;
409 if (contents == null) return null;
342 for (ItemStack item : contents) {
410 for (ItemStack item : contents) {
343 if (item == null || item.isEmpty() || item.getType() != Material.COPPER_HOE) continue;
411 if (item == null || item.isEmpty() || item.getType() != type) continue;
344 ItemStack copy = item.clone();
412 ItemStack copy = item.clone();
345 copy.setAmount(1);
413 copy.setAmount(1);
346 return copy;
414 return copy;
@@ -348,9 +416,9 @@ final class FarmerListener implements Listener {
348 return null;
416 return null;
349 }
417 }
350
418
351 private ItemStack findFarmerStatue(ItemStack[] contents) {
419 private ItemStack findWorkerStatue(ItemStack[] contents) {
352 ItemStack statue = findStatue(contents);
420 ItemStack statue = findStatue(contents);
353 return itemCodec.isFarmerItem(statue) ? statue : null;
421 return itemCodec.isWorkerItem(statue) ? statue : null;
354 }
422 }
355
423
356 private ItemStack findStatue(ItemStack[] contents) {
424 private ItemStack findStatue(ItemStack[] contents) {
src/main/java/nl/timfalken/copperfarmer/FarmerManager.java +269 −30
@@ -59,6 +59,8 @@ final class FarmerManager {
59 59 private final CropRegistry cropRegistry;
60 60 private final SeedRecipeCache seedRecipes;
61 61 private final FarmerItemCodec itemCodec;
62 private final TreeIndex treeIndex;
63 private final TreeRegistry treeRegistry;
62 64 private final Map<UUID, Brain> brains = new HashMap<>();
63 65
64 66 private final int chestChunkRadius;
@@ -79,12 +81,14 @@ final class FarmerManager {
79 81 private long clock;
80 82
81 83 FarmerManager(Plugin plugin, FarmerKeys keys, CropRegistry cropRegistry, SeedRecipeCache seedRecipes,
82 FarmerItemCodec itemCodec) {
84 FarmerItemCodec itemCodec, TreeIndex treeIndex, TreeRegistry treeRegistry) {
83 85 this.plugin = plugin;
84 86 this.keys = keys;
85 87 this.cropRegistry = cropRegistry;
86 88 this.seedRecipes = seedRecipes;
87 89 this.itemCodec = itemCodec;
90 this.treeIndex = treeIndex;
91 this.treeRegistry = treeRegistry;
88 92 this.chestChunkRadius = Math.max(0, plugin.getConfig().getInt("chest-search-chunk-radius", 3));
89 93 this.cropRadius = Math.max(1, plugin.getConfig().getInt("crop-radius", 25));
90 94 this.scanInterval = Math.max(20, plugin.getConfig().getLong("scan-interval-ticks", 200));
@@ -106,6 +110,7 @@ final class FarmerManager {
106 110
107 111 void tick(long elapsedTicks) {
108 112 clock += elapsedTicks;
113 treeIndex.tick();
109 114 // Snapshot: register/unregister can run mid-tick (chunk entity load/unload).
110 115 for (Brain brain : List.copyOf(brains.values())) {
111 116 if (!brain.golem.isValid() || brain.golem.isDead()) {
@@ -121,7 +126,7 @@ final class FarmerManager {
121 126 }
122 127
123 128 void register(CopperGolem golem) {
124 if (!isFarmer(golem)) return;
129 if (!isWorker(golem)) return;
125 130 configureEntity(golem);
126 131 brains.computeIfAbsent(golem.getUniqueId(), ignored -> new Brain(golem));
127 132 }
@@ -129,6 +134,7 @@ final class FarmerManager {
129 134 void unregister(Entity entity) {
130 135 Brain brain = brains.remove(entity.getUniqueId());
131 136 if (brain != null) {
137 brain.releaseTree();
132 138 brain.closeOpenedLid();
133 139 brain.closeAllDoors();
134 140 brain.clearHarvestCrack();
@@ -140,12 +146,27 @@ final class FarmerManager {
140 146 && entity.getPersistentDataContainer().has(keys.farmerEntity, PersistentDataType.BYTE);
141 147 }
142 148
149 boolean isLumberer(Entity entity) {
150 return entity instanceof CopperGolem
151 && entity.getPersistentDataContainer().has(keys.lumbererEntity, PersistentDataType.BYTE);
152 }
153
154 boolean isWorker(Entity entity) {
155 return isFarmer(entity) || isLumberer(entity);
156 }
157
158 WorkerRole roleOf(Entity entity) {
159 if (isLumberer(entity)) return WorkerRole.LUMBERER;
160 if (isFarmer(entity)) return WorkerRole.FARMER;
161 return null;
162 }
163
143 164 void configureEntity(CopperGolem golem) {
144 165 plugin.getServer().getMobGoals().removeAllGoals(golem);
145 166 CopperGolemVanillaAi.suppress(golem, plugin);
146 167 golem.setAI(true);
147 168 golem.setAware(true);
148 persistFarmer(golem);
169 persistWorker(golem, roleOf(golem));
149 170 golem.setCanPickupItems(false);
150 171 golem.getPathfinder().setCanFloat(true);
151 172 golem.getPathfinder().setCanPassDoors(true);
@@ -154,16 +175,18 @@ final class FarmerManager {
154 175 if (followRange != null) followRange.setBaseValue(pathfindingRange);
155 176 golem.setGolemState(CopperGolem.State.IDLE);
156 177 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
157 persistFarmer(golem);
178 persistWorker(golem, roleOf(golem));
158 179 equipHand(golem, itemCodec.readTool(golem), false);
159 180 }
160 181
161 static void persistFarmer(CopperGolem golem) {
182 static void persistWorker(CopperGolem golem, WorkerRole role) {
162 183 CopperGolemVanillaAi.persist(golem);
163 if (golem.customName() == null) {
164 golem.customName(Component.text("Copper Farmer Golem"));
165 golem.setCustomNameVisible(false);
166 }
184 if (golem.customName() != null) return;
185 String name = role == WorkerRole.LUMBERER
186 ? WorkerRole.LUMBERER.displayName()
187 : WorkerRole.FARMER.displayName();
188 golem.customName(Component.text(name));
189 golem.setCustomNameVisible(false);
167 190 }
168 191
169 192 void resyncHeldItem(CopperGolem golem, Player viewer) {
@@ -171,7 +194,7 @@ final class FarmerManager {
171 194 viewer.sendEquipmentChange(golem, EquipmentSlot.HAND, shown);
172 195 sendHandToViewers(golem, shown);
173 196 plugin.getServer().getScheduler().runTask(plugin, () -> {
174 if (golem.isValid() && isFarmer(golem)) resyncHeldItem(golem);
197 if (golem.isValid() && isWorker(golem)) resyncHeldItem(golem);
175 198 });
176 199 }
177 200
@@ -258,6 +281,11 @@ final class FarmerManager {
258 281 private BlockRef overflowTarget;
259 282 private boolean overflowIsComposter;
260 283 private final Set<BlockRef> triedOverflow = new HashSet<>();
284 private final WorkerRole role;
285 private DetectedTree activeTree;
286 private int chopIndex;
287 private Material saplingType;
288 private final Set<UUID> unreachableTrees = new HashSet<>();
261 289
262 290 Brain(CopperGolem golem) {
263 291 this.golem = golem;
@@ -265,6 +293,8 @@ final class FarmerManager {
265 293 this.tool = itemCodec.readTool(golem);
266 294 this.chest = loadChest(golem);
267 295 this.nextScanTick = clock;
296 WorkerRole detected = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
297 this.role = detected == null ? WorkerRole.FARMER : detected;
268 298 }
269 299
270 300 void tick() {
@@ -276,7 +306,7 @@ final class FarmerManager {
276 306 if (preventOxidation && golem.getOxidizing() != CopperGolem.Oxidizing.waxed()) {
277 307 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
278 308 }
279 persistFarmer(golem);
309 persistWorker(golem, role);
280 310 cleanupCooldowns();
281 311 tickDoors();
282 312
@@ -312,6 +342,11 @@ final class FarmerManager {
312 342
313 343 if (clock < nextScanTick) return;
314 344
345 if (role == WorkerRole.LUMBERER) {
346 tickIdleLumberer();
347 return;
348 }
349
315 350 Block target = findMatureCrop();
316 351 if (target == null) {
317 352 unreachableCrops.clear();
@@ -336,7 +371,178 @@ final class FarmerManager {
336 371 nextScanTick = clock + 20;
337 372 }
338 373
374 private void tickIdleLumberer() {
375 Block chestBlock = block(chest);
376 if (chestBlock == null) {
377 nextScanTick = clock + 20;
378 return;
379 }
380
381 treeIndex.requestAround(chestBlock, cropRadius);
382 DetectedTree tree = treeIndex.findAvailable(chestBlock, cropRadius, golem.getUniqueId(), unreachableTrees);
383 if (tree == null) {
384 if (treeIndex.isScanningAround(chestBlock, cropRadius)) {
385 nextScanTick = clock + 5;
386 return;
387 }
388 unreachableTrees.clear();
389 nextScanTick = clock + scanInterval;
390 return;
391 }
392
393 if (!beginChopTree(tree)) {
394 unreachableTrees.add(tree.id());
395 nextScanTick = clock + 20;
396 }
397 }
398
399 private boolean beginChopTree(DetectedTree tree) {
400 if (!tree.claim(golem.getUniqueId())) return false;
401 activeTree = tree;
402 saplingType = tree.species().sapling();
403 chopIndex = 0;
404 for (BlockRef log : tree.standOrder()) {
405 Block block = FarmerManager.this.block(log);
406 if (block == null || !tree.species().isLog(block.getType())) continue;
407 if (beginPathToBlock(block, State.MOVING_TO_CROP)) {
408 cropTarget = log;
409 return true;
410 }
411 }
412 tree.release(golem.getUniqueId());
413 activeTree = null;
414 saplingType = null;
415 return false;
416 }
417
418 private void tickMovingToTree() {
419 if (activeTree == null) {
420 resetCropTask();
421 return;
422 }
423 Block stand = block(cropTarget);
424 if (stand == null || !activeTree.species().isLog(stand.getType())) {
425 treeIndex.onLogGone(cropTarget);
426 resetCropTask();
427 return;
428 }
429
430 if (reachedNavigationTarget() && near(stand)) {
431 stopNavigation();
432 List<BlockRef> order = activeTree.chopOrder();
433 if (order.isEmpty()) {
434 finishTreeChop();
435 return;
436 }
437 chopIndex = 0;
438 cropTarget = order.getFirst();
439 Block top = block(cropTarget);
440 if (top == null) {
441 treeIndex.onLogGone(cropTarget);
442 resetCropTask();
443 return;
444 }
445 beginHarvest(top);
446 return;
447 }
448
449 if (!navigationHealthy() && !retryPath()) {
450 unreachableTrees.add(activeTree.id());
451 resetCropTask();
452 }
453 }
454
455 private void tickWaitingToChop() {
456 if (activeTree == null) {
457 clearHarvestCrack();
458 resetCropTask();
459 return;
460 }
461 Block logBlock = block(cropTarget);
462 if (logBlock == null || !activeTree.species().isLog(logBlock.getType())) {
463 clearHarvestCrack();
464 treeIndex.onLogGone(cropTarget);
465 resetCropTask();
466 return;
467 }
468
469 lookAt(logBlock);
470 playInteractAnimation();
471 float progress = harvestBreakTicks <= 1
472 ? 1.0f
473 : Math.min(1.0f, (clock - harvestStartTick + 1f) / harvestBreakTicks);
474 sendHarvestCrack(logBlock, progress);
475
476 if (clock < harvestReadyTick) return;
477 clearHarvestCrack();
478 chopLog(logBlock);
479 }
480
481 private void chopLog(Block logBlock) {
482 playHarvestEffects(logBlock);
483 List<ItemStack> calculatedDrops = new ArrayList<>(logBlock.getDrops(tool.clone(), golem));
484 logBlock.setType(Material.AIR, true);
485 List<ItemStack> overflow = cargo.addAll(calculatedDrops);
486 if (!calculatedDrops.isEmpty()) {
487 ItemStack shown = calculatedDrops.getFirst().clone();
488 shown.setAmount(1);
489 carriedProduce = shown;
490 }
491 for (ItemStack item : overflow) {
492 logBlock.getWorld().dropItemNaturally(logBlock.getLocation().add(0.5, 0.5, 0.5), item);
493 }
494
495 chopIndex++;
496 List<BlockRef> order = activeTree.chopOrder();
497 while (chopIndex < order.size()) {
498 BlockRef next = order.get(chopIndex);
499 Block nextBlock = block(next);
500 if (nextBlock != null && activeTree.species().isLog(nextBlock.getType())) {
501 cropTarget = next;
502 beginHarvest(nextBlock);
503 return;
504 }
505 treeIndex.onLogGone(next);
506 resetCropTask();
507 return;
508 }
509 finishTreeChop();
510 }
511
512 private void finishTreeChop() {
513 cropTarget = null;
514 clearHarvestCrack();
515 if (activeTree == null) {
516 beginReturnToChest();
517 return;
518 }
519 ensureSaplings(activeTree);
520 plantQueue.clear();
521 for (BlockRef spot : activeTree.plantSpots()) {
522 Block space = block(spot);
523 if (space != null && treeRegistry.canPlantAt(space, activeTree.species())) {
524 plantQueue.addLast(new PlantJob(spot, saplingType.createBlockData()));
525 }
526 }
527 if (plantQueue.isEmpty()) {
528 beginReturnToChest();
529 return;
530 }
531 advancePlantQueue();
532 }
533
534 private void ensureSaplings(DetectedTree tree) {
535 int needed = tree.plantSpots().size();
536 int have = cargo.count(tree.species().sapling());
537 if (have >= needed) return;
538 cargo.add(new ItemStack(tree.species().sapling(), needed - have));
539 }
540
339 541 private void tickMovingToCrop() {
542 if (role == WorkerRole.LUMBERER) {
543 tickMovingToTree();
544 return;
545 }
340 546 Block cropBlock = block(cropTarget);
341 547 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
342 548 || !cropRegistry.isReady(cropBlock)) {
@@ -371,6 +577,10 @@ final class FarmerManager {
371 577 }
372 578
373 579 private void tickWaitingToHarvest() {
580 if (role == WorkerRole.LUMBERER) {
581 tickWaitingToChop();
582 return;
583 }
374 584 Block cropBlock = block(cropTarget);
375 585 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
376 586 || !cropRegistry.isReady(cropBlock)) {
@@ -392,7 +602,7 @@ final class FarmerManager {
392 602 }
393 603
394 604 private void tickMovingToPlant() {
395 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
605 if (!canContinuePlanting()) {
396 606 plantQueue.clear();
397 607 beginReturnToChest();
398 608 return;
@@ -418,7 +628,7 @@ final class FarmerManager {
418 628 }
419 629
420 630 private void tickWaitingToPlant() {
421 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
631 if (!canContinuePlanting()) {
422 632 plantQueue.clear();
423 633 beginReturnToChest();
424 634 return;
@@ -436,11 +646,17 @@ final class FarmerManager {
436 646 playInteractAnimation();
437 647 if (clock < plantReadyTick) return;
438 648
439 if (cargo.remove(activeCrop.seed(), 1)) {
440 playInteractAnimation();
441 target.setBlockData(job.data(), false);
442 playPlantSound(target);
649 Material seed = plantingItem();
650 if (role == WorkerRole.LUMBERER) {
651 if (seed != null) cargo.remove(seed, 1);
652 } else if (seed == null || !cargo.remove(seed, 1)) {
653 plantQueue.pollFirst();
654 advancePlantQueue();
655 return;
443 656 }
657 playInteractAnimation();
658 target.setBlockData(job.data(), false);
659 playPlantSound(target);
444 660 plantQueue.pollFirst();
445 661 advancePlantQueue();
446 662 }
@@ -644,7 +860,7 @@ final class FarmerManager {
644 860
645 861 private void advancePlantQueue() {
646 862 while (!plantQueue.isEmpty()) {
647 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
863 if (!canContinuePlanting()) {
648 864 plantQueue.clear();
649 865 break;
650 866 }
@@ -675,12 +891,25 @@ final class FarmerManager {
675 891
676 892 private boolean jobStillValid(PlantJob job) {
677 893 Block space = block(job.space());
678 if (space == null || activeCrop == null) return false;
679 if (!space.getType().isAir()) return false;
894 if (space == null || !space.getType().isAir()) return false;
895 if (role == WorkerRole.LUMBERER) {
896 return activeTree != null && treeRegistry.canPlantAt(space, activeTree.species());
897 }
898 if (activeCrop == null) return false;
680 899 if (activeCrop.support() == CropRegistry.PlantSupport.NONE) return true;
681 900 return cropRegistry.canPlantAt(space, activeCrop);
682 901 }
683 902
903 private Material plantingItem() {
904 if (role == WorkerRole.LUMBERER) return saplingType;
905 return activeCrop == null ? null : activeCrop.seed();
906 }
907
908 private boolean canContinuePlanting() {
909 if (role == WorkerRole.LUMBERER) return saplingType != null;
910 return activeCrop != null && cargo.count(activeCrop.seed()) > 0;
911 }
912
684 913 private void beginReturnToChest() {
685 914 plantQueue.clear();
686 915 activeCrop = null;
@@ -688,6 +917,7 @@ final class FarmerManager {
688 917 overflowTarget = null;
689 918 overflowIsComposter = false;
690 919 triedOverflow.clear();
920 releaseTree();
691 921
692 922 if (cargo.isEmpty()) {
693 923 state = State.IDLE;
@@ -775,7 +1005,7 @@ final class FarmerManager {
775 1005 nextScanTick = clock + afterDepositScanTicks;
776 1006 return;
777 1007 }
778 if (beginPathToOverflowChest() || beginPathToComposter()) return;
1008 if (beginPathToOverflowChest() || (role != WorkerRole.LUMBERER && beginPathToComposter())) return;
779 1009
780 1010 overflowTarget = null;
781 1011 overflowIsComposter = false;
@@ -1251,9 +1481,14 @@ final class FarmerManager {
1251 1481
1252 1482 private void playPlantSound(Block planted) {
1253 1483 Location loc = planted.getLocation().add(0.5, 0.5, 0.5);
1254 Sound sound = planted.getType() == Material.NETHER_WART
1255 ? Sound.ITEM_NETHER_WART_PLANT
1256 : Sound.ITEM_CROP_PLANT;
1484 Sound sound;
1485 if (role == WorkerRole.LUMBERER) {
1486 sound = planted.getBlockSoundGroup().getPlaceSound();
1487 } else if (planted.getType() == Material.NETHER_WART) {
1488 sound = Sound.ITEM_NETHER_WART_PLANT;
1489 } else {
1490 sound = Sound.ITEM_CROP_PLANT;
1491 }
1257 1492 planted.getWorld().playSound(loc, sound, SoundCategory.BLOCKS, 1.0f, 0.9f);
1258 1493 }
1259 1494
@@ -1335,10 +1570,20 @@ final class FarmerManager {
1335 1570 cropTarget = null;
1336 1571 activeCrop = null;
1337 1572 plantQueue.clear();
1573 releaseTree();
1338 1574 state = State.IDLE;
1339 1575 nextScanTick = clock;
1340 1576 }
1341 1577
1578 private void releaseTree() {
1579 if (activeTree != null) {
1580 activeTree.release(golem.getUniqueId());
1581 activeTree = null;
1582 }
1583 saplingType = null;
1584 chopIndex = 0;
1585 }
1586
1342 1587 private void stopNavigation() {
1343 1588 golem.getPathfinder().stopPathfinding();
1344 1589 navigationTarget = null;
@@ -1490,12 +1735,6 @@ final class FarmerManager {
1490 1735 WAITING_FOR_CHEST_SPACE
1491 1736 }
1492 1737
1493 private record BlockRef(UUID worldId, int x, int y, int z) {
1494 static BlockRef of(Block block) {
1495 return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
1496 }
1497 }
1498
1499 1738 private Block block(BlockRef ref) {
1500 1739 if (ref == null) return null;
1501 1740 World world = Bukkit.getWorld(ref.worldId());
@@ -59,6 +59,8 @@ final class FarmerManager {
59 private final CropRegistry cropRegistry;
59 private final CropRegistry cropRegistry;
60 private final SeedRecipeCache seedRecipes;
60 private final SeedRecipeCache seedRecipes;
61 private final FarmerItemCodec itemCodec;
61 private final FarmerItemCodec itemCodec;
62 private final TreeIndex treeIndex;
63 private final TreeRegistry treeRegistry;
62 private final Map<UUID, Brain> brains = new HashMap<>();
64 private final Map<UUID, Brain> brains = new HashMap<>();
63
65
64 private final int chestChunkRadius;
66 private final int chestChunkRadius;
@@ -79,12 +81,14 @@ final class FarmerManager {
79 private long clock;
81 private long clock;
80
82
81 FarmerManager(Plugin plugin, FarmerKeys keys, CropRegistry cropRegistry, SeedRecipeCache seedRecipes,
83 FarmerManager(Plugin plugin, FarmerKeys keys, CropRegistry cropRegistry, SeedRecipeCache seedRecipes,
82 FarmerItemCodec itemCodec) {
84 FarmerItemCodec itemCodec, TreeIndex treeIndex, TreeRegistry treeRegistry) {
83 this.plugin = plugin;
85 this.plugin = plugin;
84 this.keys = keys;
86 this.keys = keys;
85 this.cropRegistry = cropRegistry;
87 this.cropRegistry = cropRegistry;
86 this.seedRecipes = seedRecipes;
88 this.seedRecipes = seedRecipes;
87 this.itemCodec = itemCodec;
89 this.itemCodec = itemCodec;
90 this.treeIndex = treeIndex;
91 this.treeRegistry = treeRegistry;
88 this.chestChunkRadius = Math.max(0, plugin.getConfig().getInt("chest-search-chunk-radius", 3));
92 this.chestChunkRadius = Math.max(0, plugin.getConfig().getInt("chest-search-chunk-radius", 3));
89 this.cropRadius = Math.max(1, plugin.getConfig().getInt("crop-radius", 25));
93 this.cropRadius = Math.max(1, plugin.getConfig().getInt("crop-radius", 25));
90 this.scanInterval = Math.max(20, plugin.getConfig().getLong("scan-interval-ticks", 200));
94 this.scanInterval = Math.max(20, plugin.getConfig().getLong("scan-interval-ticks", 200));
@@ -106,6 +110,7 @@ final class FarmerManager {
106
110
107 void tick(long elapsedTicks) {
111 void tick(long elapsedTicks) {
108 clock += elapsedTicks;
112 clock += elapsedTicks;
113 treeIndex.tick();
109 // Snapshot: register/unregister can run mid-tick (chunk entity load/unload).
114 // Snapshot: register/unregister can run mid-tick (chunk entity load/unload).
110 for (Brain brain : List.copyOf(brains.values())) {
115 for (Brain brain : List.copyOf(brains.values())) {
111 if (!brain.golem.isValid() || brain.golem.isDead()) {
116 if (!brain.golem.isValid() || brain.golem.isDead()) {
@@ -121,7 +126,7 @@ final class FarmerManager {
121 }
126 }
122
127
123 void register(CopperGolem golem) {
128 void register(CopperGolem golem) {
124 if (!isFarmer(golem)) return;
129 if (!isWorker(golem)) return;
125 configureEntity(golem);
130 configureEntity(golem);
126 brains.computeIfAbsent(golem.getUniqueId(), ignored -> new Brain(golem));
131 brains.computeIfAbsent(golem.getUniqueId(), ignored -> new Brain(golem));
127 }
132 }
@@ -129,6 +134,7 @@ final class FarmerManager {
129 void unregister(Entity entity) {
134 void unregister(Entity entity) {
130 Brain brain = brains.remove(entity.getUniqueId());
135 Brain brain = brains.remove(entity.getUniqueId());
131 if (brain != null) {
136 if (brain != null) {
137 brain.releaseTree();
132 brain.closeOpenedLid();
138 brain.closeOpenedLid();
133 brain.closeAllDoors();
139 brain.closeAllDoors();
134 brain.clearHarvestCrack();
140 brain.clearHarvestCrack();
@@ -140,12 +146,27 @@ final class FarmerManager {
140 && entity.getPersistentDataContainer().has(keys.farmerEntity, PersistentDataType.BYTE);
146 && entity.getPersistentDataContainer().has(keys.farmerEntity, PersistentDataType.BYTE);
141 }
147 }
142
148
149 boolean isLumberer(Entity entity) {
150 return entity instanceof CopperGolem
151 && entity.getPersistentDataContainer().has(keys.lumbererEntity, PersistentDataType.BYTE);
152 }
153
154 boolean isWorker(Entity entity) {
155 return isFarmer(entity) || isLumberer(entity);
156 }
157
158 WorkerRole roleOf(Entity entity) {
159 if (isLumberer(entity)) return WorkerRole.LUMBERER;
160 if (isFarmer(entity)) return WorkerRole.FARMER;
161 return null;
162 }
163
143 void configureEntity(CopperGolem golem) {
164 void configureEntity(CopperGolem golem) {
144 plugin.getServer().getMobGoals().removeAllGoals(golem);
165 plugin.getServer().getMobGoals().removeAllGoals(golem);
145 CopperGolemVanillaAi.suppress(golem, plugin);
166 CopperGolemVanillaAi.suppress(golem, plugin);
146 golem.setAI(true);
167 golem.setAI(true);
147 golem.setAware(true);
168 golem.setAware(true);
148 persistFarmer(golem);
169 persistWorker(golem, roleOf(golem));
149 golem.setCanPickupItems(false);
170 golem.setCanPickupItems(false);
150 golem.getPathfinder().setCanFloat(true);
171 golem.getPathfinder().setCanFloat(true);
151 golem.getPathfinder().setCanPassDoors(true);
172 golem.getPathfinder().setCanPassDoors(true);
@@ -154,16 +175,18 @@ final class FarmerManager {
154 if (followRange != null) followRange.setBaseValue(pathfindingRange);
175 if (followRange != null) followRange.setBaseValue(pathfindingRange);
155 golem.setGolemState(CopperGolem.State.IDLE);
176 golem.setGolemState(CopperGolem.State.IDLE);
156 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
177 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
157 persistFarmer(golem);
178 persistWorker(golem, roleOf(golem));
158 equipHand(golem, itemCodec.readTool(golem), false);
179 equipHand(golem, itemCodec.readTool(golem), false);
159 }
180 }
160
181
161 static void persistFarmer(CopperGolem golem) {
182 static void persistWorker(CopperGolem golem, WorkerRole role) {
162 CopperGolemVanillaAi.persist(golem);
183 CopperGolemVanillaAi.persist(golem);
163 if (golem.customName() == null) {
184 if (golem.customName() != null) return;
164 golem.customName(Component.text("Copper Farmer Golem"));
185 String name = role == WorkerRole.LUMBERER
165 golem.setCustomNameVisible(false);
186 ? WorkerRole.LUMBERER.displayName()
166 }
187 : WorkerRole.FARMER.displayName();
188 golem.customName(Component.text(name));
189 golem.setCustomNameVisible(false);
167 }
190 }
168
191
169 void resyncHeldItem(CopperGolem golem, Player viewer) {
192 void resyncHeldItem(CopperGolem golem, Player viewer) {
@@ -171,7 +194,7 @@ final class FarmerManager {
171 viewer.sendEquipmentChange(golem, EquipmentSlot.HAND, shown);
194 viewer.sendEquipmentChange(golem, EquipmentSlot.HAND, shown);
172 sendHandToViewers(golem, shown);
195 sendHandToViewers(golem, shown);
173 plugin.getServer().getScheduler().runTask(plugin, () -> {
196 plugin.getServer().getScheduler().runTask(plugin, () -> {
174 if (golem.isValid() && isFarmer(golem)) resyncHeldItem(golem);
197 if (golem.isValid() && isWorker(golem)) resyncHeldItem(golem);
175 });
198 });
176 }
199 }
177
200
@@ -258,6 +281,11 @@ final class FarmerManager {
258 private BlockRef overflowTarget;
281 private BlockRef overflowTarget;
259 private boolean overflowIsComposter;
282 private boolean overflowIsComposter;
260 private final Set<BlockRef> triedOverflow = new HashSet<>();
283 private final Set<BlockRef> triedOverflow = new HashSet<>();
284 private final WorkerRole role;
285 private DetectedTree activeTree;
286 private int chopIndex;
287 private Material saplingType;
288 private final Set<UUID> unreachableTrees = new HashSet<>();
261
289
262 Brain(CopperGolem golem) {
290 Brain(CopperGolem golem) {
263 this.golem = golem;
291 this.golem = golem;
@@ -265,6 +293,8 @@ final class FarmerManager {
265 this.tool = itemCodec.readTool(golem);
293 this.tool = itemCodec.readTool(golem);
266 this.chest = loadChest(golem);
294 this.chest = loadChest(golem);
267 this.nextScanTick = clock;
295 this.nextScanTick = clock;
296 WorkerRole detected = FarmerPersistence.roleOf(golem.getPersistentDataContainer(), keys);
297 this.role = detected == null ? WorkerRole.FARMER : detected;
268 }
298 }
269
299
270 void tick() {
300 void tick() {
@@ -276,7 +306,7 @@ final class FarmerManager {
276 if (preventOxidation && golem.getOxidizing() != CopperGolem.Oxidizing.waxed()) {
306 if (preventOxidation && golem.getOxidizing() != CopperGolem.Oxidizing.waxed()) {
277 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
307 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
278 }
308 }
279 persistFarmer(golem);
309 persistWorker(golem, role);
280 cleanupCooldowns();
310 cleanupCooldowns();
281 tickDoors();
311 tickDoors();
282
312
@@ -312,6 +342,11 @@ final class FarmerManager {
312
342
313 if (clock < nextScanTick) return;
343 if (clock < nextScanTick) return;
314
344
345 if (role == WorkerRole.LUMBERER) {
346 tickIdleLumberer();
347 return;
348 }
349
315 Block target = findMatureCrop();
350 Block target = findMatureCrop();
316 if (target == null) {
351 if (target == null) {
317 unreachableCrops.clear();
352 unreachableCrops.clear();
@@ -336,7 +371,178 @@ final class FarmerManager {
336 nextScanTick = clock + 20;
371 nextScanTick = clock + 20;
337 }
372 }
338
373
374 private void tickIdleLumberer() {
375 Block chestBlock = block(chest);
376 if (chestBlock == null) {
377 nextScanTick = clock + 20;
378 return;
379 }
380
381 treeIndex.requestAround(chestBlock, cropRadius);
382 DetectedTree tree = treeIndex.findAvailable(chestBlock, cropRadius, golem.getUniqueId(), unreachableTrees);
383 if (tree == null) {
384 if (treeIndex.isScanningAround(chestBlock, cropRadius)) {
385 nextScanTick = clock + 5;
386 return;
387 }
388 unreachableTrees.clear();
389 nextScanTick = clock + scanInterval;
390 return;
391 }
392
393 if (!beginChopTree(tree)) {
394 unreachableTrees.add(tree.id());
395 nextScanTick = clock + 20;
396 }
397 }
398
399 private boolean beginChopTree(DetectedTree tree) {
400 if (!tree.claim(golem.getUniqueId())) return false;
401 activeTree = tree;
402 saplingType = tree.species().sapling();
403 chopIndex = 0;
404 for (BlockRef log : tree.standOrder()) {
405 Block block = FarmerManager.this.block(log);
406 if (block == null || !tree.species().isLog(block.getType())) continue;
407 if (beginPathToBlock(block, State.MOVING_TO_CROP)) {
408 cropTarget = log;
409 return true;
410 }
411 }
412 tree.release(golem.getUniqueId());
413 activeTree = null;
414 saplingType = null;
415 return false;
416 }
417
418 private void tickMovingToTree() {
419 if (activeTree == null) {
420 resetCropTask();
421 return;
422 }
423 Block stand = block(cropTarget);
424 if (stand == null || !activeTree.species().isLog(stand.getType())) {
425 treeIndex.onLogGone(cropTarget);
426 resetCropTask();
427 return;
428 }
429
430 if (reachedNavigationTarget() && near(stand)) {
431 stopNavigation();
432 List<BlockRef> order = activeTree.chopOrder();
433 if (order.isEmpty()) {
434 finishTreeChop();
435 return;
436 }
437 chopIndex = 0;
438 cropTarget = order.getFirst();
439 Block top = block(cropTarget);
440 if (top == null) {
441 treeIndex.onLogGone(cropTarget);
442 resetCropTask();
443 return;
444 }
445 beginHarvest(top);
446 return;
447 }
448
449 if (!navigationHealthy() && !retryPath()) {
450 unreachableTrees.add(activeTree.id());
451 resetCropTask();
452 }
453 }
454
455 private void tickWaitingToChop() {
456 if (activeTree == null) {
457 clearHarvestCrack();
458 resetCropTask();
459 return;
460 }
461 Block logBlock = block(cropTarget);
462 if (logBlock == null || !activeTree.species().isLog(logBlock.getType())) {
463 clearHarvestCrack();
464 treeIndex.onLogGone(cropTarget);
465 resetCropTask();
466 return;
467 }
468
469 lookAt(logBlock);
470 playInteractAnimation();
471 float progress = harvestBreakTicks <= 1
472 ? 1.0f
473 : Math.min(1.0f, (clock - harvestStartTick + 1f) / harvestBreakTicks);
474 sendHarvestCrack(logBlock, progress);
475
476 if (clock < harvestReadyTick) return;
477 clearHarvestCrack();
478 chopLog(logBlock);
479 }
480
481 private void chopLog(Block logBlock) {
482 playHarvestEffects(logBlock);
483 List<ItemStack> calculatedDrops = new ArrayList<>(logBlock.getDrops(tool.clone(), golem));
484 logBlock.setType(Material.AIR, true);
485 List<ItemStack> overflow = cargo.addAll(calculatedDrops);
486 if (!calculatedDrops.isEmpty()) {
487 ItemStack shown = calculatedDrops.getFirst().clone();
488 shown.setAmount(1);
489 carriedProduce = shown;
490 }
491 for (ItemStack item : overflow) {
492 logBlock.getWorld().dropItemNaturally(logBlock.getLocation().add(0.5, 0.5, 0.5), item);
493 }
494
495 chopIndex++;
496 List<BlockRef> order = activeTree.chopOrder();
497 while (chopIndex < order.size()) {
498 BlockRef next = order.get(chopIndex);
499 Block nextBlock = block(next);
500 if (nextBlock != null && activeTree.species().isLog(nextBlock.getType())) {
501 cropTarget = next;
502 beginHarvest(nextBlock);
503 return;
504 }
505 treeIndex.onLogGone(next);
506 resetCropTask();
507 return;
508 }
509 finishTreeChop();
510 }
511
512 private void finishTreeChop() {
513 cropTarget = null;
514 clearHarvestCrack();
515 if (activeTree == null) {
516 beginReturnToChest();
517 return;
518 }
519 ensureSaplings(activeTree);
520 plantQueue.clear();
521 for (BlockRef spot : activeTree.plantSpots()) {
522 Block space = block(spot);
523 if (space != null && treeRegistry.canPlantAt(space, activeTree.species())) {
524 plantQueue.addLast(new PlantJob(spot, saplingType.createBlockData()));
525 }
526 }
527 if (plantQueue.isEmpty()) {
528 beginReturnToChest();
529 return;
530 }
531 advancePlantQueue();
532 }
533
534 private void ensureSaplings(DetectedTree tree) {
535 int needed = tree.plantSpots().size();
536 int have = cargo.count(tree.species().sapling());
537 if (have >= needed) return;
538 cargo.add(new ItemStack(tree.species().sapling(), needed - have));
539 }
540
339 private void tickMovingToCrop() {
541 private void tickMovingToCrop() {
542 if (role == WorkerRole.LUMBERER) {
543 tickMovingToTree();
544 return;
545 }
340 Block cropBlock = block(cropTarget);
546 Block cropBlock = block(cropTarget);
341 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
547 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
342 || !cropRegistry.isReady(cropBlock)) {
548 || !cropRegistry.isReady(cropBlock)) {
@@ -371,6 +577,10 @@ final class FarmerManager {
371 }
577 }
372
578
373 private void tickWaitingToHarvest() {
579 private void tickWaitingToHarvest() {
580 if (role == WorkerRole.LUMBERER) {
581 tickWaitingToChop();
582 return;
583 }
374 Block cropBlock = block(cropTarget);
584 Block cropBlock = block(cropTarget);
375 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
585 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
376 || !cropRegistry.isReady(cropBlock)) {
586 || !cropRegistry.isReady(cropBlock)) {
@@ -392,7 +602,7 @@ final class FarmerManager {
392 }
602 }
393
603
394 private void tickMovingToPlant() {
604 private void tickMovingToPlant() {
395 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
605 if (!canContinuePlanting()) {
396 plantQueue.clear();
606 plantQueue.clear();
397 beginReturnToChest();
607 beginReturnToChest();
398 return;
608 return;
@@ -418,7 +628,7 @@ final class FarmerManager {
418 }
628 }
419
629
420 private void tickWaitingToPlant() {
630 private void tickWaitingToPlant() {
421 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
631 if (!canContinuePlanting()) {
422 plantQueue.clear();
632 plantQueue.clear();
423 beginReturnToChest();
633 beginReturnToChest();
424 return;
634 return;
@@ -436,11 +646,17 @@ final class FarmerManager {
436 playInteractAnimation();
646 playInteractAnimation();
437 if (clock < plantReadyTick) return;
647 if (clock < plantReadyTick) return;
438
648
439 if (cargo.remove(activeCrop.seed(), 1)) {
649 Material seed = plantingItem();
440 playInteractAnimation();
650 if (role == WorkerRole.LUMBERER) {
441 target.setBlockData(job.data(), false);
651 if (seed != null) cargo.remove(seed, 1);
442 playPlantSound(target);
652 } else if (seed == null || !cargo.remove(seed, 1)) {
653 plantQueue.pollFirst();
654 advancePlantQueue();
655 return;
443 }
656 }
657 playInteractAnimation();
658 target.setBlockData(job.data(), false);
659 playPlantSound(target);
444 plantQueue.pollFirst();
660 plantQueue.pollFirst();
445 advancePlantQueue();
661 advancePlantQueue();
446 }
662 }
@@ -644,7 +860,7 @@ final class FarmerManager {
644
860
645 private void advancePlantQueue() {
861 private void advancePlantQueue() {
646 while (!plantQueue.isEmpty()) {
862 while (!plantQueue.isEmpty()) {
647 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
863 if (!canContinuePlanting()) {
648 plantQueue.clear();
864 plantQueue.clear();
649 break;
865 break;
650 }
866 }
@@ -675,12 +891,25 @@ final class FarmerManager {
675
891
676 private boolean jobStillValid(PlantJob job) {
892 private boolean jobStillValid(PlantJob job) {
677 Block space = block(job.space());
893 Block space = block(job.space());
678 if (space == null || activeCrop == null) return false;
894 if (space == null || !space.getType().isAir()) return false;
679 if (!space.getType().isAir()) return false;
895 if (role == WorkerRole.LUMBERER) {
896 return activeTree != null && treeRegistry.canPlantAt(space, activeTree.species());
897 }
898 if (activeCrop == null) return false;
680 if (activeCrop.support() == CropRegistry.PlantSupport.NONE) return true;
899 if (activeCrop.support() == CropRegistry.PlantSupport.NONE) return true;
681 return cropRegistry.canPlantAt(space, activeCrop);
900 return cropRegistry.canPlantAt(space, activeCrop);
682 }
901 }
683
902
903 private Material plantingItem() {
904 if (role == WorkerRole.LUMBERER) return saplingType;
905 return activeCrop == null ? null : activeCrop.seed();
906 }
907
908 private boolean canContinuePlanting() {
909 if (role == WorkerRole.LUMBERER) return saplingType != null;
910 return activeCrop != null && cargo.count(activeCrop.seed()) > 0;
911 }
912
684 private void beginReturnToChest() {
913 private void beginReturnToChest() {
685 plantQueue.clear();
914 plantQueue.clear();
686 activeCrop = null;
915 activeCrop = null;
@@ -688,6 +917,7 @@ final class FarmerManager {
688 overflowTarget = null;
917 overflowTarget = null;
689 overflowIsComposter = false;
918 overflowIsComposter = false;
690 triedOverflow.clear();
919 triedOverflow.clear();
920 releaseTree();
691
921
692 if (cargo.isEmpty()) {
922 if (cargo.isEmpty()) {
693 state = State.IDLE;
923 state = State.IDLE;
@@ -775,7 +1005,7 @@ final class FarmerManager {
775 nextScanTick = clock + afterDepositScanTicks;
1005 nextScanTick = clock + afterDepositScanTicks;
776 return;
1006 return;
777 }
1007 }
778 if (beginPathToOverflowChest() || beginPathToComposter()) return;
1008 if (beginPathToOverflowChest() || (role != WorkerRole.LUMBERER && beginPathToComposter())) return;
779
1009
780 overflowTarget = null;
1010 overflowTarget = null;
781 overflowIsComposter = false;
1011 overflowIsComposter = false;
@@ -1251,9 +1481,14 @@ final class FarmerManager {
1251
1481
1252 private void playPlantSound(Block planted) {
1482 private void playPlantSound(Block planted) {
1253 Location loc = planted.getLocation().add(0.5, 0.5, 0.5);
1483 Location loc = planted.getLocation().add(0.5, 0.5, 0.5);
1254 Sound sound = planted.getType() == Material.NETHER_WART
1484 Sound sound;
1255 ? Sound.ITEM_NETHER_WART_PLANT
1485 if (role == WorkerRole.LUMBERER) {
1256 : Sound.ITEM_CROP_PLANT;
1486 sound = planted.getBlockSoundGroup().getPlaceSound();
1487 } else if (planted.getType() == Material.NETHER_WART) {
1488 sound = Sound.ITEM_NETHER_WART_PLANT;
1489 } else {
1490 sound = Sound.ITEM_CROP_PLANT;
1491 }
1257 planted.getWorld().playSound(loc, sound, SoundCategory.BLOCKS, 1.0f, 0.9f);
1492 planted.getWorld().playSound(loc, sound, SoundCategory.BLOCKS, 1.0f, 0.9f);
1258 }
1493 }
1259
1494
@@ -1335,10 +1570,20 @@ final class FarmerManager {
1335 cropTarget = null;
1570 cropTarget = null;
1336 activeCrop = null;
1571 activeCrop = null;
1337 plantQueue.clear();
1572 plantQueue.clear();
1573 releaseTree();
1338 state = State.IDLE;
1574 state = State.IDLE;
1339 nextScanTick = clock;
1575 nextScanTick = clock;
1340 }
1576 }
1341
1577
1578 private void releaseTree() {
1579 if (activeTree != null) {
1580 activeTree.release(golem.getUniqueId());
1581 activeTree = null;
1582 }
1583 saplingType = null;
1584 chopIndex = 0;
1585 }
1586
1342 private void stopNavigation() {
1587 private void stopNavigation() {
1343 golem.getPathfinder().stopPathfinding();
1588 golem.getPathfinder().stopPathfinding();
1344 navigationTarget = null;
1589 navigationTarget = null;
@@ -1490,12 +1735,6 @@ final class FarmerManager {
1490 WAITING_FOR_CHEST_SPACE
1735 WAITING_FOR_CHEST_SPACE
1491 }
1736 }
1492
1737
1493 private record BlockRef(UUID worldId, int x, int y, int z) {
1494 static BlockRef of(Block block) {
1495 return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
1496 }
1497 }
1498
1499 private Block block(BlockRef ref) {
1738 private Block block(BlockRef ref) {
1500 if (ref == null) return null;
1739 if (ref == null) return null;
1501 World world = Bukkit.getWorld(ref.worldId());
1740 World world = Bukkit.getWorld(ref.worldId());
src/main/java/nl/timfalken/copperfarmer/FarmerPersistence.java +57 −9
@@ -17,30 +17,77 @@ final class FarmerPersistence {
17 17 return pdc.has(keys.farmerEntity, PersistentDataType.BYTE);
18 18 }
19 19
20 static boolean isFarmerStatue(Block block, FarmerKeys keys) {
20 static boolean isLumbererItem(PersistentDataContainerView pdc, FarmerKeys keys) {
21 return pdc.has(keys.lumbererItem, PersistentDataType.BYTE);
22 }
23
24 static boolean isLumbererEntity(PersistentDataContainerView pdc, FarmerKeys keys) {
25 return pdc.has(keys.lumbererEntity, PersistentDataType.BYTE);
26 }
27
28 static boolean isWorkerItem(PersistentDataContainerView pdc, FarmerKeys keys) {
29 return isFarmerItem(pdc, keys) || isLumbererItem(pdc, keys);
30 }
31
32 static boolean isWorkerEntity(PersistentDataContainerView pdc, FarmerKeys keys) {
33 return isFarmerEntity(pdc, keys) || isLumbererEntity(pdc, keys);
34 }
35
36 static boolean isWorkerStatue(Block block, FarmerKeys keys) {
21 37 return block.getState() instanceof CopperGolemStatue statue
22 && isFarmerEntity(statue.getPersistentDataContainer(), keys);
38 && isWorkerEntity(statue.getPersistentDataContainer(), keys);
39 }
40
41 static WorkerRole roleOf(PersistentDataContainerView pdc, FarmerKeys keys) {
42 if (isLumbererItem(pdc, keys) || isLumbererEntity(pdc, keys)) return WorkerRole.LUMBERER;
43 if (isFarmerItem(pdc, keys) || isFarmerEntity(pdc, keys)) return WorkerRole.FARMER;
44 return null;
23 45 }
24 46
25 47 static FarmerSnapshot capture(PersistentDataContainerView pdc, FarmerKeys keys) {
48 WorkerRole role = roleOf(pdc, keys);
26 49 return new FarmerSnapshot(
27 50 pdc.get(keys.tool, PersistentDataType.BYTE_ARRAY),
28 51 pdc.get(keys.cargo, PersistentDataType.BYTE_ARRAY),
29 52 pdc.get(keys.chestWorld, PersistentDataType.STRING),
30 53 pdc.get(keys.chestX, PersistentDataType.INTEGER),
31 54 pdc.get(keys.chestY, PersistentDataType.INTEGER),
32 pdc.get(keys.chestZ, PersistentDataType.INTEGER)
55 pdc.get(keys.chestZ, PersistentDataType.INTEGER),
56 role == null ? WorkerRole.FARMER : role
33 57 );
34 58 }
35 59
60 static void stampItem(PersistentDataContainer pdc, FarmerKeys keys, WorkerRole role) {
61 clearRole(pdc, keys);
62 if (role == WorkerRole.LUMBERER) {
63 pdc.set(keys.lumbererItem, PersistentDataType.BYTE, (byte) 1);
64 } else {
65 pdc.set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);
66 }
67 }
68
69 static void stampEntity(PersistentDataContainer pdc, FarmerKeys keys, WorkerRole role) {
70 clearRole(pdc, keys);
71 if (role == WorkerRole.LUMBERER) {
72 pdc.set(keys.lumbererEntity, PersistentDataType.BYTE, (byte) 1);
73 } else {
74 pdc.set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);
75 }
76 }
77
36 78 static void stampItem(PersistentDataContainer pdc, FarmerKeys keys) {
37 pdc.set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);
38 pdc.remove(keys.farmerEntity);
79 stampItem(pdc, keys, WorkerRole.FARMER);
39 80 }
40 81
41 82 static void stampEntity(PersistentDataContainer pdc, FarmerKeys keys) {
42 pdc.set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);
83 stampEntity(pdc, keys, WorkerRole.FARMER);
84 }
85
86 private static void clearRole(PersistentDataContainer pdc, FarmerKeys keys) {
43 87 pdc.remove(keys.farmerItem);
88 pdc.remove(keys.farmerEntity);
89 pdc.remove(keys.lumbererItem);
90 pdc.remove(keys.lumbererEntity);
44 91 }
45 92
46 93 record FarmerSnapshot(
@@ -49,14 +96,15 @@ final class FarmerPersistence {
49 96 String chestWorld,
50 97 Integer chestX,
51 98 Integer chestY,
52 Integer chestZ
99 Integer chestZ,
100 WorkerRole role
53 101 ) {
54 102 FarmerSnapshot withoutCargo() {
55 return new FarmerSnapshot(tool, null, chestWorld, chestX, chestY, chestZ);
103 return new FarmerSnapshot(tool, null, chestWorld, chestX, chestY, chestZ, role);
56 104 }
57 105
58 106 FarmerSnapshot withoutChest() {
59 return new FarmerSnapshot(tool, cargo, null, null, null, null);
107 return new FarmerSnapshot(tool, cargo, null, null, null, null, role);
60 108 }
61 109
62 110 void apply(PersistentDataContainer pdc, FarmerKeys keys) {
@@ -17,30 +17,77 @@ final class FarmerPersistence {
17 return pdc.has(keys.farmerEntity, PersistentDataType.BYTE);
17 return pdc.has(keys.farmerEntity, PersistentDataType.BYTE);
18 }
18 }
19
19
20 static boolean isFarmerStatue(Block block, FarmerKeys keys) {
20 static boolean isLumbererItem(PersistentDataContainerView pdc, FarmerKeys keys) {
21 return pdc.has(keys.lumbererItem, PersistentDataType.BYTE);
22 }
23
24 static boolean isLumbererEntity(PersistentDataContainerView pdc, FarmerKeys keys) {
25 return pdc.has(keys.lumbererEntity, PersistentDataType.BYTE);
26 }
27
28 static boolean isWorkerItem(PersistentDataContainerView pdc, FarmerKeys keys) {
29 return isFarmerItem(pdc, keys) || isLumbererItem(pdc, keys);
30 }
31
32 static boolean isWorkerEntity(PersistentDataContainerView pdc, FarmerKeys keys) {
33 return isFarmerEntity(pdc, keys) || isLumbererEntity(pdc, keys);
34 }
35
36 static boolean isWorkerStatue(Block block, FarmerKeys keys) {
21 return block.getState() instanceof CopperGolemStatue statue
37 return block.getState() instanceof CopperGolemStatue statue
22 && isFarmerEntity(statue.getPersistentDataContainer(), keys);
38 && isWorkerEntity(statue.getPersistentDataContainer(), keys);
39 }
40
41 static WorkerRole roleOf(PersistentDataContainerView pdc, FarmerKeys keys) {
42 if (isLumbererItem(pdc, keys) || isLumbererEntity(pdc, keys)) return WorkerRole.LUMBERER;
43 if (isFarmerItem(pdc, keys) || isFarmerEntity(pdc, keys)) return WorkerRole.FARMER;
44 return null;
23 }
45 }
24
46
25 static FarmerSnapshot capture(PersistentDataContainerView pdc, FarmerKeys keys) {
47 static FarmerSnapshot capture(PersistentDataContainerView pdc, FarmerKeys keys) {
48 WorkerRole role = roleOf(pdc, keys);
26 return new FarmerSnapshot(
49 return new FarmerSnapshot(
27 pdc.get(keys.tool, PersistentDataType.BYTE_ARRAY),
50 pdc.get(keys.tool, PersistentDataType.BYTE_ARRAY),
28 pdc.get(keys.cargo, PersistentDataType.BYTE_ARRAY),
51 pdc.get(keys.cargo, PersistentDataType.BYTE_ARRAY),
29 pdc.get(keys.chestWorld, PersistentDataType.STRING),
52 pdc.get(keys.chestWorld, PersistentDataType.STRING),
30 pdc.get(keys.chestX, PersistentDataType.INTEGER),
53 pdc.get(keys.chestX, PersistentDataType.INTEGER),
31 pdc.get(keys.chestY, PersistentDataType.INTEGER),
54 pdc.get(keys.chestY, PersistentDataType.INTEGER),
32 pdc.get(keys.chestZ, PersistentDataType.INTEGER)
55 pdc.get(keys.chestZ, PersistentDataType.INTEGER),
56 role == null ? WorkerRole.FARMER : role
33 );
57 );
34 }
58 }
35
59
60 static void stampItem(PersistentDataContainer pdc, FarmerKeys keys, WorkerRole role) {
61 clearRole(pdc, keys);
62 if (role == WorkerRole.LUMBERER) {
63 pdc.set(keys.lumbererItem, PersistentDataType.BYTE, (byte) 1);
64 } else {
65 pdc.set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);
66 }
67 }
68
69 static void stampEntity(PersistentDataContainer pdc, FarmerKeys keys, WorkerRole role) {
70 clearRole(pdc, keys);
71 if (role == WorkerRole.LUMBERER) {
72 pdc.set(keys.lumbererEntity, PersistentDataType.BYTE, (byte) 1);
73 } else {
74 pdc.set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);
75 }
76 }
77
36 static void stampItem(PersistentDataContainer pdc, FarmerKeys keys) {
78 static void stampItem(PersistentDataContainer pdc, FarmerKeys keys) {
37 pdc.set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);
79 stampItem(pdc, keys, WorkerRole.FARMER);
38 pdc.remove(keys.farmerEntity);
39 }
80 }
40
81
41 static void stampEntity(PersistentDataContainer pdc, FarmerKeys keys) {
82 static void stampEntity(PersistentDataContainer pdc, FarmerKeys keys) {
42 pdc.set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);
83 stampEntity(pdc, keys, WorkerRole.FARMER);
84 }
85
86 private static void clearRole(PersistentDataContainer pdc, FarmerKeys keys) {
43 pdc.remove(keys.farmerItem);
87 pdc.remove(keys.farmerItem);
88 pdc.remove(keys.farmerEntity);
89 pdc.remove(keys.lumbererItem);
90 pdc.remove(keys.lumbererEntity);
44 }
91 }
45
92
46 record FarmerSnapshot(
93 record FarmerSnapshot(
@@ -49,14 +96,15 @@ final class FarmerPersistence {
49 String chestWorld,
96 String chestWorld,
50 Integer chestX,
97 Integer chestX,
51 Integer chestY,
98 Integer chestY,
52 Integer chestZ
99 Integer chestZ,
100 WorkerRole role
53 ) {
101 ) {
54 FarmerSnapshot withoutCargo() {
102 FarmerSnapshot withoutCargo() {
55 return new FarmerSnapshot(tool, null, chestWorld, chestX, chestY, chestZ);
103 return new FarmerSnapshot(tool, null, chestWorld, chestX, chestY, chestZ, role);
56 }
104 }
57
105
58 FarmerSnapshot withoutChest() {
106 FarmerSnapshot withoutChest() {
59 return new FarmerSnapshot(tool, cargo, null, null, null, null);
107 return new FarmerSnapshot(tool, cargo, null, null, null, null, role);
60 }
108 }
61
109
62 void apply(PersistentDataContainer pdc, FarmerKeys keys) {
110 void apply(PersistentDataContainer pdc, FarmerKeys keys) {
src/main/java/nl/timfalken/copperfarmer/TreeIndex.java added +467 −0
@@ -0,0 +1,467 @@
1 package nl.timfalken.copperfarmer;
2
3 import org.bukkit.Bukkit;
4 import org.bukkit.HeightMap;
5 import org.bukkit.World;
6 import org.bukkit.block.Block;
7 import org.bukkit.block.BlockFace;
8 import org.bukkit.event.world.StructureGrowEvent;
9 import org.bukkit.plugin.Plugin;
10
11 import java.util.ArrayDeque;
12 import java.util.ArrayList;
13 import java.util.Deque;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.UUID;
20
21 final class TreeIndex {
22 private static final BlockFace[] ALL_SIX = {
23 BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
24 };
25 private static final BlockFace[] HORIZONTAL = {
26 BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
27 };
28
29 private final TreeRegistry registry;
30 private final int columnsPerTick;
31 private final int detectsPerTick;
32 private final int maxChunksPerTick;
33 private final int maxLogs;
34 private final int maxLeafVisits;
35 private final int scanAboveGround;
36
37 private final Map<ChunkKey, ChunkScan> chunks = new HashMap<>();
38 private final Map<UUID, DetectedTree> trees = new HashMap<>();
39 private final Map<BlockRef, UUID> logToTree = new HashMap<>();
40
41 TreeIndex(Plugin plugin, TreeRegistry registry) {
42 this.registry = registry;
43 this.columnsPerTick = Math.max(1, plugin.getConfig().getInt("tree-scan-columns-per-tick", 32));
44 this.detectsPerTick = Math.max(1, plugin.getConfig().getInt("tree-detects-per-tick", 2));
45 this.maxChunksPerTick = Math.max(1, plugin.getConfig().getInt("tree-scan-max-chunks-per-tick", 2));
46 this.maxLogs = Math.max(8, plugin.getConfig().getInt("tree-max-logs", 64));
47 this.maxLeafVisits = Math.max(32, plugin.getConfig().getInt("tree-max-leaf-visits", 128));
48 this.scanAboveGround = Math.max(8, plugin.getConfig().getInt("tree-scan-above-ground", 40));
49 }
50
51 void tick() {
52 int columnsLeft = columnsPerTick * maxChunksPerTick;
53 int detectsLeft = detectsPerTick * maxChunksPerTick;
54 int chunksWorked = 0;
55 for (ChunkScan scan : chunks.values()) {
56 if (scan.status != Status.SCANNING) continue;
57 if (chunksWorked >= maxChunksPerTick) break;
58 World world = Bukkit.getWorld(scan.key.worldId());
59 if (world == null || !world.isChunkLoaded(scan.key.x(), scan.key.z())) continue;
60
61 chunksWorked++;
62 int started = scan.nextColumn;
63 while (scan.nextColumn < 256 && columnsLeft > 0 && detectsLeft > 0) {
64 columnsLeft--;
65 if (scanColumn(world, scan, scan.nextColumn)) detectsLeft--;
66 scan.nextColumn++;
67 }
68 if (scan.nextColumn >= 256) {
69 scan.status = Status.READY;
70 } else if (scan.nextColumn == started) {
71 break;
72 }
73 }
74 }
75
76 void requestChunk(World world, int chunkX, int chunkZ) {
77 if (world == null || !world.isChunkLoaded(chunkX, chunkZ)) return;
78 ChunkKey key = new ChunkKey(world.getUID(), chunkX, chunkZ);
79 ChunkScan scan = chunks.get(key);
80 if (scan == null) {
81 scan = new ChunkScan(key);
82 chunks.put(key, scan);
83 }
84 if (scan.status == Status.READY) return;
85 if (scan.status == Status.DIRTY) {
86 removeTreesTouching(key);
87 scan.nextColumn = 0;
88 }
89 scan.status = Status.SCANNING;
90 }
91
92 void requestAround(Block origin, int radius) {
93 if (origin == null) return;
94 World world = origin.getWorld();
95 int chunkRadius = (radius >> 4) + 2;
96 int centerX = origin.getChunk().getX();
97 int centerZ = origin.getChunk().getZ();
98 for (int cx = centerX - chunkRadius; cx <= centerX + chunkRadius; cx++) {
99 for (int cz = centerZ - chunkRadius; cz <= centerZ + chunkRadius; cz++) {
100 requestChunk(world, cx, cz);
101 }
102 }
103 }
104
105 boolean isScanningAround(Block origin, int radius) {
106 if (origin == null) return false;
107 int chunkRadius = (radius >> 4) + 2;
108 int centerX = origin.getChunk().getX();
109 int centerZ = origin.getChunk().getZ();
110 UUID worldId = origin.getWorld().getUID();
111 for (int cx = centerX - chunkRadius; cx <= centerX + chunkRadius; cx++) {
112 for (int cz = centerZ - chunkRadius; cz <= centerZ + chunkRadius; cz++) {
113 ChunkScan scan = chunks.get(new ChunkKey(worldId, cx, cz));
114 if (scan != null && scan.status == Status.SCANNING) return true;
115 }
116 }
117 return false;
118 }
119
120 DetectedTree findAvailable(Block origin, int radius, UUID golemId, Set<UUID> unreachable) {
121 if (origin == null) return null;
122 DetectedTree best = null;
123 double bestDistance = Double.MAX_VALUE;
124 for (DetectedTree tree : trees.values()) {
125 if (!tree.isAvailableFor(golemId)) continue;
126 if (unreachable.contains(tree.id())) continue;
127 if (!tree.hasLogWithin(origin, radius)) continue;
128 if (!tree.stillPresent(origin.getWorld())) {
129 invalidateTree(tree);
130 continue;
131 }
132 BlockRef first = tree.standOrder().getFirst();
133 double dx = first.x() + 0.5 - origin.getX();
134 double dz = first.z() + 0.5 - origin.getZ();
135 double distance = dx * dx + dz * dz;
136 if (distance < bestDistance) {
137 bestDistance = distance;
138 best = tree;
139 }
140 }
141 return best;
142 }
143
144 DetectedTree tree(UUID id) {
145 return id == null ? null : trees.get(id);
146 }
147
148 void invalidateExpectedLog(BlockRef ref) {
149 UUID treeId = logToTree.get(ref);
150 if (treeId == null) {
151 invalidateChunk(ref.worldId(), ref.chunkX(), ref.chunkZ());
152 return;
153 }
154 DetectedTree tree = trees.get(treeId);
155 if (tree != null) invalidateTree(tree);
156 }
157
158 void onStructureGrow(StructureGrowEvent event) {
159 Set<ChunkKey> dirty = new HashSet<>();
160 World world = event.getWorld();
161 for (org.bukkit.block.BlockState state : event.getBlocks()) {
162 dirty.add(new ChunkKey(world.getUID(), state.getX() >> 4, state.getZ() >> 4));
163 }
164 dirty.add(new ChunkKey(world.getUID(), event.getLocation().getBlockX() >> 4, event.getLocation().getBlockZ() >> 4));
165 for (ChunkKey key : dirty) invalidateChunk(key.worldId(), key.x(), key.z());
166 }
167
168 void onBlockChanged(Block block) {
169 if (block == null) return;
170 BlockRef ref = BlockRef.of(block);
171 if (logToTree.containsKey(ref)) invalidateExpectedLog(ref);
172 }
173
174 void onLogGone(BlockRef ref) {
175 invalidateExpectedLog(ref);
176 }
177
178 private boolean scanColumn(World world, ChunkScan scan, int column) {
179 int x = (scan.key.x() << 4) + (column & 15);
180 int z = (scan.key.z() << 4) + (column >> 4);
181 int surface = world.getHighestBlockYAt(HeightMap.MOTION_BLOCKING_NO_LEAVES, x, z);
182 int maxY = Math.min(world.getMaxHeight() - 1, surface + scanAboveGround);
183 if (surface < world.getMinHeight()) return false;
184
185 Block surfaceBlock = world.getBlockAt(x, surface, z);
186 if (tryDetect(surfaceBlock)) return true;
187
188 for (int y = surface + 1; y <= maxY; y++) {
189 Block block = world.getBlockAt(x, y, z);
190 if (tryDetect(block)) return true;
191 }
192 return false;
193 }
194
195 private boolean tryDetect(Block block) {
196 if (!registry.isLog(block.getType())) return false;
197 BlockRef ref = BlockRef.of(block);
198 if (logToTree.containsKey(ref)) return false;
199 DetectedTree tree = detect(block);
200 if (tree == null) return true;
201 addTree(tree);
202 return true;
203 }
204
205 private DetectedTree detect(Block start) {
206 Material logType = start.getType();
207 if (!registry.isLog(logType)) return null;
208 Set<Material> allowedLeaves = registry.leavesForLog(logType);
209
210 Set<BlockRef> trunk = floodLogs(start, logType, maxLogs);
211 if (trunk.isEmpty() || trunk.size() > maxLogs) return null;
212
213 Set<BlockRef> ourFeet = feetOf(start.getWorld(), trunk, logType);
214 Set<BlockRef> allLogs = new HashSet<>(trunk);
215 Set<BlockRef> foreign = new HashSet<>();
216 Set<BlockRef> visitedLeaves = new HashSet<>();
217 Deque<Block> leafQueue = new ArrayDeque<>();
218
219 for (BlockRef log : trunk) enqueueAdjacentLeaves(log, allowedLeaves, visitedLeaves, leafQueue);
220
221 int leafVisits = 0;
222 while (!leafQueue.isEmpty() && leafVisits < maxLeafVisits && allLogs.size() <= maxLogs) {
223 Block leaf = leafQueue.pollFirst();
224 leafVisits++;
225 for (BlockFace face : ALL_SIX) {
226 Block next = leaf.getRelative(face);
227 if (!isChunkLoaded(next)) continue;
228 if (registry.isNaturalLeaf(next, allowedLeaves)) {
229 if (visitedLeaves.add(BlockRef.of(next))) leafQueue.addLast(next);
230 continue;
231 }
232 if (next.getType() != logType) continue;
233 BlockRef nextRef = BlockRef.of(next);
234 if (allLogs.contains(nextRef) || foreign.contains(nextRef)) continue;
235
236 Set<BlockRef> component = floodLogs(next, logType, maxLogs);
237 if (component.size() > maxLogs) {
238 foreign.addAll(component);
239 continue;
240 }
241 Set<BlockRef> theirFeet = feetOf(start.getWorld(), component, logType);
242 if (isOtherTree(ourFeet, theirFeet)) {
243 foreign.addAll(component);
244 continue;
245 }
246 allLogs.addAll(component);
247 for (BlockRef log : component) enqueueAdjacentLeaves(log, allowedLeaves, visitedLeaves, leafQueue);
248 }
249 }
250
251 if (allLogs.isEmpty() || allLogs.size() > maxLogs) return null;
252 return validate(start.getWorld(), logType, allowedLeaves, allLogs, visitedLeaves);
253 }
254
255 private Set<BlockRef> floodLogs(Block start, Material logType, int limit) {
256 Set<BlockRef> found = new HashSet<>();
257 Deque<Block> queue = new ArrayDeque<>();
258 queue.add(start);
259 found.add(BlockRef.of(start));
260 while (!queue.isEmpty() && found.size() <= limit) {
261 Block current = queue.pollFirst();
262 for (BlockFace face : ALL_SIX) {
263 Block next = current.getRelative(face);
264 if (!isChunkLoaded(next) || next.getType() != logType) continue;
265 if (found.add(BlockRef.of(next))) queue.addLast(next);
266 }
267 }
268 return found;
269 }
270
271 private void enqueueAdjacentLeaves(
272 BlockRef log,
273 Set<Material> allowedLeaves,
274 Set<BlockRef> visitedLeaves,
275 Deque<Block> leafQueue
276 ) {
277 Block block = log.blockIfLoaded();
278 if (block == null) return;
279 for (BlockFace face : ALL_SIX) {
280 Block next = block.getRelative(face);
281 if (!isChunkLoaded(next) || !registry.isNaturalLeaf(next, allowedLeaves)) continue;
282 if (visitedLeaves.add(BlockRef.of(next))) leafQueue.addLast(next);
283 }
284 }
285
286 private Set<BlockRef> feetOf(World world, Set<BlockRef> logs, Material logType) {
287 Set<BlockRef> feet = new HashSet<>();
288 for (BlockRef log : logs) {
289 if (world == null || !world.isChunkLoaded(log.chunkX(), log.chunkZ())) continue;
290 Block below = world.getBlockAt(log.x(), log.y() - 1, log.z());
291 if (below.getType() == logType) continue;
292 if (registry.isValidSoil(below.getType())) feet.add(log);
293 }
294 return feet;
295 }
296
297 private boolean isOtherTree(Set<BlockRef> ourFeet, Set<BlockRef> theirFeet) {
298 if (theirFeet.isEmpty()) return false;
299 for (BlockRef foot : theirFeet) {
300 if (!ourFeet.contains(foot)) return true;
301 }
302 return false;
303 }
304
305 private DetectedTree validate(
306 World world,
307 Material logType,
308 Set<Material> allowedLeaves,
309 Set<BlockRef> logs,
310 Set<BlockRef> seenLeafBlocks
311 ) {
312 if (world == null) return null;
313 Set<Material> seenLeaves = new HashSet<>();
314 for (BlockRef leafRef : seenLeafBlocks) {
315 Block leaf = leafRef.blockIfLoaded();
316 if (leaf != null) seenLeaves.add(leaf.getType());
317 }
318
319 int highestY = Integer.MIN_VALUE;
320 for (BlockRef log : logs) highestY = Math.max(highestY, log.y());
321 boolean topHasLeaves = false;
322
323 for (BlockRef log : logs) {
324 Block block = log.blockIfLoaded();
325 if (block == null || block.getType() != logType) return null;
326 for (BlockFace face : HORIZONTAL) {
327 Block neighbour = block.getRelative(face);
328 if (!registry.isAllowedHorizontal(neighbour.getType(), logType, allowedLeaves, neighbour)) {
329 return null;
330 }
331 }
332 if (log.y() == highestY) {
333 for (BlockFace face : ALL_SIX) {
334 if (registry.isNaturalLeaf(block.getRelative(face), allowedLeaves)) {
335 topHasLeaves = true;
336 seenLeaves.add(block.getRelative(face).getType());
337 break;
338 }
339 }
340 }
341 }
342 if (!topHasLeaves) return null;
343
344 TreeRegistry.Species species = registry.classify(logType, seenLeaves);
345 if (species == null) return null;
346
347 Set<BlockRef> feet = feetOf(world, logs, logType);
348 List<BlockRef> plantSpots = plantSpots(feet, logs);
349 if (plantSpots.isEmpty()) return null;
350
351 List<BlockRef> ordered = new ArrayList<>(logs);
352 return new DetectedTree(species, ordered, plantSpots);
353 }
354
355 private List<BlockRef> plantSpots(Set<BlockRef> feet, Set<BlockRef> logs) {
356 if (feet.isEmpty()) return List.of();
357 List<BlockRef> asList = new ArrayList<>(feet);
358 if (asList.size() == 4 && isTwoByTwo(asList)) return asList;
359 return List.of(primaryFoot(asList, logs));
360 }
361
362 private boolean isTwoByTwo(List<BlockRef> feet) {
363 int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
364 int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE;
365 Integer y = null;
366 Set<Long> xz = new HashSet<>();
367 for (BlockRef foot : feet) {
368 if (y == null) y = foot.y();
369 if (foot.y() != y) return false;
370 minX = Math.min(minX, foot.x());
371 maxX = Math.max(maxX, foot.x());
372 minZ = Math.min(minZ, foot.z());
373 maxZ = Math.max(maxZ, foot.z());
374 xz.add((((long) foot.x()) << 32) ^ (foot.z() & 0xffffffffL));
375 }
376 return xz.size() == 4 && maxX - minX == 1 && maxZ - minZ == 1;
377 }
378
379 private BlockRef primaryFoot(List<BlockRef> feet, Set<BlockRef> logs) {
380 BlockRef best = feet.getFirst();
381 int bestCount = -1;
382 for (BlockRef foot : feet) {
383 int count = 0;
384 for (BlockRef log : logs) {
385 if (log.x() == foot.x() && log.z() == foot.z()) count++;
386 }
387 if (count > bestCount) {
388 bestCount = count;
389 best = foot;
390 }
391 }
392 return best;
393 }
394
395 private void addTree(DetectedTree tree) {
396 trees.put(tree.id(), tree);
397 for (BlockRef log : tree.logs()) logToTree.put(log, tree.id());
398 }
399
400 private void invalidateTree(DetectedTree tree) {
401 removeTree(tree.id());
402 Set<ChunkKey> dirty = new HashSet<>();
403 for (BlockRef log : tree.logs()) {
404 dirty.add(new ChunkKey(log.worldId(), log.chunkX(), log.chunkZ()));
405 }
406 for (ChunkKey key : dirty) {
407 ChunkScan scan = chunks.get(key);
408 if (scan == null) {
409 scan = new ChunkScan(key);
410 chunks.put(key, scan);
411 }
412 if (scan.status == Status.SCANNING) continue;
413 scan.status = Status.DIRTY;
414 scan.nextColumn = 0;
415 }
416 }
417
418 private void invalidateChunk(UUID worldId, int chunkX, int chunkZ) {
419 ChunkKey key = new ChunkKey(worldId, chunkX, chunkZ);
420 removeTreesTouching(key);
421 ChunkScan scan = chunks.get(key);
422 if (scan == null) {
423 scan = new ChunkScan(key);
424 chunks.put(key, scan);
425 }
426 if (scan.status != Status.SCANNING) {
427 scan.status = Status.DIRTY;
428 scan.nextColumn = 0;
429 }
430 }
431
432 private void removeTreesTouching(ChunkKey key) {
433 List<UUID> remove = new ArrayList<>();
434 for (DetectedTree tree : trees.values()) {
435 if (tree.touchesChunk(key.worldId(), key.x(), key.z())) remove.add(tree.id());
436 }
437 for (UUID id : remove) removeTree(id);
438 }
439
440 private void removeTree(UUID id) {
441 DetectedTree tree = trees.remove(id);
442 if (tree == null) return;
443 for (BlockRef log : tree.logs()) logToTree.remove(log, id);
444 }
445
446 private static boolean isChunkLoaded(Block block) {
447 return block.getWorld().isChunkLoaded(block.getX() >> 4, block.getZ() >> 4);
448 }
449
450 private enum Status {
451 SCANNING,
452 READY,
453 DIRTY
454 }
455
456 private record ChunkKey(UUID worldId, int x, int z) {}
457
458 private static final class ChunkScan {
459 final ChunkKey key;
460 Status status = Status.DIRTY;
461 int nextColumn;
462
463 ChunkScan(ChunkKey key) {
464 this.key = key;
465 }
466 }
467 }
@@ -0,0 +1,467 @@
1package nl.timfalken.copperfarmer;
2
3import org.bukkit.Bukkit;
4import org.bukkit.HeightMap;
5import org.bukkit.World;
6import org.bukkit.block.Block;
7import org.bukkit.block.BlockFace;
8import org.bukkit.event.world.StructureGrowEvent;
9import org.bukkit.plugin.Plugin;
10
11import java.util.ArrayDeque;
12import java.util.ArrayList;
13import java.util.Deque;
14import java.util.HashMap;
15import java.util.HashSet;
16import java.util.List;
17import java.util.Map;
18import java.util.Set;
19import java.util.UUID;
20
21final class TreeIndex {
22 private static final BlockFace[] ALL_SIX = {
23 BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
24 };
25 private static final BlockFace[] HORIZONTAL = {
26 BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
27 };
28
29 private final TreeRegistry registry;
30 private final int columnsPerTick;
31 private final int detectsPerTick;
32 private final int maxChunksPerTick;
33 private final int maxLogs;
34 private final int maxLeafVisits;
35 private final int scanAboveGround;
36
37 private final Map<ChunkKey, ChunkScan> chunks = new HashMap<>();
38 private final Map<UUID, DetectedTree> trees = new HashMap<>();
39 private final Map<BlockRef, UUID> logToTree = new HashMap<>();
40
41 TreeIndex(Plugin plugin, TreeRegistry registry) {
42 this.registry = registry;
43 this.columnsPerTick = Math.max(1, plugin.getConfig().getInt("tree-scan-columns-per-tick", 32));
44 this.detectsPerTick = Math.max(1, plugin.getConfig().getInt("tree-detects-per-tick", 2));
45 this.maxChunksPerTick = Math.max(1, plugin.getConfig().getInt("tree-scan-max-chunks-per-tick", 2));
46 this.maxLogs = Math.max(8, plugin.getConfig().getInt("tree-max-logs", 64));
47 this.maxLeafVisits = Math.max(32, plugin.getConfig().getInt("tree-max-leaf-visits", 128));
48 this.scanAboveGround = Math.max(8, plugin.getConfig().getInt("tree-scan-above-ground", 40));
49 }
50
51 void tick() {
52 int columnsLeft = columnsPerTick * maxChunksPerTick;
53 int detectsLeft = detectsPerTick * maxChunksPerTick;
54 int chunksWorked = 0;
55 for (ChunkScan scan : chunks.values()) {
56 if (scan.status != Status.SCANNING) continue;
57 if (chunksWorked >= maxChunksPerTick) break;
58 World world = Bukkit.getWorld(scan.key.worldId());
59 if (world == null || !world.isChunkLoaded(scan.key.x(), scan.key.z())) continue;
60
61 chunksWorked++;
62 int started = scan.nextColumn;
63 while (scan.nextColumn < 256 && columnsLeft > 0 && detectsLeft > 0) {
64 columnsLeft--;
65 if (scanColumn(world, scan, scan.nextColumn)) detectsLeft--;
66 scan.nextColumn++;
67 }
68 if (scan.nextColumn >= 256) {
69 scan.status = Status.READY;
70 } else if (scan.nextColumn == started) {
71 break;
72 }
73 }
74 }
75
76 void requestChunk(World world, int chunkX, int chunkZ) {
77 if (world == null || !world.isChunkLoaded(chunkX, chunkZ)) return;
78 ChunkKey key = new ChunkKey(world.getUID(), chunkX, chunkZ);
79 ChunkScan scan = chunks.get(key);
80 if (scan == null) {
81 scan = new ChunkScan(key);
82 chunks.put(key, scan);
83 }
84 if (scan.status == Status.READY) return;
85 if (scan.status == Status.DIRTY) {
86 removeTreesTouching(key);
87 scan.nextColumn = 0;
88 }
89 scan.status = Status.SCANNING;
90 }
91
92 void requestAround(Block origin, int radius) {
93 if (origin == null) return;
94 World world = origin.getWorld();
95 int chunkRadius = (radius >> 4) + 2;
96 int centerX = origin.getChunk().getX();
97 int centerZ = origin.getChunk().getZ();
98 for (int cx = centerX - chunkRadius; cx <= centerX + chunkRadius; cx++) {
99 for (int cz = centerZ - chunkRadius; cz <= centerZ + chunkRadius; cz++) {
100 requestChunk(world, cx, cz);
101 }
102 }
103 }
104
105 boolean isScanningAround(Block origin, int radius) {
106 if (origin == null) return false;
107 int chunkRadius = (radius >> 4) + 2;
108 int centerX = origin.getChunk().getX();
109 int centerZ = origin.getChunk().getZ();
110 UUID worldId = origin.getWorld().getUID();
111 for (int cx = centerX - chunkRadius; cx <= centerX + chunkRadius; cx++) {
112 for (int cz = centerZ - chunkRadius; cz <= centerZ + chunkRadius; cz++) {
113 ChunkScan scan = chunks.get(new ChunkKey(worldId, cx, cz));
114 if (scan != null && scan.status == Status.SCANNING) return true;
115 }
116 }
117 return false;
118 }
119
120 DetectedTree findAvailable(Block origin, int radius, UUID golemId, Set<UUID> unreachable) {
121 if (origin == null) return null;
122 DetectedTree best = null;
123 double bestDistance = Double.MAX_VALUE;
124 for (DetectedTree tree : trees.values()) {
125 if (!tree.isAvailableFor(golemId)) continue;
126 if (unreachable.contains(tree.id())) continue;
127 if (!tree.hasLogWithin(origin, radius)) continue;
128 if (!tree.stillPresent(origin.getWorld())) {
129 invalidateTree(tree);
130 continue;
131 }
132 BlockRef first = tree.standOrder().getFirst();
133 double dx = first.x() + 0.5 - origin.getX();
134 double dz = first.z() + 0.5 - origin.getZ();
135 double distance = dx * dx + dz * dz;
136 if (distance < bestDistance) {
137 bestDistance = distance;
138 best = tree;
139 }
140 }
141 return best;
142 }
143
144 DetectedTree tree(UUID id) {
145 return id == null ? null : trees.get(id);
146 }
147
148 void invalidateExpectedLog(BlockRef ref) {
149 UUID treeId = logToTree.get(ref);
150 if (treeId == null) {
151 invalidateChunk(ref.worldId(), ref.chunkX(), ref.chunkZ());
152 return;
153 }
154 DetectedTree tree = trees.get(treeId);
155 if (tree != null) invalidateTree(tree);
156 }
157
158 void onStructureGrow(StructureGrowEvent event) {
159 Set<ChunkKey> dirty = new HashSet<>();
160 World world = event.getWorld();
161 for (org.bukkit.block.BlockState state : event.getBlocks()) {
162 dirty.add(new ChunkKey(world.getUID(), state.getX() >> 4, state.getZ() >> 4));
163 }
164 dirty.add(new ChunkKey(world.getUID(), event.getLocation().getBlockX() >> 4, event.getLocation().getBlockZ() >> 4));
165 for (ChunkKey key : dirty) invalidateChunk(key.worldId(), key.x(), key.z());
166 }
167
168 void onBlockChanged(Block block) {
169 if (block == null) return;
170 BlockRef ref = BlockRef.of(block);
171 if (logToTree.containsKey(ref)) invalidateExpectedLog(ref);
172 }
173
174 void onLogGone(BlockRef ref) {
175 invalidateExpectedLog(ref);
176 }
177
178 private boolean scanColumn(World world, ChunkScan scan, int column) {
179 int x = (scan.key.x() << 4) + (column & 15);
180 int z = (scan.key.z() << 4) + (column >> 4);
181 int surface = world.getHighestBlockYAt(HeightMap.MOTION_BLOCKING_NO_LEAVES, x, z);
182 int maxY = Math.min(world.getMaxHeight() - 1, surface + scanAboveGround);
183 if (surface < world.getMinHeight()) return false;
184
185 Block surfaceBlock = world.getBlockAt(x, surface, z);
186 if (tryDetect(surfaceBlock)) return true;
187
188 for (int y = surface + 1; y <= maxY; y++) {
189 Block block = world.getBlockAt(x, y, z);
190 if (tryDetect(block)) return true;
191 }
192 return false;
193 }
194
195 private boolean tryDetect(Block block) {
196 if (!registry.isLog(block.getType())) return false;
197 BlockRef ref = BlockRef.of(block);
198 if (logToTree.containsKey(ref)) return false;
199 DetectedTree tree = detect(block);
200 if (tree == null) return true;
201 addTree(tree);
202 return true;
203 }
204
205 private DetectedTree detect(Block start) {
206 Material logType = start.getType();
207 if (!registry.isLog(logType)) return null;
208 Set<Material> allowedLeaves = registry.leavesForLog(logType);
209
210 Set<BlockRef> trunk = floodLogs(start, logType, maxLogs);
211 if (trunk.isEmpty() || trunk.size() > maxLogs) return null;
212
213 Set<BlockRef> ourFeet = feetOf(start.getWorld(), trunk, logType);
214 Set<BlockRef> allLogs = new HashSet<>(trunk);
215 Set<BlockRef> foreign = new HashSet<>();
216 Set<BlockRef> visitedLeaves = new HashSet<>();
217 Deque<Block> leafQueue = new ArrayDeque<>();
218
219 for (BlockRef log : trunk) enqueueAdjacentLeaves(log, allowedLeaves, visitedLeaves, leafQueue);
220
221 int leafVisits = 0;
222 while (!leafQueue.isEmpty() && leafVisits < maxLeafVisits && allLogs.size() <= maxLogs) {
223 Block leaf = leafQueue.pollFirst();
224 leafVisits++;
225 for (BlockFace face : ALL_SIX) {
226 Block next = leaf.getRelative(face);
227 if (!isChunkLoaded(next)) continue;
228 if (registry.isNaturalLeaf(next, allowedLeaves)) {
229 if (visitedLeaves.add(BlockRef.of(next))) leafQueue.addLast(next);
230 continue;
231 }
232 if (next.getType() != logType) continue;
233 BlockRef nextRef = BlockRef.of(next);
234 if (allLogs.contains(nextRef) || foreign.contains(nextRef)) continue;
235
236 Set<BlockRef> component = floodLogs(next, logType, maxLogs);
237 if (component.size() > maxLogs) {
238 foreign.addAll(component);
239 continue;
240 }
241 Set<BlockRef> theirFeet = feetOf(start.getWorld(), component, logType);
242 if (isOtherTree(ourFeet, theirFeet)) {
243 foreign.addAll(component);
244 continue;
245 }
246 allLogs.addAll(component);
247 for (BlockRef log : component) enqueueAdjacentLeaves(log, allowedLeaves, visitedLeaves, leafQueue);
248 }
249 }
250
251 if (allLogs.isEmpty() || allLogs.size() > maxLogs) return null;
252 return validate(start.getWorld(), logType, allowedLeaves, allLogs, visitedLeaves);
253 }
254
255 private Set<BlockRef> floodLogs(Block start, Material logType, int limit) {
256 Set<BlockRef> found = new HashSet<>();
257 Deque<Block> queue = new ArrayDeque<>();
258 queue.add(start);
259 found.add(BlockRef.of(start));
260 while (!queue.isEmpty() && found.size() <= limit) {
261 Block current = queue.pollFirst();
262 for (BlockFace face : ALL_SIX) {
263 Block next = current.getRelative(face);
264 if (!isChunkLoaded(next) || next.getType() != logType) continue;
265 if (found.add(BlockRef.of(next))) queue.addLast(next);
266 }
267 }
268 return found;
269 }
270
271 private void enqueueAdjacentLeaves(
272 BlockRef log,
273 Set<Material> allowedLeaves,
274 Set<BlockRef> visitedLeaves,
275 Deque<Block> leafQueue
276 ) {
277 Block block = log.blockIfLoaded();
278 if (block == null) return;
279 for (BlockFace face : ALL_SIX) {
280 Block next = block.getRelative(face);
281 if (!isChunkLoaded(next) || !registry.isNaturalLeaf(next, allowedLeaves)) continue;
282 if (visitedLeaves.add(BlockRef.of(next))) leafQueue.addLast(next);
283 }
284 }
285
286 private Set<BlockRef> feetOf(World world, Set<BlockRef> logs, Material logType) {
287 Set<BlockRef> feet = new HashSet<>();
288 for (BlockRef log : logs) {
289 if (world == null || !world.isChunkLoaded(log.chunkX(), log.chunkZ())) continue;
290 Block below = world.getBlockAt(log.x(), log.y() - 1, log.z());
291 if (below.getType() == logType) continue;
292 if (registry.isValidSoil(below.getType())) feet.add(log);
293 }
294 return feet;
295 }
296
297 private boolean isOtherTree(Set<BlockRef> ourFeet, Set<BlockRef> theirFeet) {
298 if (theirFeet.isEmpty()) return false;
299 for (BlockRef foot : theirFeet) {
300 if (!ourFeet.contains(foot)) return true;
301 }
302 return false;
303 }
304
305 private DetectedTree validate(
306 World world,
307 Material logType,
308 Set<Material> allowedLeaves,
309 Set<BlockRef> logs,
310 Set<BlockRef> seenLeafBlocks
311 ) {
312 if (world == null) return null;
313 Set<Material> seenLeaves = new HashSet<>();
314 for (BlockRef leafRef : seenLeafBlocks) {
315 Block leaf = leafRef.blockIfLoaded();
316 if (leaf != null) seenLeaves.add(leaf.getType());
317 }
318
319 int highestY = Integer.MIN_VALUE;
320 for (BlockRef log : logs) highestY = Math.max(highestY, log.y());
321 boolean topHasLeaves = false;
322
323 for (BlockRef log : logs) {
324 Block block = log.blockIfLoaded();
325 if (block == null || block.getType() != logType) return null;
326 for (BlockFace face : HORIZONTAL) {
327 Block neighbour = block.getRelative(face);
328 if (!registry.isAllowedHorizontal(neighbour.getType(), logType, allowedLeaves, neighbour)) {
329 return null;
330 }
331 }
332 if (log.y() == highestY) {
333 for (BlockFace face : ALL_SIX) {
334 if (registry.isNaturalLeaf(block.getRelative(face), allowedLeaves)) {
335 topHasLeaves = true;
336 seenLeaves.add(block.getRelative(face).getType());
337 break;
338 }
339 }
340 }
341 }
342 if (!topHasLeaves) return null;
343
344 TreeRegistry.Species species = registry.classify(logType, seenLeaves);
345 if (species == null) return null;
346
347 Set<BlockRef> feet = feetOf(world, logs, logType);
348 List<BlockRef> plantSpots = plantSpots(feet, logs);
349 if (plantSpots.isEmpty()) return null;
350
351 List<BlockRef> ordered = new ArrayList<>(logs);
352 return new DetectedTree(species, ordered, plantSpots);
353 }
354
355 private List<BlockRef> plantSpots(Set<BlockRef> feet, Set<BlockRef> logs) {
356 if (feet.isEmpty()) return List.of();
357 List<BlockRef> asList = new ArrayList<>(feet);
358 if (asList.size() == 4 && isTwoByTwo(asList)) return asList;
359 return List.of(primaryFoot(asList, logs));
360 }
361
362 private boolean isTwoByTwo(List<BlockRef> feet) {
363 int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
364 int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE;
365 Integer y = null;
366 Set<Long> xz = new HashSet<>();
367 for (BlockRef foot : feet) {
368 if (y == null) y = foot.y();
369 if (foot.y() != y) return false;
370 minX = Math.min(minX, foot.x());
371 maxX = Math.max(maxX, foot.x());
372 minZ = Math.min(minZ, foot.z());
373 maxZ = Math.max(maxZ, foot.z());
374 xz.add((((long) foot.x()) << 32) ^ (foot.z() & 0xffffffffL));
375 }
376 return xz.size() == 4 && maxX - minX == 1 && maxZ - minZ == 1;
377 }
378
379 private BlockRef primaryFoot(List<BlockRef> feet, Set<BlockRef> logs) {
380 BlockRef best = feet.getFirst();
381 int bestCount = -1;
382 for (BlockRef foot : feet) {
383 int count = 0;
384 for (BlockRef log : logs) {
385 if (log.x() == foot.x() && log.z() == foot.z()) count++;
386 }
387 if (count > bestCount) {
388 bestCount = count;
389 best = foot;
390 }
391 }
392 return best;
393 }
394
395 private void addTree(DetectedTree tree) {
396 trees.put(tree.id(), tree);
397 for (BlockRef log : tree.logs()) logToTree.put(log, tree.id());
398 }
399
400 private void invalidateTree(DetectedTree tree) {
401 removeTree(tree.id());
402 Set<ChunkKey> dirty = new HashSet<>();
403 for (BlockRef log : tree.logs()) {
404 dirty.add(new ChunkKey(log.worldId(), log.chunkX(), log.chunkZ()));
405 }
406 for (ChunkKey key : dirty) {
407 ChunkScan scan = chunks.get(key);
408 if (scan == null) {
409 scan = new ChunkScan(key);
410 chunks.put(key, scan);
411 }
412 if (scan.status == Status.SCANNING) continue;
413 scan.status = Status.DIRTY;
414 scan.nextColumn = 0;
415 }
416 }
417
418 private void invalidateChunk(UUID worldId, int chunkX, int chunkZ) {
419 ChunkKey key = new ChunkKey(worldId, chunkX, chunkZ);
420 removeTreesTouching(key);
421 ChunkScan scan = chunks.get(key);
422 if (scan == null) {
423 scan = new ChunkScan(key);
424 chunks.put(key, scan);
425 }
426 if (scan.status != Status.SCANNING) {
427 scan.status = Status.DIRTY;
428 scan.nextColumn = 0;
429 }
430 }
431
432 private void removeTreesTouching(ChunkKey key) {
433 List<UUID> remove = new ArrayList<>();
434 for (DetectedTree tree : trees.values()) {
435 if (tree.touchesChunk(key.worldId(), key.x(), key.z())) remove.add(tree.id());
436 }
437 for (UUID id : remove) removeTree(id);
438 }
439
440 private void removeTree(UUID id) {
441 DetectedTree tree = trees.remove(id);
442 if (tree == null) return;
443 for (BlockRef log : tree.logs()) logToTree.remove(log, id);
444 }
445
446 private static boolean isChunkLoaded(Block block) {
447 return block.getWorld().isChunkLoaded(block.getX() >> 4, block.getZ() >> 4);
448 }
449
450 private enum Status {
451 SCANNING,
452 READY,
453 DIRTY
454 }
455
456 private record ChunkKey(UUID worldId, int x, int z) {}
457
458 private static final class ChunkScan {
459 final ChunkKey key;
460 Status status = Status.DIRTY;
461 int nextColumn;
462
463 ChunkScan(ChunkKey key) {
464 this.key = key;
465 }
466 }
467}
src/main/java/nl/timfalken/copperfarmer/TreeRegistry.java added +135 −0
@@ -0,0 +1,135 @@
1 package nl.timfalken.copperfarmer;
2
3 import org.bukkit.Material;
4 import org.bukkit.block.Block;
5 import org.bukkit.block.BlockFace;
6 import org.bukkit.block.data.type.Leaves;
7
8 import java.util.EnumMap;
9 import java.util.EnumSet;
10 import java.util.HashSet;
11 import java.util.Map;
12 import java.util.Set;
13
14 final class TreeRegistry {
15 private static final Set<Material> SOILS = EnumSet.of(
16 Material.DIRT,
17 Material.GRASS_BLOCK,
18 Material.PODZOL,
19 Material.COARSE_DIRT,
20 Material.ROOTED_DIRT,
21 Material.MYCELIUM,
22 Material.MOSS_BLOCK,
23 Material.PALE_MOSS_BLOCK,
24 Material.MUD,
25 Material.MUDDY_MANGROVE_ROOTS,
26 Material.FARMLAND
27 );
28
29 private static final Set<Material> CLUTTER = EnumSet.of(
30 Material.VINE,
31 Material.CAVE_VINES,
32 Material.CAVE_VINES_PLANT,
33 Material.GLOW_LICHEN,
34 Material.COCOA,
35 Material.SNOW,
36 Material.MOSS_CARPET,
37 Material.PALE_MOSS_CARPET,
38 Material.PALE_HANGING_MOSS,
39 Material.PINK_PETALS,
40 Material.LEAF_LITTER
41 );
42
43 record Species(String name, Set<Material> logs, Set<Material> leaves, Material sapling) {
44 boolean isLog(Material material) {
45 return logs.contains(material);
46 }
47
48 boolean isLeaf(Material material) {
49 return leaves.contains(material);
50 }
51 }
52
53 private final Map<Material, Set<Species>> byLog = new EnumMap<>(Material.class);
54 private final Set<Material> logs = EnumSet.noneOf(Material.class);
55
56 TreeRegistry() {
57 register("oak", Set.of(Material.OAK_LOG), Set.of(Material.OAK_LEAVES), Material.OAK_SAPLING);
58 register("azalea", Set.of(Material.OAK_LOG), Set.of(Material.AZALEA_LEAVES, Material.FLOWERING_AZALEA_LEAVES),
59 Material.AZALEA);
60 register("birch", Set.of(Material.BIRCH_LOG), Set.of(Material.BIRCH_LEAVES), Material.BIRCH_SAPLING);
61 register("spruce", Set.of(Material.SPRUCE_LOG), Set.of(Material.SPRUCE_LEAVES), Material.SPRUCE_SAPLING);
62 register("jungle", Set.of(Material.JUNGLE_LOG), Set.of(Material.JUNGLE_LEAVES), Material.JUNGLE_SAPLING);
63 register("acacia", Set.of(Material.ACACIA_LOG), Set.of(Material.ACACIA_LEAVES), Material.ACACIA_SAPLING);
64 register("dark_oak", Set.of(Material.DARK_OAK_LOG), Set.of(Material.DARK_OAK_LEAVES), Material.DARK_OAK_SAPLING);
65 register("cherry", Set.of(Material.CHERRY_LOG), Set.of(Material.CHERRY_LEAVES), Material.CHERRY_SAPLING);
66 register("pale_oak", Set.of(Material.PALE_OAK_LOG), Set.of(Material.PALE_OAK_LEAVES), Material.PALE_OAK_SAPLING);
67 register("mangrove", Set.of(Material.MANGROVE_LOG), Set.of(Material.MANGROVE_LEAVES), Material.MANGROVE_PROPAGULE);
68 }
69
70 private void register(String name, Set<Material> logTypes, Set<Material> leafTypes, Material sapling) {
71 Species species = new Species(name, EnumSet.copyOf(logTypes), EnumSet.copyOf(leafTypes), sapling);
72 for (Material log : logTypes) {
73 logs.add(log);
74 byLog.computeIfAbsent(log, ignored -> new HashSet<>()).add(species);
75 }
76 }
77
78 boolean isLog(Material material) {
79 return logs.contains(material);
80 }
81
82 Set<Species> speciesForLog(Material material) {
83 Set<Species> species = byLog.get(material);
84 return species == null ? Set.of() : species;
85 }
86
87 Set<Material> leavesForLog(Material log) {
88 EnumSet<Material> leaves = EnumSet.noneOf(Material.class);
89 for (Species species : speciesForLog(log)) leaves.addAll(species.leaves());
90 return leaves;
91 }
92
93 Species classify(Material log, Set<Material> seenLeaves) {
94 Set<Species> candidates = speciesForLog(log);
95 if (candidates.isEmpty()) return null;
96 Species best = null;
97 int bestScore = -1;
98 for (Species species : candidates) {
99 int score = 0;
100 for (Material leaf : seenLeaves) {
101 if (species.isLeaf(leaf)) score++;
102 }
103 if (score > bestScore) {
104 bestScore = score;
105 best = species;
106 }
107 }
108 return bestScore > 0 ? best : null;
109 }
110
111 boolean isNaturalLeaf(Block block, Set<Material> allowedLeaves) {
112 if (!allowedLeaves.contains(block.getType())) return false;
113 return block.getBlockData() instanceof Leaves leaves && !leaves.isPersistent();
114 }
115
116 boolean isValidSoil(Material material) {
117 return SOILS.contains(material);
118 }
119
120 boolean isAllowedHorizontal(Material neighbour, Material log, Set<Material> allowedLeaves, Block neighbourBlock) {
121 if (neighbour.isAir()) return true;
122 if (neighbour == log) return true;
123 if (CLUTTER.contains(neighbour)) return true;
124 if (allowedLeaves.contains(neighbour)) {
125 return neighbourBlock.getBlockData() instanceof Leaves leaves && !leaves.isPersistent();
126 }
127 return false;
128 }
129
130 boolean canPlantAt(Block space, Species species) {
131 if (space == null || !space.getType().isAir() || species == null) return false;
132 return isValidSoil(space.getRelative(BlockFace.DOWN).getType());
133 }
134
135 }
@@ -0,0 +1,135 @@
1package nl.timfalken.copperfarmer;
2
3import org.bukkit.Material;
4import org.bukkit.block.Block;
5import org.bukkit.block.BlockFace;
6import org.bukkit.block.data.type.Leaves;
7
8import java.util.EnumMap;
9import java.util.EnumSet;
10import java.util.HashSet;
11import java.util.Map;
12import java.util.Set;
13
14final class TreeRegistry {
15 private static final Set<Material> SOILS = EnumSet.of(
16 Material.DIRT,
17 Material.GRASS_BLOCK,
18 Material.PODZOL,
19 Material.COARSE_DIRT,
20 Material.ROOTED_DIRT,
21 Material.MYCELIUM,
22 Material.MOSS_BLOCK,
23 Material.PALE_MOSS_BLOCK,
24 Material.MUD,
25 Material.MUDDY_MANGROVE_ROOTS,
26 Material.FARMLAND
27 );
28
29 private static final Set<Material> CLUTTER = EnumSet.of(
30 Material.VINE,
31 Material.CAVE_VINES,
32 Material.CAVE_VINES_PLANT,
33 Material.GLOW_LICHEN,
34 Material.COCOA,
35 Material.SNOW,
36 Material.MOSS_CARPET,
37 Material.PALE_MOSS_CARPET,
38 Material.PALE_HANGING_MOSS,
39 Material.PINK_PETALS,
40 Material.LEAF_LITTER
41 );
42
43 record Species(String name, Set<Material> logs, Set<Material> leaves, Material sapling) {
44 boolean isLog(Material material) {
45 return logs.contains(material);
46 }
47
48 boolean isLeaf(Material material) {
49 return leaves.contains(material);
50 }
51 }
52
53 private final Map<Material, Set<Species>> byLog = new EnumMap<>(Material.class);
54 private final Set<Material> logs = EnumSet.noneOf(Material.class);
55
56 TreeRegistry() {
57 register("oak", Set.of(Material.OAK_LOG), Set.of(Material.OAK_LEAVES), Material.OAK_SAPLING);
58 register("azalea", Set.of(Material.OAK_LOG), Set.of(Material.AZALEA_LEAVES, Material.FLOWERING_AZALEA_LEAVES),
59 Material.AZALEA);
60 register("birch", Set.of(Material.BIRCH_LOG), Set.of(Material.BIRCH_LEAVES), Material.BIRCH_SAPLING);
61 register("spruce", Set.of(Material.SPRUCE_LOG), Set.of(Material.SPRUCE_LEAVES), Material.SPRUCE_SAPLING);
62 register("jungle", Set.of(Material.JUNGLE_LOG), Set.of(Material.JUNGLE_LEAVES), Material.JUNGLE_SAPLING);
63 register("acacia", Set.of(Material.ACACIA_LOG), Set.of(Material.ACACIA_LEAVES), Material.ACACIA_SAPLING);
64 register("dark_oak", Set.of(Material.DARK_OAK_LOG), Set.of(Material.DARK_OAK_LEAVES), Material.DARK_OAK_SAPLING);
65 register("cherry", Set.of(Material.CHERRY_LOG), Set.of(Material.CHERRY_LEAVES), Material.CHERRY_SAPLING);
66 register("pale_oak", Set.of(Material.PALE_OAK_LOG), Set.of(Material.PALE_OAK_LEAVES), Material.PALE_OAK_SAPLING);
67 register("mangrove", Set.of(Material.MANGROVE_LOG), Set.of(Material.MANGROVE_LEAVES), Material.MANGROVE_PROPAGULE);
68 }
69
70 private void register(String name, Set<Material> logTypes, Set<Material> leafTypes, Material sapling) {
71 Species species = new Species(name, EnumSet.copyOf(logTypes), EnumSet.copyOf(leafTypes), sapling);
72 for (Material log : logTypes) {
73 logs.add(log);
74 byLog.computeIfAbsent(log, ignored -> new HashSet<>()).add(species);
75 }
76 }
77
78 boolean isLog(Material material) {
79 return logs.contains(material);
80 }
81
82 Set<Species> speciesForLog(Material material) {
83 Set<Species> species = byLog.get(material);
84 return species == null ? Set.of() : species;
85 }
86
87 Set<Material> leavesForLog(Material log) {
88 EnumSet<Material> leaves = EnumSet.noneOf(Material.class);
89 for (Species species : speciesForLog(log)) leaves.addAll(species.leaves());
90 return leaves;
91 }
92
93 Species classify(Material log, Set<Material> seenLeaves) {
94 Set<Species> candidates = speciesForLog(log);
95 if (candidates.isEmpty()) return null;
96 Species best = null;
97 int bestScore = -1;
98 for (Species species : candidates) {
99 int score = 0;
100 for (Material leaf : seenLeaves) {
101 if (species.isLeaf(leaf)) score++;
102 }
103 if (score > bestScore) {
104 bestScore = score;
105 best = species;
106 }
107 }
108 return bestScore > 0 ? best : null;
109 }
110
111 boolean isNaturalLeaf(Block block, Set<Material> allowedLeaves) {
112 if (!allowedLeaves.contains(block.getType())) return false;
113 return block.getBlockData() instanceof Leaves leaves && !leaves.isPersistent();
114 }
115
116 boolean isValidSoil(Material material) {
117 return SOILS.contains(material);
118 }
119
120 boolean isAllowedHorizontal(Material neighbour, Material log, Set<Material> allowedLeaves, Block neighbourBlock) {
121 if (neighbour.isAir()) return true;
122 if (neighbour == log) return true;
123 if (CLUTTER.contains(neighbour)) return true;
124 if (allowedLeaves.contains(neighbour)) {
125 return neighbourBlock.getBlockData() instanceof Leaves leaves && !leaves.isPersistent();
126 }
127 return false;
128 }
129
130 boolean canPlantAt(Block space, Species species) {
131 if (space == null || !space.getType().isAir() || species == null) return false;
132 return isValidSoil(space.getRelative(BlockFace.DOWN).getType());
133 }
134
135}
src/main/java/nl/timfalken/copperfarmer/WorkerRole.java added +24 −0
@@ -0,0 +1,24 @@
1 package nl.timfalken.copperfarmer;
2
3 import org.bukkit.Material;
4
5 enum WorkerRole {
6 FARMER("Copper Farmer Golem", Material.COPPER_HOE),
7 LUMBERER("Copper Lumberer Golem", Material.COPPER_AXE);
8
9 private final String displayName;
10 private final Material toolType;
11
12 WorkerRole(String displayName, Material toolType) {
13 this.displayName = displayName;
14 this.toolType = toolType;
15 }
16
17 String displayName() {
18 return displayName;
19 }
20
21 Material toolType() {
22 return toolType;
23 }
24 }
@@ -0,0 +1,24 @@
1package nl.timfalken.copperfarmer;
2
3import org.bukkit.Material;
4
5enum WorkerRole {
6 FARMER("Copper Farmer Golem", Material.COPPER_HOE),
7 LUMBERER("Copper Lumberer Golem", Material.COPPER_AXE);
8
9 private final String displayName;
10 private final Material toolType;
11
12 WorkerRole(String displayName, Material toolType) {
13 this.displayName = displayName;
14 this.toolType = toolType;
15 }
16
17 String displayName() {
18 return displayName;
19 }
20
21 Material toolType() {
22 return toolType;
23 }
24}
src/main/resources/config.yml +19 −0
@@ -51,3 +51,22 @@ cargo-slots: 9
51 51 # When true, farmers are kept waxed so they never weather into statues.
52 52 # Leave false for vanilla oxidation, honeycomb waxing and axe scraping.
53 53 prevent-oxidation: false
54
55 # Lumberer tree scan: columns processed per scanning chunk per brain tick.
56 tree-scan-columns-per-tick: 32
57
58 # Max tree detections (flood-fills) per scanning chunk per brain tick.
59 tree-detects-per-tick: 2
60
61 # How many chunks may be scanned in the same tick.
62 tree-scan-max-chunks-per-tick: 2
63
64 # Refuse trees larger than this many logs (also caps mega-jungle / merged trunks).
65 tree-max-logs: 64
66
67 # Leaf blocks visited while looking for diagonal branches.
68 tree-max-leaf-visits: 128
69
70 # How far above the no-leaves heightmap a column is checked for a trunk.
71 # Columns are never scanned downward into stone/ore.
72 tree-scan-above-ground: 40
@@ -51,3 +51,22 @@ cargo-slots: 9
51# When true, farmers are kept waxed so they never weather into statues.
51# When true, farmers are kept waxed so they never weather into statues.
52# Leave false for vanilla oxidation, honeycomb waxing and axe scraping.
52# Leave false for vanilla oxidation, honeycomb waxing and axe scraping.
53prevent-oxidation: false
53prevent-oxidation: false
54
55# Lumberer tree scan: columns processed per scanning chunk per brain tick.
56tree-scan-columns-per-tick: 32
57
58# Max tree detections (flood-fills) per scanning chunk per brain tick.
59tree-detects-per-tick: 2
60
61# How many chunks may be scanned in the same tick.
62tree-scan-max-chunks-per-tick: 2
63
64# Refuse trees larger than this many logs (also caps mega-jungle / merged trunks).
65tree-max-logs: 64
66
67# Leaf blocks visited while looking for diagonal branches.
68tree-max-leaf-visits: 128
69
70# How far above the no-leaves heightmap a column is checked for a trunk.
71# Columns are never scanned downward into stone/ore.
72tree-scan-above-ground: 40