Initial commit
@@ -0,0 +1,38 @@
1
---
2
description: Release-tag format, when to create tags, and what the GitLab release pipeline does
3
alwaysApply: true
4
---
5
6
# Release tags (ContainerPipes)
7
8
## Tag format
9
10
- Allowed: `X.Y.Z` or `vX.Y.Z` (digits only, no prerelease suffix).
11
- Valid: `1.7.0`, `v1.7.0`, `1.7.10`, `1.8.0`
12
- Invalid: `1.7`, `v1.7.0-beta`, `release-1.7.0`, `1.07.0` (no leading zeros in a segment)
13
14
## Creating a release
15
16
1. Ensure release-related changes are on `master` and pushed.
17
2. Create the tag on the intended commit (usually `HEAD` of `master`).
18
3. Push only the new tag: `git push origin <tag>`.
19
4. Do **not** force-update or move an existing protected tag. If a retry is needed on the same version, delete the tag in the GitLab UI first, then recreate it.
20
21
The new version must be **strictly greater** than the previous release tag (semver compare). The pipeline fails otherwise.
22
23
## What the pipeline does on a version tag
24
25
Triggered by `.gitlab-ci.yml` when any tag is pushed:
26
27
1. **validate** — check format and that the version is newer than prior release tags
28
2. **bump** — set version in project files (`build.gradle.kts`, `plugin.yml`, READMEs, plugin log string), commit, push to default branch with `ci.skip` (tag is **not** moved; protected tags cannot be updated)
29
3. **build** — produce `ContainerPipes-<version>.jar`, upload to Package Registry
30
4. **release** — publish a GitLab Release with that jar
31
5. **rotate-token** — self-rotate `CI_PUSH_TOKEN` and write it back to CI/CD variables
32
33
## Agent do / don't
34
35
- Do create/push a **new** version tag when the user asks to release or retag after they deleted the old tag.
36
- Do not rewrite/force-push protected tags; ask the user to delete via GitLab UI first.
37
- Do not invent non-semver tags for releases.
38
- After a failed release fix, push the fix to `master`, then recreate the version tag only if the remote tag is gone (or the user deleted it).
@@ -0,0 +1,38 @@1
---2
description: Release-tag format, when to create tags, and what the GitLab release pipeline does3
alwaysApply: true4
---5
6
# Release tags (ContainerPipes)7
8
## Tag format9
10
- Allowed: `X.Y.Z` or `vX.Y.Z` (digits only, no prerelease suffix).11
- Valid: `1.7.0`, `v1.7.0`, `1.7.10`, `1.8.0`12
- Invalid: `1.7`, `v1.7.0-beta`, `release-1.7.0`, `1.07.0` (no leading zeros in a segment)13
14
## Creating a release15
16
1. Ensure release-related changes are on `master` and pushed.17
2. Create the tag on the intended commit (usually `HEAD` of `master`).18
3. Push only the new tag: `git push origin <tag>`.19
4. Do **not** force-update or move an existing protected tag. If a retry is needed on the same version, delete the tag in the GitLab UI first, then recreate it.20
21
The new version must be **strictly greater** than the previous release tag (semver compare). The pipeline fails otherwise.22
23
## What the pipeline does on a version tag24
25
Triggered by `.gitlab-ci.yml` when any tag is pushed:26
27
1. **validate** — check format and that the version is newer than prior release tags28
2. **bump** — set version in project files (`build.gradle.kts`, `plugin.yml`, READMEs, plugin log string), commit, push to default branch with `ci.skip` (tag is **not** moved; protected tags cannot be updated)29
3. **build** — produce `ContainerPipes-<version>.jar`, upload to Package Registry30
4. **release** — publish a GitLab Release with that jar31
5. **rotate-token** — self-rotate `CI_PUSH_TOKEN` and write it back to CI/CD variables32
33
## Agent do / don't34
35
- Do create/push a **new** version tag when the user asks to release or retag after they deleted the old tag.36
- Do not rewrite/force-push protected tags; ask the user to delete via GitLab UI first.37
- Do not invent non-semver tags for releases.38
- After a failed release fix, push the fix to `master`, then recreate the version tag only if the remote tag is gone (or the user deleted it).@@ -0,0 +1,120 @@
1
# Release pipeline: runs when a version tag is created (e.g. v1.8.0 or 1.8.0).
2
#
3
# Required CI/CD variable:
4
# CI_PUSH_TOKEN — Project Access Token (Maintainer) with scopes:
5
# `write_repository`, `self_rotate` (or `api`), and `api`
6
# (api is required to write the rotated token back to this variable).
7
#
8
# Flow:
9
# 1. validate — reject invalid or non-increasing versions
10
# 2. bump — update version in project files and push commit (ci.skip; tag unchanged)
11
# 3. build — produce ContainerPipes-<version>.jar and upload to Package Registry
12
# 4. release — publish a GitLab Release with the jar attached
13
# 5. rotate-token — self-rotate CI_PUSH_TOKEN and update the CI/CD variable
14
15
workflow:
16
rules:
17
- if: $CI_COMMIT_TAG
18
19
variables:
20
GIT_DEPTH: "0"
21
GIT_FETCH_EXTRA_FLAGS: "--tags"
22
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
23
24
stages:
25
- validate
26
- bump
27
- build
28
- release
29
- rotate
30
31
.validate_image:
32
image: alpine:3.20
33
before_script:
34
- apk add --no-cache bash git grep coreutils
35
- git fetch --tags --force origin
36
- chmod +x scripts/release.sh
37
38
validate:version:
39
extends: .validate_image
40
stage: validate
41
script:
42
- ./scripts/release.sh validate
43
artifacts:
44
reports:
45
dotenv: version.env
46
paths:
47
- version.env
48
49
bump:version:
50
extends: .validate_image
51
stage: bump
52
needs:
53
- job: validate:version
54
artifacts: true
55
script:
56
- ./scripts/release.sh bump
57
artifacts:
58
reports:
59
dotenv: version.env
60
paths:
61
- version.env
62
- build.gradle.kts
63
- src/main/resources/plugin.yml
64
- README.md
65
- src/README-*.md
66
- src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java
67
68
build:jar:
69
stage: build
70
image: gradle:jdk25
71
needs:
72
- job: bump:version
73
artifacts: true
74
before_script:
75
- apt-get update -qq && apt-get install -y -qq curl >/dev/null
76
- chmod +x scripts/release.sh
77
# Checkout may still contain a previous src/README-*.md; keep only the bumped one.
78
- find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
79
script:
80
- test -n "${VERSION}"
81
- gradle --no-daemon clean jar
82
- test -f "build/libs/ContainerPipes-${VERSION}.jar"
83
- ls -la "build/libs/ContainerPipes-${VERSION}.jar"
84
- ./scripts/release.sh upload
85
artifacts:
86
reports:
87
dotenv: version.env
88
paths:
89
- "build/libs/ContainerPipes-*.jar"
90
- version.env
91
expire_in: 30 days
92
93
release:gitlab:
94
stage: release
95
image: registry.gitlab.com/gitlab-org/release-cli:latest
96
needs:
97
- job: build:jar
98
artifacts: true
99
script:
100
- echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
101
release:
102
name: "ContainerPipes $VERSION"
103
tag_name: "$TAG"
104
description: "Release $VERSION of ContainerPipes."
105
assets:
106
links:
107
- name: "ContainerPipes-$VERSION.jar"
108
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/containerpipes/$VERSION/ContainerPipes-$VERSION.jar"
109
link_type: package
110
111
rotate:push-token:
112
image: alpine:3.20
113
stage: rotate
114
needs:
115
- job: release:gitlab
116
before_script:
117
- apk add --no-cache bash curl jq coreutils
118
- chmod +x scripts/release.sh
119
script:
120
- ./scripts/release.sh rotate-token
@@ -0,0 +1,120 @@1
# Release pipeline: runs when a version tag is created (e.g. v1.8.0 or 1.8.0).2
#3
# Required CI/CD variable:4
# CI_PUSH_TOKEN — Project Access Token (Maintainer) with scopes:5
# `write_repository`, `self_rotate` (or `api`), and `api`6
# (api is required to write the rotated token back to this variable).7
#8
# Flow:9
# 1. validate — reject invalid or non-increasing versions10
# 2. bump — update version in project files and push commit (ci.skip; tag unchanged)11
# 3. build — produce ContainerPipes-<version>.jar and upload to Package Registry12
# 4. release — publish a GitLab Release with the jar attached13
# 5. rotate-token — self-rotate CI_PUSH_TOKEN and update the CI/CD variable14
15
workflow:16
rules:17
- if: $CI_COMMIT_TAG18
19
variables:20
GIT_DEPTH: "0"21
GIT_FETCH_EXTRA_FLAGS: "--tags"22
GRADLE_OPTS: "-Dorg.gradle.daemon=false"23
24
stages:25
- validate26
- bump27
- build28
- release29
- rotate30
31
.validate_image:32
image: alpine:3.2033
before_script:34
- apk add --no-cache bash git grep coreutils35
- git fetch --tags --force origin36
- chmod +x scripts/release.sh37
38
validate:version:39
extends: .validate_image40
stage: validate41
script:42
- ./scripts/release.sh validate43
artifacts:44
reports:45
dotenv: version.env46
paths:47
- version.env48
49
bump:version:50
extends: .validate_image51
stage: bump52
needs:53
- job: validate:version54
artifacts: true55
script:56
- ./scripts/release.sh bump57
artifacts:58
reports:59
dotenv: version.env60
paths:61
- version.env62
- build.gradle.kts63
- src/main/resources/plugin.yml64
- README.md65
- src/README-*.md66
- src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java67
68
build:jar:69
stage: build70
image: gradle:jdk2571
needs:72
- job: bump:version73
artifacts: true74
before_script:75
- apt-get update -qq && apt-get install -y -qq curl >/dev/null76
- chmod +x scripts/release.sh77
# Checkout may still contain a previous src/README-*.md; keep only the bumped one.78
- find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete79
script:80
- test -n "${VERSION}"81
- gradle --no-daemon clean jar82
- test -f "build/libs/ContainerPipes-${VERSION}.jar"83
- ls -la "build/libs/ContainerPipes-${VERSION}.jar"84
- ./scripts/release.sh upload85
artifacts:86
reports:87
dotenv: version.env88
paths:89
- "build/libs/ContainerPipes-*.jar"90
- version.env91
expire_in: 30 days92
93
release:gitlab:94
stage: release95
image: registry.gitlab.com/gitlab-org/release-cli:latest96
needs:97
- job: build:jar98
artifacts: true99
script:100
- echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"101
release:102
name: "ContainerPipes $VERSION"103
tag_name: "$TAG"104
description: "Release $VERSION of ContainerPipes."105
assets:106
links:107
- name: "ContainerPipes-$VERSION.jar"108
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/containerpipes/$VERSION/ContainerPipes-$VERSION.jar"109
link_type: package110
111
rotate:push-token:112
image: alpine:3.20113
stage: rotate114
needs:115
- job: release:gitlab116
before_script:117
- apk add --no-cache bash curl jq coreutils118
- chmod +x scripts/release.sh119
script:120
- ./scripts/release.sh rotate-token@@ -0,0 +1,80 @@
1
# CopperFarmer 0.1.0
2
3
First-version Paper 26.2 / Java 25 plugin for autonomous Copper Farmer Golems.
4
5
## Crafting
6
7
Shapeless recipe:
8
9
- 1x Copper Golem Statue
10
- 1x Copper Hoe
11
- -> 1x **Copper Farmer Golem** statue
12
13
For player crafting and vanilla Crafters, the output stores the **exact Copper Hoe used in the recipe** (one item), including its durability, enchantments, name and other item data. That stored hoe is equipped on the golem, used as the tool for crop loot calculation, and returned on death.
14
15
Placing the special statue consumes it normally and replaces that placed statue with a tagged real `CopperGolem` on the next tick. All vanilla goals are removed. Minecraft/Paper's native Pathfinder remains responsible for navigation.
16
17
## Farming behaviour
18
19
1. Bind the nearest **loaded** copper chest within the configured chunk radius (default: 2 chunks).
20
2. Every 10 seconds while idle, scan within 15 blocks of that chest for a mature supported crop.
21
3. Pick a standable work position next to the crop and ask the native Pathfinder to navigate there.
22
4. Let vanilla keep/follow the path. If the golem stops making progress or loses its path, request one fresh path; failed targets receive a cooldown.
23
5. At the crop, calculate its loot using `Block#getDrops(storedCopperHoe, golem)`.
24
6. Put the calculated drops into persistent internal cargo, then remove the crop block.
25
7. Replant from a seed/crop already in cargo. If none exists, try **one** cached crop-to-seed crafting conversion.
26
8. For farmland crops, use remaining seeds on connected empty farmland, navigating to each planting point.
27
9. Return to the bound copper chest and deposit the cargo.
28
10. If the chest is full, keep leftovers and retry later. If the chest disappears or proves unreachable, search for another chest.
29
11. On death, drop the exact construction hoe and every item still in persistent cargo.
30
31
## Supported crops in 0.1.0
32
33
- Wheat
34
- Carrots
35
- Potatoes
36
- Beetroot
37
- Nether Wart
38
- Cocoa
39
- Sweet Berry Bushes
40
- Torchflowers
41
- Melons — fruit only; attached stem is left intact
42
- Pumpkins — fruit only; attached stem is left intact
43
44
The crop registry is isolated from the state machine, so more vanilla/Matcha-specific crop handlers can be added later without rewriting navigation or chest logic. Pitcher crops, cave vines, sugar cane and bamboo are deliberately not special-cased in this first version because their harvest/replant rules differ from a normal single-block ageable crop.
45
46
## Seed recipe cache
47
48
The cache is built **once on the first server tick after plugin enable**. During normal startup, that is after other plugins have had their `onEnable()`, so their registered recipes are included as well.
49
50
A shaped/shapeless recipe is cached when:
51
52
- its result is a seed item used by a registered crop;
53
- every occupied ingredient slot can be satisfied by the **same input material**.
54
55
For shaped recipes, repeated shape cells are counted individually. This deliberately recognises crop/item -> seed conversions without turning the farmer into a general autocrafter.
56
57
The farmer never searches the recipe registry while working. Recipe changes after this cache is built are intentionally ignored until CopperFarmer/server restart or reload.
58
59
## Persistence and behaviour notes
60
61
- Farmer identity, bound chest, exact construction hoe and cargo are stored in PDC.
62
- Cargo uses Paper's NBT ItemStack byte serialization, so arbitrary item metadata survives chunk unloads/restarts.
63
- Only loaded chunks are searched; CopperFarmer never force-loads chunks.
64
- Internal cargo defaults to 9 stacks. If a datapack produces an unusually huge single harvest that cannot fit, only the overflow is dropped at the crop rather than deleted.
65
- Farmer Copper Golems are internally kept waxed by default (`prevent-oxidation: true`) so they do not eventually oxidise out of service. This is configurable.
66
- The golem swings its main hand when harvesting/planting. Whether the Copper Golem client renderer visibly renders held equipment is client-side; the equipment slot itself is populated regardless.
67
- No fake player `BlockBreakEvent` is generated. Loot is calculated from the real block loot table with the stored hoe and farmer golem as context.
68
- The stored construction hoe is not damaged by farming in 0.1.0; it is used as loot/tool context only.
69
70
## Build
71
72
The project targets the official Paper 26.2 API build `26.2.build.112-stable` and Java 25.
73
74
With Gradle installed:
75
76
```bash
77
gradle build
78
```
79
80
The resulting JAR will be under `build/libs/`.
@@ -0,0 +1,80 @@1
# CopperFarmer 0.1.02
3
First-version Paper 26.2 / Java 25 plugin for autonomous Copper Farmer Golems.4
5
## Crafting6
7
Shapeless recipe:8
9
- 1x Copper Golem Statue10
- 1x Copper Hoe11
- -> 1x **Copper Farmer Golem** statue12
13
For player crafting and vanilla Crafters, the output stores the **exact Copper Hoe used in the recipe** (one item), including its durability, enchantments, name and other item data. That stored hoe is equipped on the golem, used as the tool for crop loot calculation, and returned on death.14
15
Placing the special statue consumes it normally and replaces that placed statue with a tagged real `CopperGolem` on the next tick. All vanilla goals are removed. Minecraft/Paper's native Pathfinder remains responsible for navigation.16
17
## Farming behaviour18
19
1. Bind the nearest **loaded** copper chest within the configured chunk radius (default: 2 chunks).20
2. Every 10 seconds while idle, scan within 15 blocks of that chest for a mature supported crop.21
3. Pick a standable work position next to the crop and ask the native Pathfinder to navigate there.22
4. Let vanilla keep/follow the path. If the golem stops making progress or loses its path, request one fresh path; failed targets receive a cooldown.23
5. At the crop, calculate its loot using `Block#getDrops(storedCopperHoe, golem)`.24
6. Put the calculated drops into persistent internal cargo, then remove the crop block.25
7. Replant from a seed/crop already in cargo. If none exists, try **one** cached crop-to-seed crafting conversion.26
8. For farmland crops, use remaining seeds on connected empty farmland, navigating to each planting point.27
9. Return to the bound copper chest and deposit the cargo.28
10. If the chest is full, keep leftovers and retry later. If the chest disappears or proves unreachable, search for another chest.29
11. On death, drop the exact construction hoe and every item still in persistent cargo.30
31
## Supported crops in 0.1.032
33
- Wheat34
- Carrots35
- Potatoes36
- Beetroot37
- Nether Wart38
- Cocoa39
- Sweet Berry Bushes40
- Torchflowers41
- Melons — fruit only; attached stem is left intact42
- Pumpkins — fruit only; attached stem is left intact43
44
The crop registry is isolated from the state machine, so more vanilla/Matcha-specific crop handlers can be added later without rewriting navigation or chest logic. Pitcher crops, cave vines, sugar cane and bamboo are deliberately not special-cased in this first version because their harvest/replant rules differ from a normal single-block ageable crop.45
46
## Seed recipe cache47
48
The cache is built **once on the first server tick after plugin enable**. During normal startup, that is after other plugins have had their `onEnable()`, so their registered recipes are included as well.49
50
A shaped/shapeless recipe is cached when:51
52
- its result is a seed item used by a registered crop;53
- every occupied ingredient slot can be satisfied by the **same input material**.54
55
For shaped recipes, repeated shape cells are counted individually. This deliberately recognises crop/item -> seed conversions without turning the farmer into a general autocrafter.56
57
The farmer never searches the recipe registry while working. Recipe changes after this cache is built are intentionally ignored until CopperFarmer/server restart or reload.58
59
## Persistence and behaviour notes60
61
- Farmer identity, bound chest, exact construction hoe and cargo are stored in PDC.62
- Cargo uses Paper's NBT ItemStack byte serialization, so arbitrary item metadata survives chunk unloads/restarts.63
- Only loaded chunks are searched; CopperFarmer never force-loads chunks.64
- Internal cargo defaults to 9 stacks. If a datapack produces an unusually huge single harvest that cannot fit, only the overflow is dropped at the crop rather than deleted.65
- Farmer Copper Golems are internally kept waxed by default (`prevent-oxidation: true`) so they do not eventually oxidise out of service. This is configurable.66
- The golem swings its main hand when harvesting/planting. Whether the Copper Golem client renderer visibly renders held equipment is client-side; the equipment slot itself is populated regardless.67
- No fake player `BlockBreakEvent` is generated. Loot is calculated from the real block loot table with the stored hoe and farmer golem as context.68
- The stored construction hoe is not damaged by farming in 0.1.0; it is used as loot/tool context only.69
70
## Build71
72
The project targets the official Paper 26.2 API build `26.2.build.112-stable` and Java 25.73
74
With Gradle installed:75
76
```bash77
gradle build78
```79
80
The resulting JAR will be under `build/libs/`.@@ -0,0 +1,70 @@
1
# CopperFarmer 0.1.0 smoke test
2
3
Use this checklist on a Paper 26.2 server before treating 0.1.0 as production-ready.
4
5
## Startup
6
7
- [ ] Start the server with CopperFarmer installed and confirm there is no enable error.
8
- [ ] Confirm the log contains `Seed recipe cache:` once shortly after startup.
9
- [ ] Confirm the plugin does not repeatedly rebuild the recipe cache while the server is running.
10
11
## Crafting and placement
12
13
- [ ] Craft 1 Copper Golem Statue + 1 Copper Hoe and verify the result is named `Copper Farmer Golem`.
14
- [ ] Repeat with a damaged / renamed / enchanted Copper Hoe and verify those exact properties survive on the stored construction tool.
15
- [ ] Test the same recipe in a vanilla Crafter.
16
- [ ] Place the special statue and verify it becomes exactly one Copper Golem on the next tick.
17
- [ ] Place a normal Copper Golem Statue and verify CopperFarmer leaves it completely alone.
18
- [ ] Verify the farmer does not perform vanilla Copper Golem sorting/wandering behaviour.
19
- [ ] Verify the Copper Hoe is visibly rendered in the main hand. If not, the server-side equipment is still present; add an ItemDisplay visual in the next version.
20
21
## Chest binding
22
23
- [ ] Put two copper chests within the configured search area and verify the closest loaded one is selected.
24
- [ ] Put a closer chest in an unloaded chunk and verify CopperFarmer does not force-load that chunk.
25
- [ ] Break the bound chest while the farmer is carrying items and verify it searches for another copper chest.
26
- [ ] Make the bound chest unreachable and verify the farmer eventually abandons it after the configured path retries/cooldown.
27
- [ ] Fill the chest completely and verify the farmer keeps its cargo instead of dropping/deleting it.
28
29
## Crops
30
31
Test at least one full harvest/replant/deposit cycle for:
32
33
- [ ] Wheat
34
- [ ] Carrots
35
- [ ] Potatoes
36
- [ ] Beetroot
37
- [ ] Nether Wart
38
- [ ] Cocoa
39
- [ ] Sweet Berry Bushes
40
- [ ] Torchflowers
41
- [ ] Melon (fruit breaks; attached stem survives)
42
- [ ] Pumpkin (fruit breaks; attached stem survives)
43
44
Also verify:
45
46
- [ ] Immature crops are ignored.
47
- [ ] A mature but completely unreachable crop is not selected endlessly.
48
- [ ] The farmer tries alternative standable sides of a target before declaring it unreachable.
49
- [ ] Once a path is accepted, the farmer follows vanilla navigation rather than recalculating every brain tick.
50
- [ ] A changed obstruction causes a retry instead of permanently freezing the farmer.
51
52
## Seeds and expansion
53
54
- [ ] Normal seed/crop-as-seed replanting consumes exactly one appropriate item.
55
- [ ] If a supported crop has a shaped/shapeless crop-to-seed recipe, remove direct seed drops and verify the farmer crafts once and replants.
56
- [ ] If that recipe outputs multiple seeds, verify one is replanted and the remainder stays available for expansion/deposit.
57
- [ ] Verify repeated cells in a shaped recipe consume the correct ingredient count.
58
- [ ] Add/change a recipe after CopperFarmer's cache was built and verify it is ignored until restart/reload.
59
- [ ] Leave connected farmland empty and verify spare seeds are planted one reachable position at a time.
60
61
## Persistence and death
62
63
- [ ] Let the farmer carry cargo, unload/reload its chunk, and verify cargo + chest binding + construction tool survive.
64
- [ ] Restart the server while a farmer has cargo and verify the same state survives.
65
- [ ] Kill a farmer with cargo and verify its exact construction Copper Hoe and all cargo drop.
66
- [ ] Verify no duplicate construction hoe is produced by vanilla equipment drops.
67
68
## Weathering
69
70
- [ ] With `prevent-oxidation: true`, verify the farmer remains active and does not eventually weather back into a statue.
@@ -0,0 +1,70 @@1
# CopperFarmer 0.1.0 smoke test2
3
Use this checklist on a Paper 26.2 server before treating 0.1.0 as production-ready.4
5
## Startup6
7
- [ ] Start the server with CopperFarmer installed and confirm there is no enable error.8
- [ ] Confirm the log contains `Seed recipe cache:` once shortly after startup.9
- [ ] Confirm the plugin does not repeatedly rebuild the recipe cache while the server is running.10
11
## Crafting and placement12
13
- [ ] Craft 1 Copper Golem Statue + 1 Copper Hoe and verify the result is named `Copper Farmer Golem`.14
- [ ] Repeat with a damaged / renamed / enchanted Copper Hoe and verify those exact properties survive on the stored construction tool.15
- [ ] Test the same recipe in a vanilla Crafter.16
- [ ] Place the special statue and verify it becomes exactly one Copper Golem on the next tick.17
- [ ] Place a normal Copper Golem Statue and verify CopperFarmer leaves it completely alone.18
- [ ] Verify the farmer does not perform vanilla Copper Golem sorting/wandering behaviour.19
- [ ] Verify the Copper Hoe is visibly rendered in the main hand. If not, the server-side equipment is still present; add an ItemDisplay visual in the next version.20
21
## Chest binding22
23
- [ ] Put two copper chests within the configured search area and verify the closest loaded one is selected.24
- [ ] Put a closer chest in an unloaded chunk and verify CopperFarmer does not force-load that chunk.25
- [ ] Break the bound chest while the farmer is carrying items and verify it searches for another copper chest.26
- [ ] Make the bound chest unreachable and verify the farmer eventually abandons it after the configured path retries/cooldown.27
- [ ] Fill the chest completely and verify the farmer keeps its cargo instead of dropping/deleting it.28
29
## Crops30
31
Test at least one full harvest/replant/deposit cycle for:32
33
- [ ] Wheat34
- [ ] Carrots35
- [ ] Potatoes36
- [ ] Beetroot37
- [ ] Nether Wart38
- [ ] Cocoa39
- [ ] Sweet Berry Bushes40
- [ ] Torchflowers41
- [ ] Melon (fruit breaks; attached stem survives)42
- [ ] Pumpkin (fruit breaks; attached stem survives)43
44
Also verify:45
46
- [ ] Immature crops are ignored.47
- [ ] A mature but completely unreachable crop is not selected endlessly.48
- [ ] The farmer tries alternative standable sides of a target before declaring it unreachable.49
- [ ] Once a path is accepted, the farmer follows vanilla navigation rather than recalculating every brain tick.50
- [ ] A changed obstruction causes a retry instead of permanently freezing the farmer.51
52
## Seeds and expansion53
54
- [ ] Normal seed/crop-as-seed replanting consumes exactly one appropriate item.55
- [ ] If a supported crop has a shaped/shapeless crop-to-seed recipe, remove direct seed drops and verify the farmer crafts once and replants.56
- [ ] If that recipe outputs multiple seeds, verify one is replanted and the remainder stays available for expansion/deposit.57
- [ ] Verify repeated cells in a shaped recipe consume the correct ingredient count.58
- [ ] Add/change a recipe after CopperFarmer's cache was built and verify it is ignored until restart/reload.59
- [ ] Leave connected farmland empty and verify spare seeds are planted one reachable position at a time.60
61
## Persistence and death62
63
- [ ] Let the farmer carry cargo, unload/reload its chunk, and verify cargo + chest binding + construction tool survive.64
- [ ] Restart the server while a farmer has cargo and verify the same state survives.65
- [ ] Kill a farmer with cargo and verify its exact construction Copper Hoe and all cargo drop.66
- [ ] Verify no duplicate construction hoe is produced by vanilla equipment drops.67
68
## Weathering69
70
- [ ] With `prevent-oxidation: true`, verify the farmer remains active and does not eventually weather back into a statue.@@ -0,0 +1,27 @@
1
plugins {
2
java
3
}
4
5
group = "nl.timfalken"
6
version = "0.1.0"
7
8
repositories {
9
mavenCentral()
10
maven {
11
name = "papermc"
12
url = uri("https://repo.papermc.io/repository/maven-public/")
13
}
14
}
15
16
dependencies {
17
compileOnly("io.papermc.paper:paper-api:26.2.build.112-stable")
18
}
19
20
java {
21
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
22
}
23
24
tasks.withType<JavaCompile>().configureEach {
25
options.encoding = "UTF-8"
26
options.release.set(25)
27
}
@@ -0,0 +1,27 @@1
plugins {2
java3
}4
5
group = "nl.timfalken"6
version = "0.1.0"7
8
repositories {9
mavenCentral()10
maven {11
name = "papermc"12
url = uri("https://repo.papermc.io/repository/maven-public/")13
}14
}15
16
dependencies {17
compileOnly("io.papermc.paper:paper-api:26.2.build.112-stable")18
}19
20
java {21
toolchain.languageVersion.set(JavaLanguageVersion.of(25))22
}23
24
tasks.withType<JavaCompile>().configureEach {25
options.encoding = "UTF-8"26
options.release.set(25)27
}@@ -0,0 +1,232 @@
1
#!/usr/bin/env bash
2
# Release helpers for GitLab CI.
3
set -euo pipefail
4
5
VERSION_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
6
7
normalize_version() {
8
echo "${1#v}"
9
}
10
11
is_valid_version_tag() {
12
[[ "$1" =~ $VERSION_REGEX ]]
13
}
14
15
# True if $1 is strictly greater than $2 (semver X.Y.Z).
16
is_newer_version() {
17
local a b
18
a="$(normalize_version "$1")"
19
b="$(normalize_version "$2")"
20
[[ "$a" != "$b" ]] && [[ "$(printf '%s\n' "$a" "$b" | sort -V | tail -n1)" == "$a" ]]
21
}
22
23
write_version_env() {
24
local version="$1"
25
local tag="$2"
26
{
27
echo "VERSION=${version}"
28
echo "TAG=${tag}"
29
} > version.env
30
}
31
32
validate() {
33
local tag="${CI_COMMIT_TAG:?CI_COMMIT_TAG is required}"
34
local version newest
35
36
if ! is_valid_version_tag "$tag"; then
37
echo "ERROR: Tag '${tag}' has an invalid format."
38
echo "Expected: v1.7.0, 1.7.10, 1.8.0, ..."
39
exit 1
40
fi
41
42
version="$(normalize_version "$tag")"
43
echo "Validated release tag: ${tag} (version ${version})"
44
45
mapfile -t tags < <(
46
git tag -l \
47
| grep -E "$VERSION_REGEX" \
48
| grep -vxF "$tag" \
49
|| true
50
)
51
52
if ((${#tags[@]} == 0)); then
53
echo "No previous release tags found; accepting ${version} as first release."
54
write_version_env "$version" "$tag"
55
return 0
56
fi
57
58
newest="$(printf '%s\n' "${tags[@]}" | sed 's/^v//' | sort -V | tail -n1)"
59
echo "Previous release version: ${newest}"
60
61
if ! is_newer_version "$version" "$newest"; then
62
echo "ERROR: Release version ${version} is not greater than previous release ${newest}."
63
exit 1
64
fi
65
66
write_version_env "$version" "$tag"
67
echo "Version check passed: ${version} > ${newest}"
68
}
69
70
bump_files() {
71
local version="${1:?version required}"
72
local readme
73
74
sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts
75
sed -i "s/^version: '.*/version: '${version}'/" src/main/resources/plugin.yml
76
sed -i "1s/.*/# ContainerPipes ${version}/" README.md
77
sed -i -E "s/ContainerPipes [0-9]+\.[0-9]+\.[0-9]+ enabled/ContainerPipes ${version} enabled/" \
78
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java
79
80
shopt -s nullglob
81
for readme in src/README-*.md; do
82
sed -i "1s/.*/# ContainerPipes ${version}/" "$readme"
83
if [[ "$readme" != "src/README-${version}.md" ]]; then
84
git mv "$readme" "src/README-${version}.md"
85
fi
86
done
87
shopt -u nullglob
88
89
echo "Updated project files to version ${version}"
90
}
91
92
require_push_token() {
93
if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then
94
return 0
95
fi
96
97
cat <<'EOF' >&2
98
ERROR: CI_PUSH_TOKEN is not available in this job.
99
100
The variable may exist in Settings → CI/CD → Variables but still be hidden here if:
101
1. It is Protected, while this tag/branch is not protected
102
→ Protect tag pattern (e.g. *) or uncheck Protected on the variable
103
2. Its Environment scope is not "*"
104
3. The key is misspelled (must be exactly CI_PUSH_TOKEN)
105
106
EOF
107
exit 1
108
}
109
110
bump_and_push() {
111
local version="${1:?version required}"
112
local tag="${2:?tag required}"
113
local token branch
114
115
require_push_token
116
token="${CI_PUSH_TOKEN}"
117
branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
118
119
git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
120
git config user.name "GitLab CI"
121
122
bump_files "$version"
123
124
# Stage only versioned project files (never CI artifacts like version.env).
125
git add -- \
126
build.gradle.kts \
127
src/main/resources/plugin.yml \
128
README.md \
129
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java
130
git add -A -- src/README-*.md 2>/dev/null || true
131
132
if git diff --cached --quiet; then
133
echo "No version file changes to commit (already at ${version})."
134
else
135
git commit -m "chore: bump version to ${version}"
136
fi
137
138
git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
139
140
# Push version bump only. Protected tags cannot be moved/updated.
141
git push origin "HEAD:refs/heads/${branch}" -o ci.skip
142
143
echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."
144
}
145
146
upload_package() {
147
local version="${1:?version required}"
148
local jar="build/libs/ContainerPipes-${version}.jar"
149
local package_url
150
151
if [[ ! -f "$jar" ]]; then
152
echo "ERROR: Expected jar not found: ${jar}"
153
ls -la build/libs/ || true
154
exit 1
155
fi
156
157
package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/containerpipes/${version}/ContainerPipes-${version}.jar"
158
curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
159
--upload-file "$jar" \
160
"$package_url"
161
162
echo "Uploaded ${jar}"
163
echo "PACKAGE_URL=${package_url}" > package.env
164
}
165
166
# Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.
167
# Requires scopes: write_repository + self_rotate (or api), and api to update variables.
168
# Project access token role should be Maintainer (needed to edit CI/CD variables).
169
rotate_push_token() {
170
local old_token expires_at response new_token var_meta protected masked raw scope
171
172
require_push_token
173
old_token="${CI_PUSH_TOKEN}"
174
175
expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"
176
echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."
177
178
response="$(curl --fail --silent --show-error \
179
--request POST \
180
--header "PRIVATE-TOKEN: ${old_token}" \
181
--header "Content-Type: application/json" \
182
--data "{\"expires_at\":\"${expires_at}\"}" \
183
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"
184
185
new_token="$(jq -er '.token' <<<"${response}")"
186
if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then
187
echo "ERROR: Token rotation response did not include a new token."
188
echo "${response}"
189
exit 1
190
fi
191
192
var_meta="$(curl --fail --silent --show-error \
193
--header "PRIVATE-TOKEN: ${new_token}" \
194
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"
195
196
protected="$(jq -r '.protected' <<<"${var_meta}")"
197
masked="$(jq -r '.masked' <<<"${var_meta}")"
198
raw="$(jq -r '.raw // false' <<<"${var_meta}")"
199
scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"
200
201
curl --fail --silent --show-error \
202
--request PUT \
203
--header "PRIVATE-TOKEN: ${new_token}" \
204
--form "value=${new_token}" \
205
--form "protected=${protected}" \
206
--form "masked=${masked}" \
207
--form "raw=${raw}" \
208
--form "environment_scope=${scope}" \
209
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \
210
>/dev/null
211
212
echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."
213
}
214
215
case "${1:-}" in
216
validate) validate ;;
217
bump)
218
# shellcheck disable=SC1091
219
source version.env
220
bump_and_push "$VERSION" "$TAG"
221
;;
222
upload)
223
# shellcheck disable=SC1091
224
source version.env
225
upload_package "$VERSION"
226
;;
227
rotate-token) rotate_push_token ;;
228
*)
229
echo "Usage: $0 {validate|bump|upload|rotate-token}"
230
exit 1
231
;;
232
esac
@@ -0,0 +1,232 @@1
#!/usr/bin/env bash2
# Release helpers for GitLab CI.3
set -euo pipefail4
5
VERSION_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'6
7
normalize_version() {8
echo "${1#v}"9
}10
11
is_valid_version_tag() {12
[[ "$1" =~ $VERSION_REGEX ]]13
}14
15
# True if $1 is strictly greater than $2 (semver X.Y.Z).16
is_newer_version() {17
local a b18
a="$(normalize_version "$1")"19
b="$(normalize_version "$2")"20
[[ "$a" != "$b" ]] && [[ "$(printf '%s\n' "$a" "$b" | sort -V | tail -n1)" == "$a" ]]21
}22
23
write_version_env() {24
local version="$1"25
local tag="$2"26
{27
echo "VERSION=${version}"28
echo "TAG=${tag}"29
} > version.env30
}31
32
validate() {33
local tag="${CI_COMMIT_TAG:?CI_COMMIT_TAG is required}"34
local version newest35
36
if ! is_valid_version_tag "$tag"; then37
echo "ERROR: Tag '${tag}' has an invalid format."38
echo "Expected: v1.7.0, 1.7.10, 1.8.0, ..."39
exit 140
fi41
42
version="$(normalize_version "$tag")"43
echo "Validated release tag: ${tag} (version ${version})"44
45
mapfile -t tags < <(46
git tag -l \47
| grep -E "$VERSION_REGEX" \48
| grep -vxF "$tag" \49
|| true50
)51
52
if ((${#tags[@]} == 0)); then53
echo "No previous release tags found; accepting ${version} as first release."54
write_version_env "$version" "$tag"55
return 056
fi57
58
newest="$(printf '%s\n' "${tags[@]}" | sed 's/^v//' | sort -V | tail -n1)"59
echo "Previous release version: ${newest}"60
61
if ! is_newer_version "$version" "$newest"; then62
echo "ERROR: Release version ${version} is not greater than previous release ${newest}."63
exit 164
fi65
66
write_version_env "$version" "$tag"67
echo "Version check passed: ${version} > ${newest}"68
}69
70
bump_files() {71
local version="${1:?version required}"72
local readme73
74
sed -i "s/^version = \".*\"/version = \"${version}\"/" build.gradle.kts75
sed -i "s/^version: '.*/version: '${version}'/" src/main/resources/plugin.yml76
sed -i "1s/.*/# ContainerPipes ${version}/" README.md77
sed -i -E "s/ContainerPipes [0-9]+\.[0-9]+\.[0-9]+ enabled/ContainerPipes ${version} enabled/" \78
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java79
80
shopt -s nullglob81
for readme in src/README-*.md; do82
sed -i "1s/.*/# ContainerPipes ${version}/" "$readme"83
if [[ "$readme" != "src/README-${version}.md" ]]; then84
git mv "$readme" "src/README-${version}.md"85
fi86
done87
shopt -u nullglob88
89
echo "Updated project files to version ${version}"90
}91
92
require_push_token() {93
if [[ -n "${CI_PUSH_TOKEN:-}" ]]; then94
return 095
fi96
97
cat <<'EOF' >&298
ERROR: CI_PUSH_TOKEN is not available in this job.99
100
The variable may exist in Settings → CI/CD → Variables but still be hidden here if:101
1. It is Protected, while this tag/branch is not protected102
→ Protect tag pattern (e.g. *) or uncheck Protected on the variable103
2. Its Environment scope is not "*"104
3. The key is misspelled (must be exactly CI_PUSH_TOKEN)105
106
EOF107
exit 1108
}109
110
bump_and_push() {111
local version="${1:?version required}"112
local tag="${2:?tag required}"113
local token branch114
115
require_push_token116
token="${CI_PUSH_TOKEN}"117
branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"118
119
git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"120
git config user.name "GitLab CI"121
122
bump_files "$version"123
124
# Stage only versioned project files (never CI artifacts like version.env).125
git add -- \126
build.gradle.kts \127
src/main/resources/plugin.yml \128
README.md \129
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java130
git add -A -- src/README-*.md 2>/dev/null || true131
132
if git diff --cached --quiet; then133
echo "No version file changes to commit (already at ${version})."134
else135
git commit -m "chore: bump version to ${version}"136
fi137
138
git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"139
140
# Push version bump only. Protected tags cannot be moved/updated.141
git push origin "HEAD:refs/heads/${branch}" -o ci.skip142
143
echo "Pushed version bump for ${tag} to ${branch} (ci.skip). Tag left unchanged."144
}145
146
upload_package() {147
local version="${1:?version required}"148
local jar="build/libs/ContainerPipes-${version}.jar"149
local package_url150
151
if [[ ! -f "$jar" ]]; then152
echo "ERROR: Expected jar not found: ${jar}"153
ls -la build/libs/ || true154
exit 1155
fi156
157
package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/containerpipes/${version}/ContainerPipes-${version}.jar"158
curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \159
--upload-file "$jar" \160
"$package_url"161
162
echo "Uploaded ${jar}"163
echo "PACKAGE_URL=${package_url}" > package.env164
}165
166
# Self-rotate CI_PUSH_TOKEN and write the new value back to the CI/CD variable.167
# Requires scopes: write_repository + self_rotate (or api), and api to update variables.168
# Project access token role should be Maintainer (needed to edit CI/CD variables).169
rotate_push_token() {170
local old_token expires_at response new_token var_meta protected masked raw scope171
172
require_push_token173
old_token="${CI_PUSH_TOKEN}"174
175
expires_at="$(date -u -d '+365 days' +%Y-%m-%d)"176
echo "Rotating CI_PUSH_TOKEN (new expiry ${expires_at})..."177
178
response="$(curl --fail --silent --show-error \179
--request POST \180
--header "PRIVATE-TOKEN: ${old_token}" \181
--header "Content-Type: application/json" \182
--data "{\"expires_at\":\"${expires_at}\"}" \183
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/access_tokens/self/rotate")"184
185
new_token="$(jq -er '.token' <<<"${response}")"186
if [[ -z "${new_token}" || "${new_token}" == "null" ]]; then187
echo "ERROR: Token rotation response did not include a new token."188
echo "${response}"189
exit 1190
fi191
192
var_meta="$(curl --fail --silent --show-error \193
--header "PRIVATE-TOKEN: ${new_token}" \194
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN")"195
196
protected="$(jq -r '.protected' <<<"${var_meta}")"197
masked="$(jq -r '.masked' <<<"${var_meta}")"198
raw="$(jq -r '.raw // false' <<<"${var_meta}")"199
scope="$(jq -r '.environment_scope // "*"' <<<"${var_meta}")"200
201
curl --fail --silent --show-error \202
--request PUT \203
--header "PRIVATE-TOKEN: ${new_token}" \204
--form "value=${new_token}" \205
--form "protected=${protected}" \206
--form "masked=${masked}" \207
--form "raw=${raw}" \208
--form "environment_scope=${scope}" \209
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/variables/CI_PUSH_TOKEN" \210
>/dev/null211
212
echo "CI_PUSH_TOKEN rotated and CI/CD variable updated."213
}214
215
case "${1:-}" in216
validate) validate ;;217
bump)218
# shellcheck disable=SC1091219
source version.env220
bump_and_push "$VERSION" "$TAG"221
;;222
upload)223
# shellcheck disable=SC1091224
source version.env225
upload_package "$VERSION"226
;;227
rotate-token) rotate_push_token ;;228
*)229
echo "Usage: $0 {validate|bump|upload|rotate-token}"230
exit 1231
;;232
esac@@ -0,0 +1 @@
1
rootProject.name = "CopperFarmer"
@@ -0,0 +1 @@1
rootProject.name = "CopperFarmer"@@ -0,0 +1,68 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.Bukkit;
4
import org.bukkit.Material;
5
import org.bukkit.World;
6
import org.bukkit.entity.CopperGolem;
7
import org.bukkit.entity.Entity;
8
import org.bukkit.inventory.ItemStack;
9
import org.bukkit.inventory.ShapelessRecipe;
10
import org.bukkit.plugin.java.JavaPlugin;
11
import org.bukkit.scheduler.BukkitTask;
12
13
public final class CopperFarmerPlugin extends JavaPlugin {
14
private FarmerKeys keys;
15
private CropRegistry crops;
16
private FarmerItemCodec itemCodec;
17
private SeedRecipeCache seedRecipes;
18
private FarmerManager manager;
19
private BukkitTask brainTask;
20
21
@Override
22
public void onEnable() {
23
saveDefaultConfig();
24
25
keys = new FarmerKeys(this);
26
crops = new CropRegistry();
27
itemCodec = new FarmerItemCodec(keys);
28
registerFarmerRecipe();
29
30
seedRecipes = new SeedRecipeCache(this, crops.seedMaterials());
31
32
manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec);
33
getServer().getPluginManager().registerEvents(new FarmerListener(this, keys, manager, itemCodec), this);
34
35
// Register tagged golems that were already loaded before this plugin enabled.
36
for (World world : Bukkit.getWorlds()) {
37
for (Entity entity : world.getEntities()) {
38
if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) manager.register(golem);
39
}
40
}
41
42
// Run once on the first server tick. During a normal startup this is after
43
// every plugin has had its onEnable(), so recipes registered by other
44
// plugins are included too. The cache is intentionally not refreshed at
45
// runtime; restart/reload CopperFarmer to rebuild it.
46
getServer().getScheduler().runTask(this, seedRecipes::build);
47
48
long interval = Math.max(1L, getConfig().getLong("brain-tick-interval", 5L));
49
brainTask = getServer().getScheduler().runTaskTimer(this, () -> manager.tick(interval), interval, interval);
50
51
getLogger().info("CopperFarmer 0.1.0 enabled for Paper 26.2.");
52
}
53
54
@Override
55
public void onDisable() {
56
if (brainTask != null) brainTask.cancel();
57
}
58
59
private void registerFarmerRecipe() {
60
Bukkit.removeRecipe(keys.recipe);
61
ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE));
62
ShapelessRecipe recipe = new ShapelessRecipe(keys.recipe, result);
63
recipe.addIngredient(Material.COPPER_GOLEM_STATUE);
64
recipe.addIngredient(Material.COPPER_HOE);
65
Bukkit.addRecipe(recipe);
66
}
67
68
}
@@ -0,0 +1,68 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.Bukkit;4
import org.bukkit.Material;5
import org.bukkit.World;6
import org.bukkit.entity.CopperGolem;7
import org.bukkit.entity.Entity;8
import org.bukkit.inventory.ItemStack;9
import org.bukkit.inventory.ShapelessRecipe;10
import org.bukkit.plugin.java.JavaPlugin;11
import org.bukkit.scheduler.BukkitTask;12
13
public final class CopperFarmerPlugin extends JavaPlugin {14
private FarmerKeys keys;15
private CropRegistry crops;16
private FarmerItemCodec itemCodec;17
private SeedRecipeCache seedRecipes;18
private FarmerManager manager;19
private BukkitTask brainTask;20
21
@Override22
public void onEnable() {23
saveDefaultConfig();24
25
keys = new FarmerKeys(this);26
crops = new CropRegistry();27
itemCodec = new FarmerItemCodec(keys);28
registerFarmerRecipe();29
30
seedRecipes = new SeedRecipeCache(this, crops.seedMaterials());31
32
manager = new FarmerManager(this, keys, crops, seedRecipes, itemCodec);33
getServer().getPluginManager().registerEvents(new FarmerListener(this, keys, manager, itemCodec), this);34
35
// Register tagged golems that were already loaded before this plugin enabled.36
for (World world : Bukkit.getWorlds()) {37
for (Entity entity : world.getEntities()) {38
if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) manager.register(golem);39
}40
}41
42
// Run once on the first server tick. During a normal startup this is after43
// every plugin has had its onEnable(), so recipes registered by other44
// plugins are included too. The cache is intentionally not refreshed at45
// runtime; restart/reload CopperFarmer to rebuild it.46
getServer().getScheduler().runTask(this, seedRecipes::build);47
48
long interval = Math.max(1L, getConfig().getLong("brain-tick-interval", 5L));49
brainTask = getServer().getScheduler().runTaskTimer(this, () -> manager.tick(interval), interval, interval);50
51
getLogger().info("CopperFarmer 0.1.0 enabled for Paper 26.2.");52
}53
54
@Override55
public void onDisable() {56
if (brainTask != null) brainTask.cancel();57
}58
59
private void registerFarmerRecipe() {60
Bukkit.removeRecipe(keys.recipe);61
ItemStack result = itemCodec.createStatue(new ItemStack(Material.COPPER_HOE));62
ShapelessRecipe recipe = new ShapelessRecipe(keys.recipe, result);63
recipe.addIngredient(Material.COPPER_GOLEM_STATUE);64
recipe.addIngredient(Material.COPPER_HOE);65
Bukkit.addRecipe(recipe);66
}67
68
}@@ -0,0 +1,73 @@
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.Ageable;
7
8
import java.util.Collection;
9
import java.util.EnumMap;
10
import java.util.EnumSet;
11
import java.util.Map;
12
import java.util.Set;
13
14
final class CropRegistry {
15
record Crop(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {}
16
17
private final Map<Material, Crop> crops = new EnumMap<>(Material.class);
18
private final Set<Material> seedMaterials = EnumSet.noneOf(Material.class);
19
20
CropRegistry() {
21
register(Material.WHEAT, Material.WHEAT_SEEDS, true, false);
22
register(Material.CARROTS, Material.CARROT, true, false);
23
register(Material.POTATOES, Material.POTATO, true, false);
24
register(Material.BEETROOTS, Material.BEETROOT_SEEDS, true, false);
25
register(Material.NETHER_WART, Material.NETHER_WART, false, false);
26
register(Material.COCOA, Material.COCOA_BEANS, false, false);
27
register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, false, false);
28
register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, true, false);
29
register(Material.MELON, Material.MELON_SEEDS, false, true);
30
register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, false, true);
31
}
32
33
private void register(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {
34
Crop crop = new Crop(block, seed, farmland, breakOnlyFruit);
35
crops.put(block, crop);
36
seedMaterials.add(seed);
37
}
38
39
Crop get(Material material) {
40
return crops.get(material);
41
}
42
43
Collection<Crop> all() {
44
return crops.values();
45
}
46
47
Set<Material> seedMaterials() {
48
return Set.copyOf(seedMaterials);
49
}
50
51
boolean isReady(Block block) {
52
Crop crop = get(block.getType());
53
if (crop == null) return false;
54
55
if (crop.breakOnlyFruit()) {
56
return hasAttachedStem(block, crop.block() == Material.MELON
57
? Material.ATTACHED_MELON_STEM
58
: Material.ATTACHED_PUMPKIN_STEM);
59
}
60
61
if (block.getBlockData() instanceof Ageable ageable) {
62
return ageable.getAge() >= ageable.getMaximumAge();
63
}
64
return false;
65
}
66
67
private boolean hasAttachedStem(Block fruit, Material attachedStem) {
68
for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
69
if (fruit.getRelative(face).getType() == attachedStem) return true;
70
}
71
return false;
72
}
73
}
@@ -0,0 +1,73 @@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.Ageable;7
8
import java.util.Collection;9
import java.util.EnumMap;10
import java.util.EnumSet;11
import java.util.Map;12
import java.util.Set;13
14
final class CropRegistry {15
record Crop(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {}16
17
private final Map<Material, Crop> crops = new EnumMap<>(Material.class);18
private final Set<Material> seedMaterials = EnumSet.noneOf(Material.class);19
20
CropRegistry() {21
register(Material.WHEAT, Material.WHEAT_SEEDS, true, false);22
register(Material.CARROTS, Material.CARROT, true, false);23
register(Material.POTATOES, Material.POTATO, true, false);24
register(Material.BEETROOTS, Material.BEETROOT_SEEDS, true, false);25
register(Material.NETHER_WART, Material.NETHER_WART, false, false);26
register(Material.COCOA, Material.COCOA_BEANS, false, false);27
register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, false, false);28
register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, true, false);29
register(Material.MELON, Material.MELON_SEEDS, false, true);30
register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, false, true);31
}32
33
private void register(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {34
Crop crop = new Crop(block, seed, farmland, breakOnlyFruit);35
crops.put(block, crop);36
seedMaterials.add(seed);37
}38
39
Crop get(Material material) {40
return crops.get(material);41
}42
43
Collection<Crop> all() {44
return crops.values();45
}46
47
Set<Material> seedMaterials() {48
return Set.copyOf(seedMaterials);49
}50
51
boolean isReady(Block block) {52
Crop crop = get(block.getType());53
if (crop == null) return false;54
55
if (crop.breakOnlyFruit()) {56
return hasAttachedStem(block, crop.block() == Material.MELON57
? Material.ATTACHED_MELON_STEM58
: Material.ATTACHED_PUMPKIN_STEM);59
}60
61
if (block.getBlockData() instanceof Ageable ageable) {62
return ageable.getAge() >= ageable.getMaximumAge();63
}64
return false;65
}66
67
private boolean hasAttachedStem(Block fruit, Material attachedStem) {68
for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {69
if (fruit.getRelative(face).getType() == attachedStem) return true;70
}71
return false;72
}73
}@@ -0,0 +1,133 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.Material;
4
import org.bukkit.entity.CopperGolem;
5
import org.bukkit.inventory.ItemStack;
6
import org.bukkit.persistence.PersistentDataType;
7
8
import java.util.ArrayList;
9
import java.util.Collection;
10
import java.util.List;
11
12
final class FarmerCargo {
13
private final CopperGolem golem;
14
private final FarmerKeys keys;
15
private final int maxSlots;
16
private final List<ItemStack> items = new ArrayList<>();
17
18
FarmerCargo(CopperGolem golem, FarmerKeys keys, int maxSlots) {
19
this.golem = golem;
20
this.keys = keys;
21
this.maxSlots = Math.max(1, maxSlots);
22
load();
23
}
24
25
List<ItemStack> snapshot() {
26
List<ItemStack> copy = new ArrayList<>(items.size());
27
for (ItemStack item : items) copy.add(item.clone());
28
return copy;
29
}
30
31
boolean isEmpty() {
32
return items.isEmpty();
33
}
34
35
int count(Material type) {
36
int count = 0;
37
for (ItemStack item : items) if (item.getType() == type) count += item.getAmount();
38
return count;
39
}
40
41
boolean remove(Material type, int amount) {
42
if (amount <= 0) return true;
43
if (count(type) < amount) return false;
44
45
int remaining = amount;
46
for (int i = items.size() - 1; i >= 0 && remaining > 0; i--) {
47
ItemStack item = items.get(i);
48
if (item.getType() != type) continue;
49
int take = Math.min(remaining, item.getAmount());
50
item.setAmount(item.getAmount() - take);
51
remaining -= take;
52
if (item.getAmount() <= 0) items.remove(i);
53
}
54
save();
55
return true;
56
}
57
58
List<ItemStack> addAll(Collection<ItemStack> stacks) {
59
List<ItemStack> leftovers = new ArrayList<>();
60
for (ItemStack stack : stacks) {
61
ItemStack left = add(stack);
62
if (left != null && !left.isEmpty()) leftovers.add(left);
63
}
64
save();
65
return leftovers;
66
}
67
68
ItemStack add(ItemStack original) {
69
if (original == null || original.isEmpty()) return null;
70
ItemStack remaining = original.clone();
71
72
for (ItemStack existing : items) {
73
if (!existing.isSimilar(remaining)) continue;
74
int space = existing.getMaxStackSize() - existing.getAmount();
75
if (space <= 0) continue;
76
int moved = Math.min(space, remaining.getAmount());
77
existing.setAmount(existing.getAmount() + moved);
78
remaining.setAmount(remaining.getAmount() - moved);
79
if (remaining.getAmount() == 0) {
80
save();
81
return null;
82
}
83
}
84
85
while (remaining.getAmount() > 0 && items.size() < maxSlots) {
86
int moved = Math.min(remaining.getMaxStackSize(), remaining.getAmount());
87
ItemStack split = remaining.clone();
88
split.setAmount(moved);
89
items.add(split);
90
remaining.setAmount(remaining.getAmount() - moved);
91
}
92
save();
93
return remaining.getAmount() == 0 ? null : remaining;
94
}
95
96
void replaceWith(Collection<ItemStack> stacks) {
97
items.clear();
98
for (ItemStack item : stacks) {
99
if (item != null && !item.isEmpty()) items.add(item.clone());
100
}
101
save();
102
}
103
104
void clear() {
105
items.clear();
106
save();
107
}
108
109
private void load() {
110
byte[] bytes = golem.getPersistentDataContainer().get(keys.cargo, PersistentDataType.BYTE_ARRAY);
111
if (bytes == null || bytes.length == 0) return;
112
try {
113
ItemStack[] decoded = ItemStack.deserializeItemsFromBytes(bytes);
114
for (ItemStack item : decoded) {
115
if (item != null && !item.isEmpty()) items.add(item);
116
}
117
} catch (RuntimeException ignored) {
118
// A malformed cargo tag must not prevent the entity from loading.
119
}
120
}
121
122
private void save() {
123
if (items.isEmpty()) {
124
golem.getPersistentDataContainer().remove(keys.cargo);
125
return;
126
}
127
golem.getPersistentDataContainer().set(
128
keys.cargo,
129
PersistentDataType.BYTE_ARRAY,
130
ItemStack.serializeItemsAsBytes(items)
131
);
132
}
133
}
@@ -0,0 +1,133 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.Material;4
import org.bukkit.entity.CopperGolem;5
import org.bukkit.inventory.ItemStack;6
import org.bukkit.persistence.PersistentDataType;7
8
import java.util.ArrayList;9
import java.util.Collection;10
import java.util.List;11
12
final class FarmerCargo {13
private final CopperGolem golem;14
private final FarmerKeys keys;15
private final int maxSlots;16
private final List<ItemStack> items = new ArrayList<>();17
18
FarmerCargo(CopperGolem golem, FarmerKeys keys, int maxSlots) {19
this.golem = golem;20
this.keys = keys;21
this.maxSlots = Math.max(1, maxSlots);22
load();23
}24
25
List<ItemStack> snapshot() {26
List<ItemStack> copy = new ArrayList<>(items.size());27
for (ItemStack item : items) copy.add(item.clone());28
return copy;29
}30
31
boolean isEmpty() {32
return items.isEmpty();33
}34
35
int count(Material type) {36
int count = 0;37
for (ItemStack item : items) if (item.getType() == type) count += item.getAmount();38
return count;39
}40
41
boolean remove(Material type, int amount) {42
if (amount <= 0) return true;43
if (count(type) < amount) return false;44
45
int remaining = amount;46
for (int i = items.size() - 1; i >= 0 && remaining > 0; i--) {47
ItemStack item = items.get(i);48
if (item.getType() != type) continue;49
int take = Math.min(remaining, item.getAmount());50
item.setAmount(item.getAmount() - take);51
remaining -= take;52
if (item.getAmount() <= 0) items.remove(i);53
}54
save();55
return true;56
}57
58
List<ItemStack> addAll(Collection<ItemStack> stacks) {59
List<ItemStack> leftovers = new ArrayList<>();60
for (ItemStack stack : stacks) {61
ItemStack left = add(stack);62
if (left != null && !left.isEmpty()) leftovers.add(left);63
}64
save();65
return leftovers;66
}67
68
ItemStack add(ItemStack original) {69
if (original == null || original.isEmpty()) return null;70
ItemStack remaining = original.clone();71
72
for (ItemStack existing : items) {73
if (!existing.isSimilar(remaining)) continue;74
int space = existing.getMaxStackSize() - existing.getAmount();75
if (space <= 0) continue;76
int moved = Math.min(space, remaining.getAmount());77
existing.setAmount(existing.getAmount() + moved);78
remaining.setAmount(remaining.getAmount() - moved);79
if (remaining.getAmount() == 0) {80
save();81
return null;82
}83
}84
85
while (remaining.getAmount() > 0 && items.size() < maxSlots) {86
int moved = Math.min(remaining.getMaxStackSize(), remaining.getAmount());87
ItemStack split = remaining.clone();88
split.setAmount(moved);89
items.add(split);90
remaining.setAmount(remaining.getAmount() - moved);91
}92
save();93
return remaining.getAmount() == 0 ? null : remaining;94
}95
96
void replaceWith(Collection<ItemStack> stacks) {97
items.clear();98
for (ItemStack item : stacks) {99
if (item != null && !item.isEmpty()) items.add(item.clone());100
}101
save();102
}103
104
void clear() {105
items.clear();106
save();107
}108
109
private void load() {110
byte[] bytes = golem.getPersistentDataContainer().get(keys.cargo, PersistentDataType.BYTE_ARRAY);111
if (bytes == null || bytes.length == 0) return;112
try {113
ItemStack[] decoded = ItemStack.deserializeItemsFromBytes(bytes);114
for (ItemStack item : decoded) {115
if (item != null && !item.isEmpty()) items.add(item);116
}117
} catch (RuntimeException ignored) {118
// A malformed cargo tag must not prevent the entity from loading.119
}120
}121
122
private void save() {123
if (items.isEmpty()) {124
golem.getPersistentDataContainer().remove(keys.cargo);125
return;126
}127
golem.getPersistentDataContainer().set(128
keys.cargo,129
PersistentDataType.BYTE_ARRAY,130
ItemStack.serializeItemsAsBytes(items)131
);132
}133
}@@ -0,0 +1,66 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.Material;
4
import org.bukkit.entity.CopperGolem;
5
import org.bukkit.inventory.ItemStack;
6
import org.bukkit.persistence.PersistentDataType;
7
8
final class FarmerItemCodec {
9
private final FarmerKeys keys;
10
11
FarmerItemCodec(FarmerKeys keys) {
12
this.keys = keys;
13
}
14
15
ItemStack createStatue(ItemStack sourceTool) {
16
ItemStack tool = normalizeTool(sourceTool);
17
ItemStack item = new ItemStack(Material.COPPER_GOLEM_STATUE);
18
item.editMeta(meta -> {
19
meta.setItemName("Copper Farmer Golem");
20
meta.getPersistentDataContainer().set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);
21
meta.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
22
});
23
return item;
24
}
25
26
boolean isFarmerItem(ItemStack item) {
27
return item != null && !item.isEmpty()
28
&& item.getPersistentDataContainer().has(keys.farmerItem, PersistentDataType.BYTE);
29
}
30
31
ItemStack readTool(ItemStack farmerItem) {
32
if (farmerItem == null || farmerItem.isEmpty()) return defaultTool();
33
byte[] bytes = farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY);
34
return decodeTool(bytes);
35
}
36
37
ItemStack readTool(CopperGolem golem) {
38
byte[] bytes = golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY);
39
return decodeTool(bytes);
40
}
41
42
void storeTool(CopperGolem golem, ItemStack sourceTool) {
43
ItemStack tool = normalizeTool(sourceTool);
44
golem.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());
45
}
46
47
private ItemStack decodeTool(byte[] bytes) {
48
if (bytes == null || bytes.length == 0) return defaultTool();
49
try {
50
return normalizeTool(ItemStack.deserializeBytes(bytes));
51
} catch (RuntimeException ex) {
52
return defaultTool();
53
}
54
}
55
56
private ItemStack normalizeTool(ItemStack source) {
57
if (source == null || source.isEmpty() || source.getType() != Material.COPPER_HOE) return defaultTool();
58
ItemStack copy = source.clone();
59
copy.setAmount(1);
60
return copy;
61
}
62
63
private ItemStack defaultTool() {
64
return new ItemStack(Material.COPPER_HOE);
65
}
66
}
@@ -0,0 +1,66 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.Material;4
import org.bukkit.entity.CopperGolem;5
import org.bukkit.inventory.ItemStack;6
import org.bukkit.persistence.PersistentDataType;7
8
final class FarmerItemCodec {9
private final FarmerKeys keys;10
11
FarmerItemCodec(FarmerKeys keys) {12
this.keys = keys;13
}14
15
ItemStack createStatue(ItemStack sourceTool) {16
ItemStack tool = normalizeTool(sourceTool);17
ItemStack item = new ItemStack(Material.COPPER_GOLEM_STATUE);18
item.editMeta(meta -> {19
meta.setItemName("Copper Farmer Golem");20
meta.getPersistentDataContainer().set(keys.farmerItem, PersistentDataType.BYTE, (byte) 1);21
meta.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());22
});23
return item;24
}25
26
boolean isFarmerItem(ItemStack item) {27
return item != null && !item.isEmpty()28
&& item.getPersistentDataContainer().has(keys.farmerItem, PersistentDataType.BYTE);29
}30
31
ItemStack readTool(ItemStack farmerItem) {32
if (farmerItem == null || farmerItem.isEmpty()) return defaultTool();33
byte[] bytes = farmerItem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY);34
return decodeTool(bytes);35
}36
37
ItemStack readTool(CopperGolem golem) {38
byte[] bytes = golem.getPersistentDataContainer().get(keys.tool, PersistentDataType.BYTE_ARRAY);39
return decodeTool(bytes);40
}41
42
void storeTool(CopperGolem golem, ItemStack sourceTool) {43
ItemStack tool = normalizeTool(sourceTool);44
golem.getPersistentDataContainer().set(keys.tool, PersistentDataType.BYTE_ARRAY, tool.serializeAsBytes());45
}46
47
private ItemStack decodeTool(byte[] bytes) {48
if (bytes == null || bytes.length == 0) return defaultTool();49
try {50
return normalizeTool(ItemStack.deserializeBytes(bytes));51
} catch (RuntimeException ex) {52
return defaultTool();53
}54
}55
56
private ItemStack normalizeTool(ItemStack source) {57
if (source == null || source.isEmpty() || source.getType() != Material.COPPER_HOE) return defaultTool();58
ItemStack copy = source.clone();59
copy.setAmount(1);60
return copy;61
}62
63
private ItemStack defaultTool() {64
return new ItemStack(Material.COPPER_HOE);65
}66
}@@ -0,0 +1,28 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.NamespacedKey;
4
import org.bukkit.plugin.Plugin;
5
6
final class FarmerKeys {
7
final NamespacedKey farmerItem;
8
final NamespacedKey farmerEntity;
9
final NamespacedKey cargo;
10
final NamespacedKey tool;
11
final NamespacedKey chestWorld;
12
final NamespacedKey chestX;
13
final NamespacedKey chestY;
14
final NamespacedKey chestZ;
15
final NamespacedKey recipe;
16
17
FarmerKeys(Plugin plugin) {
18
farmerItem = new NamespacedKey(plugin, "farmer_item");
19
farmerEntity = new NamespacedKey(plugin, "farmer_entity");
20
cargo = new NamespacedKey(plugin, "cargo");
21
tool = new NamespacedKey(plugin, "tool");
22
chestWorld = new NamespacedKey(plugin, "chest_world");
23
chestX = new NamespacedKey(plugin, "chest_x");
24
chestY = new NamespacedKey(plugin, "chest_y");
25
chestZ = new NamespacedKey(plugin, "chest_z");
26
recipe = new NamespacedKey(plugin, "farmer_statue");
27
}
28
}
@@ -0,0 +1,28 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.NamespacedKey;4
import org.bukkit.plugin.Plugin;5
6
final class FarmerKeys {7
final NamespacedKey farmerItem;8
final NamespacedKey farmerEntity;9
final NamespacedKey cargo;10
final NamespacedKey tool;11
final NamespacedKey chestWorld;12
final NamespacedKey chestX;13
final NamespacedKey chestY;14
final NamespacedKey chestZ;15
final NamespacedKey recipe;16
17
FarmerKeys(Plugin plugin) {18
farmerItem = new NamespacedKey(plugin, "farmer_item");19
farmerEntity = new NamespacedKey(plugin, "farmer_entity");20
cargo = new NamespacedKey(plugin, "cargo");21
tool = new NamespacedKey(plugin, "tool");22
chestWorld = new NamespacedKey(plugin, "chest_world");23
chestX = new NamespacedKey(plugin, "chest_x");24
chestY = new NamespacedKey(plugin, "chest_y");25
chestZ = new NamespacedKey(plugin, "chest_z");26
recipe = new NamespacedKey(plugin, "farmer_statue");27
}28
}@@ -0,0 +1,118 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.Location;
4
import org.bukkit.Material;
5
import org.bukkit.block.Block;
6
import org.bukkit.block.BlockState;
7
import org.bukkit.entity.CopperGolem;
8
import org.bukkit.entity.Entity;
9
import org.bukkit.event.EventHandler;
10
import org.bukkit.event.EventPriority;
11
import org.bukkit.event.Listener;
12
import org.bukkit.event.block.BlockPlaceEvent;
13
import org.bukkit.event.block.CrafterCraftEvent;
14
import org.bukkit.event.entity.EntityDeathEvent;
15
import org.bukkit.event.inventory.PrepareItemCraftEvent;
16
import org.bukkit.event.world.EntitiesLoadEvent;
17
import org.bukkit.event.world.EntitiesUnloadEvent;
18
import org.bukkit.inventory.InventoryHolder;
19
import org.bukkit.inventory.ItemStack;
20
import org.bukkit.inventory.Recipe;
21
import org.bukkit.inventory.ShapelessRecipe;
22
import org.bukkit.persistence.PersistentDataType;
23
import org.bukkit.plugin.Plugin;
24
25
final class FarmerListener implements Listener {
26
private final Plugin plugin;
27
private final FarmerKeys keys;
28
private final FarmerManager manager;
29
private final FarmerItemCodec itemCodec;
30
31
FarmerListener(Plugin plugin, FarmerKeys keys, FarmerManager manager, FarmerItemCodec itemCodec) {
32
this.plugin = plugin;
33
this.keys = keys;
34
this.manager = manager;
35
this.itemCodec = itemCodec;
36
}
37
38
@EventHandler(priority = EventPriority.HIGHEST)
39
public void onPrepareCraft(PrepareItemCraftEvent event) {
40
if (!isFarmerRecipe(event.getRecipe())) return;
41
ItemStack hoe = findCopperHoe(event.getInventory().getMatrix());
42
if (hoe != null) event.getInventory().setResult(itemCodec.createStatue(hoe));
43
}
44
45
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
46
public void onCrafterCraft(CrafterCraftEvent event) {
47
if (!isFarmerRecipe(event.getRecipe())) return;
48
BlockState state = event.getBlock().getState();
49
if (!(state instanceof InventoryHolder holder)) return;
50
ItemStack hoe = findCopperHoe(holder.getInventory().getContents());
51
if (hoe != null) event.setResult(itemCodec.createStatue(hoe));
52
}
53
54
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
55
public void onFarmerStatuePlaced(BlockPlaceEvent event) {
56
if (!itemCodec.isFarmerItem(event.getItemInHand())) return;
57
58
Block placed = event.getBlockPlaced();
59
if (!placed.getType().name().endsWith("COPPER_GOLEM_STATUE")) return;
60
61
// Capture the exact construction tool now: the crafting recipe consumed it,
62
// and the placed item stack may be mutated by vanilla after this event.
63
ItemStack tool = itemCodec.readTool(event.getItemInHand());
64
65
// Let successful vanilla placement consume exactly one statue, then replace
66
// that special statue with our tagged real Copper Golem on the next tick.
67
Location location = placed.getLocation();
68
plugin.getServer().getScheduler().runTask(plugin, () -> {
69
Block current = location.getBlock();
70
if (!current.getType().name().endsWith("COPPER_GOLEM_STATUE")) return;
71
72
current.setType(Material.AIR, false);
73
Location spawn = location.clone().add(0.5, 0.0, 0.5);
74
CopperGolem golem = location.getWorld().spawn(spawn, CopperGolem.class, entity -> {
75
entity.getPersistentDataContainer().set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);
76
itemCodec.storeTool(entity, tool);
77
});
78
manager.register(golem);
79
});
80
}
81
82
@EventHandler
83
public void onEntitiesLoad(EntitiesLoadEvent event) {
84
for (Entity entity : event.getEntities()) {
85
if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) {
86
manager.register(golem);
87
}
88
}
89
}
90
91
@EventHandler
92
public void onEntitiesUnload(EntitiesUnloadEvent event) {
93
for (Entity entity : event.getEntities()) {
94
if (manager.isFarmer(entity)) manager.unregister(entity);
95
}
96
}
97
98
@EventHandler(priority = EventPriority.HIGHEST)
99
public void onDeath(EntityDeathEvent event) {
100
if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;
101
event.getDrops().addAll(manager.deathDrops(golem));
102
}
103
104
private boolean isFarmerRecipe(Recipe recipe) {
105
return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.recipe);
106
}
107
108
private ItemStack findCopperHoe(ItemStack[] contents) {
109
if (contents == null) return null;
110
for (ItemStack item : contents) {
111
if (item == null || item.isEmpty() || item.getType() != Material.COPPER_HOE) continue;
112
ItemStack copy = item.clone();
113
copy.setAmount(1);
114
return copy;
115
}
116
return null;
117
}
118
}
@@ -0,0 +1,118 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.Location;4
import org.bukkit.Material;5
import org.bukkit.block.Block;6
import org.bukkit.block.BlockState;7
import org.bukkit.entity.CopperGolem;8
import org.bukkit.entity.Entity;9
import org.bukkit.event.EventHandler;10
import org.bukkit.event.EventPriority;11
import org.bukkit.event.Listener;12
import org.bukkit.event.block.BlockPlaceEvent;13
import org.bukkit.event.block.CrafterCraftEvent;14
import org.bukkit.event.entity.EntityDeathEvent;15
import org.bukkit.event.inventory.PrepareItemCraftEvent;16
import org.bukkit.event.world.EntitiesLoadEvent;17
import org.bukkit.event.world.EntitiesUnloadEvent;18
import org.bukkit.inventory.InventoryHolder;19
import org.bukkit.inventory.ItemStack;20
import org.bukkit.inventory.Recipe;21
import org.bukkit.inventory.ShapelessRecipe;22
import org.bukkit.persistence.PersistentDataType;23
import org.bukkit.plugin.Plugin;24
25
final class FarmerListener implements Listener {26
private final Plugin plugin;27
private final FarmerKeys keys;28
private final FarmerManager manager;29
private final FarmerItemCodec itemCodec;30
31
FarmerListener(Plugin plugin, FarmerKeys keys, FarmerManager manager, FarmerItemCodec itemCodec) {32
this.plugin = plugin;33
this.keys = keys;34
this.manager = manager;35
this.itemCodec = itemCodec;36
}37
38
@EventHandler(priority = EventPriority.HIGHEST)39
public void onPrepareCraft(PrepareItemCraftEvent event) {40
if (!isFarmerRecipe(event.getRecipe())) return;41
ItemStack hoe = findCopperHoe(event.getInventory().getMatrix());42
if (hoe != null) event.getInventory().setResult(itemCodec.createStatue(hoe));43
}44
45
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)46
public void onCrafterCraft(CrafterCraftEvent event) {47
if (!isFarmerRecipe(event.getRecipe())) return;48
BlockState state = event.getBlock().getState();49
if (!(state instanceof InventoryHolder holder)) return;50
ItemStack hoe = findCopperHoe(holder.getInventory().getContents());51
if (hoe != null) event.setResult(itemCodec.createStatue(hoe));52
}53
54
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)55
public void onFarmerStatuePlaced(BlockPlaceEvent event) {56
if (!itemCodec.isFarmerItem(event.getItemInHand())) return;57
58
Block placed = event.getBlockPlaced();59
if (!placed.getType().name().endsWith("COPPER_GOLEM_STATUE")) return;60
61
// Capture the exact construction tool now: the crafting recipe consumed it,62
// and the placed item stack may be mutated by vanilla after this event.63
ItemStack tool = itemCodec.readTool(event.getItemInHand());64
65
// Let successful vanilla placement consume exactly one statue, then replace66
// that special statue with our tagged real Copper Golem on the next tick.67
Location location = placed.getLocation();68
plugin.getServer().getScheduler().runTask(plugin, () -> {69
Block current = location.getBlock();70
if (!current.getType().name().endsWith("COPPER_GOLEM_STATUE")) return;71
72
current.setType(Material.AIR, false);73
Location spawn = location.clone().add(0.5, 0.0, 0.5);74
CopperGolem golem = location.getWorld().spawn(spawn, CopperGolem.class, entity -> {75
entity.getPersistentDataContainer().set(keys.farmerEntity, PersistentDataType.BYTE, (byte) 1);76
itemCodec.storeTool(entity, tool);77
});78
manager.register(golem);79
});80
}81
82
@EventHandler83
public void onEntitiesLoad(EntitiesLoadEvent event) {84
for (Entity entity : event.getEntities()) {85
if (entity instanceof CopperGolem golem && manager.isFarmer(golem)) {86
manager.register(golem);87
}88
}89
}90
91
@EventHandler92
public void onEntitiesUnload(EntitiesUnloadEvent event) {93
for (Entity entity : event.getEntities()) {94
if (manager.isFarmer(entity)) manager.unregister(entity);95
}96
}97
98
@EventHandler(priority = EventPriority.HIGHEST)99
public void onDeath(EntityDeathEvent event) {100
if (!(event.getEntity() instanceof CopperGolem golem) || !manager.isFarmer(golem)) return;101
event.getDrops().addAll(manager.deathDrops(golem));102
}103
104
private boolean isFarmerRecipe(Recipe recipe) {105
return recipe instanceof ShapelessRecipe shapeless && shapeless.getKey().equals(keys.recipe);106
}107
108
private ItemStack findCopperHoe(ItemStack[] contents) {109
if (contents == null) return null;110
for (ItemStack item : contents) {111
if (item == null || item.isEmpty() || item.getType() != Material.COPPER_HOE) continue;112
ItemStack copy = item.clone();113
copy.setAmount(1);114
return copy;115
}116
return null;117
}118
}@@ -0,0 +1,715 @@
1
package nl.timfalken.copperfarmer;
2
3
import com.destroystokyo.paper.entity.Pathfinder;
4
import org.bukkit.Bukkit;
5
import org.bukkit.Chunk;
6
import org.bukkit.Location;
7
import org.bukkit.Material;
8
import org.bukkit.World;
9
import org.bukkit.block.Block;
10
import org.bukkit.block.BlockFace;
11
import org.bukkit.block.BlockState;
12
import org.bukkit.block.data.Ageable;
13
import org.bukkit.block.data.BlockData;
14
import org.bukkit.entity.CopperGolem;
15
import org.bukkit.entity.Entity;
16
import org.bukkit.inventory.Inventory;
17
import org.bukkit.inventory.InventoryHolder;
18
import org.bukkit.inventory.ItemStack;
19
import org.bukkit.persistence.PersistentDataContainer;
20
import org.bukkit.persistence.PersistentDataType;
21
import org.bukkit.plugin.Plugin;
22
23
import java.util.ArrayDeque;
24
import java.util.ArrayList;
25
import java.util.Comparator;
26
import java.util.Deque;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.Set;
32
import java.util.UUID;
33
34
final class FarmerManager {
35
private static final BlockFace[] HORIZONTAL = {
36
BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
37
};
38
39
private final Plugin plugin;
40
private final FarmerKeys keys;
41
private final CropRegistry cropRegistry;
42
private final SeedRecipeCache seedRecipes;
43
private final FarmerItemCodec itemCodec;
44
private final Map<UUID, Brain> brains = new HashMap<>();
45
46
private final int chestChunkRadius;
47
private final int cropRadius;
48
private final long scanInterval;
49
private final double moveSpeed;
50
private final long stuckTimeout;
51
private final int maxPathRetries;
52
private final long unreachableCooldown;
53
private final double actionDistanceSquared;
54
private final int cargoSlots;
55
private final boolean preventOxidation;
56
57
private long clock;
58
59
FarmerManager(Plugin plugin, FarmerKeys keys, CropRegistry cropRegistry, SeedRecipeCache seedRecipes,
60
FarmerItemCodec itemCodec) {
61
this.plugin = plugin;
62
this.keys = keys;
63
this.cropRegistry = cropRegistry;
64
this.seedRecipes = seedRecipes;
65
this.itemCodec = itemCodec;
66
this.chestChunkRadius = Math.max(0, plugin.getConfig().getInt("chest-search-chunk-radius", 2));
67
this.cropRadius = Math.max(1, plugin.getConfig().getInt("crop-radius", 15));
68
this.scanInterval = Math.max(20, plugin.getConfig().getLong("scan-interval-ticks", 200));
69
this.moveSpeed = Math.max(0.1, plugin.getConfig().getDouble("move-speed", 1.0));
70
this.stuckTimeout = Math.max(20, plugin.getConfig().getLong("stuck-timeout-ticks", 60));
71
this.maxPathRetries = Math.max(0, plugin.getConfig().getInt("max-path-retries", 1));
72
this.unreachableCooldown = Math.max(20, plugin.getConfig().getLong("unreachable-crop-cooldown-ticks", 600));
73
double actionDistance = Math.max(1.25, plugin.getConfig().getDouble("action-distance", 2.25));
74
this.actionDistanceSquared = actionDistance * actionDistance;
75
this.cargoSlots = Math.max(1, plugin.getConfig().getInt("cargo-slots", 9));
76
this.preventOxidation = plugin.getConfig().getBoolean("prevent-oxidation", true);
77
}
78
79
void tick(long elapsedTicks) {
80
clock += elapsedTicks;
81
var iterator = brains.entrySet().iterator();
82
while (iterator.hasNext()) {
83
Brain brain = iterator.next().getValue();
84
if (!brain.golem.isValid() || brain.golem.isDead()) {
85
iterator.remove();
86
continue;
87
}
88
try {
89
brain.tick();
90
} catch (RuntimeException ex) {
91
plugin.getLogger().warning("Farmer " + brain.golem.getUniqueId() + " tick failed: " + ex.getMessage());
92
}
93
}
94
}
95
96
void register(CopperGolem golem) {
97
if (!isFarmer(golem)) return;
98
configureEntity(golem);
99
brains.computeIfAbsent(golem.getUniqueId(), ignored -> new Brain(golem));
100
}
101
102
void unregister(Entity entity) {
103
brains.remove(entity.getUniqueId());
104
}
105
106
boolean isFarmer(Entity entity) {
107
return entity instanceof CopperGolem
108
&& entity.getPersistentDataContainer().has(keys.farmerEntity, PersistentDataType.BYTE);
109
}
110
111
void configureEntity(CopperGolem golem) {
112
plugin.getServer().getMobGoals().removeAllGoals(golem);
113
golem.setAI(true);
114
golem.setAware(true);
115
golem.setCanPickupItems(false);
116
golem.getPathfinder().setCanFloat(true);
117
golem.getPathfinder().setCanPassDoors(true);
118
golem.getPathfinder().setCanOpenDoors(false);
119
golem.setGolemState(CopperGolem.State.IDLE);
120
if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
121
var equipment = golem.getEquipment();
122
if (equipment != null) {
123
equipment.setItemInMainHand(itemCodec.readTool(golem));
124
equipment.setItemInMainHandDropChance(0.0f);
125
}
126
}
127
128
List<ItemStack> deathDrops(CopperGolem golem) {
129
Brain brain = brains.remove(golem.getUniqueId());
130
FarmerCargo cargo = brain != null ? brain.cargo : new FarmerCargo(golem, keys, cargoSlots);
131
ItemStack tool = brain != null ? brain.tool.clone() : itemCodec.readTool(golem);
132
List<ItemStack> drops = new ArrayList<>();
133
drops.add(tool);
134
drops.addAll(cargo.snapshot());
135
cargo.clear();
136
return drops;
137
}
138
139
private final class Brain {
140
private final CopperGolem golem;
141
private final FarmerCargo cargo;
142
private final ItemStack tool;
143
private State state = State.IDLE;
144
private BlockRef chest;
145
private BlockRef cropTarget;
146
private CropRegistry.Crop activeCrop;
147
private final Deque<BlockRef> plantQueue = new ArrayDeque<>();
148
private final Map<BlockRef, Long> unreachableCrops = new HashMap<>();
149
private final Map<BlockRef, Long> unreachableChests = new HashMap<>();
150
151
private Location navigationTarget;
152
private Location lastProgressLocation;
153
private long lastProgressTick;
154
private int pathRetries;
155
private long nextScanTick;
156
157
Brain(CopperGolem golem) {
158
this.golem = golem;
159
this.cargo = new FarmerCargo(golem, keys, cargoSlots);
160
this.tool = itemCodec.readTool(golem);
161
this.chest = loadChest(golem);
162
this.nextScanTick = clock;
163
}
164
165
void tick() {
166
if (preventOxidation && golem.getOxidizing() != CopperGolem.Oxidizing.waxed()) {
167
golem.setOxidizing(CopperGolem.Oxidizing.waxed());
168
}
169
cleanupCooldowns();
170
171
if (!isChestValid(chest)) {
172
clearChest();
173
}
174
175
switch (state) {
176
case IDLE -> tickIdle();
177
case MOVING_TO_CROP -> tickMovingToCrop();
178
case MOVING_TO_PLANT -> tickMovingToPlant();
179
case MOVING_TO_CHEST -> tickMovingToChest();
180
case WAITING_FOR_CHEST_SPACE -> tickWaitingForChestSpace();
181
}
182
}
183
184
private void tickIdle() {
185
if (chest == null) {
186
if (clock < nextScanTick) return;
187
nextScanTick = clock + scanInterval;
188
if (!bindNearestChest()) return;
189
}
190
191
if (!cargo.isEmpty()) {
192
beginReturnToChest();
193
return;
194
}
195
196
if (clock < nextScanTick) return;
197
nextScanTick = clock + scanInterval;
198
199
Block target = findMatureCrop();
200
if (target == null) return;
201
202
CropRegistry.Crop crop = cropRegistry.get(target.getType());
203
if (crop == null) {
204
markCropUnreachable(BlockRef.of(target));
205
return;
206
}
207
208
cropTarget = BlockRef.of(target);
209
activeCrop = crop;
210
if (!beginPathToBlock(target, State.MOVING_TO_CROP)) {
211
markCropUnreachable(cropTarget);
212
cropTarget = null;
213
activeCrop = null;
214
state = State.IDLE;
215
}
216
}
217
218
private void tickMovingToCrop() {
219
Block cropBlock = block(cropTarget);
220
if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
221
|| !cropRegistry.isReady(cropBlock)) {
222
stopNavigation();
223
resetCropTask();
224
return;
225
}
226
227
if (reachedNavigationTarget() && near(cropBlock)) {
228
stopNavigation();
229
harvest(cropBlock, activeCrop);
230
return;
231
}
232
233
if (!navigationHealthy()) {
234
if (!retryPath()) {
235
markCropUnreachable(cropTarget);
236
resetCropTask();
237
}
238
}
239
}
240
241
private void tickMovingToPlant() {
242
if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
243
plantQueue.clear();
244
beginReturnToChest();
245
return;
246
}
247
248
BlockRef targetRef = plantQueue.peekFirst();
249
Block target = block(targetRef);
250
if (target == null || !canPlantOn(target, activeCrop)) {
251
plantQueue.pollFirst();
252
advancePlantQueue();
253
return;
254
}
255
256
if (reachedNavigationTarget() && near(target)) {
257
stopNavigation();
258
if (cargo.remove(activeCrop.seed(), 1)) {
259
golem.swingMainHand();
260
target.setType(activeCrop.block(), false);
261
}
262
plantQueue.pollFirst();
263
advancePlantQueue();
264
return;
265
}
266
267
if (!navigationHealthy() && !retryPath()) {
268
plantQueue.pollFirst();
269
advancePlantQueue();
270
}
271
}
272
273
private void tickMovingToChest() {
274
Block chestBlock = block(chest);
275
if (!isCopperChest(chestBlock)) {
276
clearChest();
277
state = State.IDLE;
278
nextScanTick = clock;
279
return;
280
}
281
282
if (reachedNavigationTarget() && near(chestBlock)) {
283
stopNavigation();
284
deposit(chestBlock);
285
return;
286
}
287
288
if (!navigationHealthy() && !retryPath()) {
289
markChestUnreachable(chest);
290
clearChest();
291
state = State.IDLE;
292
nextScanTick = clock;
293
}
294
}
295
296
private void tickWaitingForChestSpace() {
297
if (cargo.isEmpty()) {
298
state = State.IDLE;
299
nextScanTick = clock + scanInterval;
300
return;
301
}
302
if (!isChestValid(chest)) {
303
clearChest();
304
state = State.IDLE;
305
nextScanTick = clock;
306
return;
307
}
308
if (clock >= nextScanTick) {
309
nextScanTick = clock + scanInterval;
310
beginReturnToChest();
311
}
312
}
313
314
private void harvest(Block cropBlock, CropRegistry.Crop crop) {
315
golem.swingMainHand();
316
BlockData oldData = cropBlock.getBlockData().clone();
317
List<ItemStack> calculatedDrops = new ArrayList<>(cropBlock.getDrops(tool.clone(), golem));
318
319
cropBlock.setType(Material.AIR, false);
320
List<ItemStack> overflow = cargo.addAll(calculatedDrops);
321
for (ItemStack item : overflow) {
322
cropBlock.getWorld().dropItemNaturally(cropBlock.getLocation().add(0.5, 0.5, 0.5), item);
323
}
324
325
if (!crop.breakOnlyFruit()) {
326
ensureSeed(crop.seed());
327
if (cargo.remove(crop.seed(), 1)) {
328
if (oldData instanceof Ageable ageable) ageable.setAge(0);
329
cropBlock.setBlockData(oldData, false);
330
}
331
}
332
333
cropTarget = null;
334
335
if (!crop.breakOnlyFruit() && crop.farmland() && cargo.count(crop.seed()) > 0) {
336
buildPlantQueue(cropBlock, crop);
337
if (!plantQueue.isEmpty()) {
338
activeCrop = crop;
339
advancePlantQueue();
340
return;
341
}
342
}
343
344
activeCrop = null;
345
beginReturnToChest();
346
}
347
348
private boolean ensureSeed(Material requiredSeed) {
349
if (cargo.count(requiredSeed) > 0) return true;
350
for (ItemStack stack : cargo.snapshot()) {
351
SeedRecipeCache.Conversion conversion = seedRecipes.find(stack.getType(), requiredSeed);
352
if (conversion == null || cargo.count(conversion.input()) < conversion.inputCount()) continue;
353
if (!cargo.remove(conversion.input(), conversion.inputCount())) continue;
354
ItemStack overflow = cargo.add(conversion.output());
355
if (overflow != null && !overflow.isEmpty()) {
356
// The recipe was legitimately crafted; if the internal bag cannot
357
// contain all output, spill only that excess into the world.
358
golem.getWorld().dropItemNaturally(golem.getLocation(), overflow);
359
}
360
return cargo.count(requiredSeed) > 0;
361
}
362
return false;
363
}
364
365
private void buildPlantQueue(Block harvestedCropBlock, CropRegistry.Crop crop) {
366
plantQueue.clear();
367
Block startFarmland = harvestedCropBlock.getRelative(BlockFace.DOWN);
368
if (startFarmland.getType() != Material.FARMLAND) return;
369
370
Set<BlockRef> visited = new HashSet<>();
371
Deque<Block> search = new ArrayDeque<>();
372
search.add(startFarmland);
373
visited.add(BlockRef.of(startFarmland));
374
375
while (!search.isEmpty()) {
376
Block farmland = search.pollFirst();
377
Block above = farmland.getRelative(BlockFace.UP);
378
if (above.getType().isAir() && withinCropRadius(above) && canPlantOn(above, crop)) {
379
plantQueue.add(BlockRef.of(above));
380
}
381
382
for (BlockFace face : HORIZONTAL) {
383
Block next = farmland.getRelative(face);
384
if (next.getType() != Material.FARMLAND || !withinCropRadius(next)) continue;
385
BlockRef ref = BlockRef.of(next);
386
if (visited.add(ref)) search.addLast(next);
387
}
388
}
389
}
390
391
private void advancePlantQueue() {
392
while (!plantQueue.isEmpty()) {
393
if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
394
plantQueue.clear();
395
break;
396
}
397
Block target = block(plantQueue.peekFirst());
398
if (target == null || !canPlantOn(target, activeCrop)) {
399
plantQueue.pollFirst();
400
continue;
401
}
402
if (beginPathToBlock(target, State.MOVING_TO_PLANT)) return;
403
plantQueue.pollFirst();
404
}
405
beginReturnToChest();
406
}
407
408
private boolean canPlantOn(Block cropSpace, CropRegistry.Crop crop) {
409
if (!crop.farmland()) return false;
410
return cropSpace.getType().isAir() && cropSpace.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;
411
}
412
413
private void beginReturnToChest() {
414
plantQueue.clear();
415
activeCrop = null;
416
cropTarget = null;
417
418
if (cargo.isEmpty()) {
419
state = State.IDLE;
420
nextScanTick = clock + scanInterval;
421
return;
422
}
423
if (chest == null && !bindNearestChest()) {
424
state = State.IDLE;
425
nextScanTick = clock + scanInterval;
426
return;
427
}
428
429
Block chestBlock = block(chest);
430
if (chestBlock == null || !beginPathToBlock(chestBlock, State.MOVING_TO_CHEST)) {
431
markChestUnreachable(chest);
432
clearChest();
433
state = State.IDLE;
434
nextScanTick = clock + scanInterval;
435
}
436
}
437
438
private void deposit(Block chestBlock) {
439
BlockState state = chestBlock.getState();
440
if (!(state instanceof InventoryHolder holder)) {
441
clearChest();
442
this.state = State.IDLE;
443
nextScanTick = clock;
444
return;
445
}
446
447
Inventory inventory = holder.getInventory();
448
List<ItemStack> leftovers = new ArrayList<>();
449
for (ItemStack item : cargo.snapshot()) {
450
Map<Integer, ItemStack> notInserted = inventory.addItem(item.clone());
451
leftovers.addAll(notInserted.values());
452
}
453
cargo.replaceWith(leftovers);
454
455
if (cargo.isEmpty()) {
456
this.state = State.IDLE;
457
nextScanTick = clock + scanInterval;
458
} else {
459
this.state = State.WAITING_FOR_CHEST_SPACE;
460
nextScanTick = clock + scanInterval;
461
}
462
}
463
464
private Block findMatureCrop() {
465
Block chestBlock = block(chest);
466
if (chestBlock == null) return null;
467
World world = chestBlock.getWorld();
468
int radiusSquared = cropRadius * cropRadius;
469
Location golemLocation = golem.getLocation();
470
List<Block> candidates = new ArrayList<>();
471
472
int minY = Math.max(world.getMinHeight(), chestBlock.getY() - cropRadius);
473
int maxY = Math.min(world.getMaxHeight() - 1, chestBlock.getY() + cropRadius);
474
475
for (int x = chestBlock.getX() - cropRadius; x <= chestBlock.getX() + cropRadius; x++) {
476
for (int z = chestBlock.getZ() - cropRadius; z <= chestBlock.getZ() + cropRadius; z++) {
477
if (!world.isChunkLoaded(x >> 4, z >> 4)) continue;
478
int dx = x - chestBlock.getX();
479
int dz = z - chestBlock.getZ();
480
for (int y = minY; y <= maxY; y++) {
481
int dy = y - chestBlock.getY();
482
if (dx * dx + dy * dy + dz * dz > radiusSquared) continue;
483
Block block = world.getBlockAt(x, y, z);
484
if (!cropRegistry.isReady(block)) continue;
485
BlockRef ref = BlockRef.of(block);
486
Long blockedUntil = unreachableCrops.get(ref);
487
if (blockedUntil != null && blockedUntil > clock) continue;
488
candidates.add(block);
489
}
490
}
491
}
492
493
return candidates.stream()
494
.min(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)
495
.distanceSquared(golemLocation)))
496
.orElse(null);
497
}
498
499
private boolean bindNearestChest() {
500
Location origin = golem.getLocation();
501
World world = golem.getWorld();
502
int centerX = golem.getChunk().getX();
503
int centerZ = golem.getChunk().getZ();
504
Block best = null;
505
double bestDistance = Double.MAX_VALUE;
506
507
for (int cx = centerX - chestChunkRadius; cx <= centerX + chestChunkRadius; cx++) {
508
for (int cz = centerZ - chestChunkRadius; cz <= centerZ + chestChunkRadius; cz++) {
509
if (!world.isChunkLoaded(cx, cz)) continue;
510
Chunk chunk = world.getChunkAt(cx, cz);
511
for (BlockState tile : chunk.getTileEntities()) {
512
Block block = tile.getBlock();
513
if (!isCopperChest(block)) continue;
514
BlockRef ref = BlockRef.of(block);
515
Long blockedUntil = unreachableChests.get(ref);
516
if (blockedUntil != null && blockedUntil > clock) continue;
517
double distance = block.getLocation().add(0.5, 0.5, 0.5).distanceSquared(origin);
518
if (distance < bestDistance) {
519
bestDistance = distance;
520
best = block;
521
}
522
}
523
}
524
}
525
526
if (best == null) return false;
527
chest = BlockRef.of(best);
528
saveChest(golem, chest);
529
return true;
530
}
531
532
private boolean beginPath(Location destination, State newState) {
533
navigationTarget = destination.clone();
534
pathRetries = 0;
535
lastProgressLocation = golem.getLocation().clone();
536
lastProgressTick = clock;
537
state = newState;
538
539
// If native navigation considers this too close to build a path, the
540
// state machine can still perform the action on the next brain tick.
541
if (reachedNavigationTarget()) {
542
golem.getPathfinder().stopPathfinding();
543
return true;
544
}
545
return golem.getPathfinder().moveTo(destination, moveSpeed);
546
}
547
548
private boolean navigationHealthy() {
549
if (navigationTarget == null) return false;
550
Location now = golem.getLocation();
551
552
if (lastProgressLocation == null || lastProgressLocation.getWorld() != now.getWorld()
553
|| lastProgressLocation.distanceSquared(now) >= 0.04) {
554
lastProgressLocation = now.clone();
555
lastProgressTick = clock;
556
}
557
558
Pathfinder pathfinder = golem.getPathfinder();
559
if (!pathfinder.hasPath()) return false;
560
return clock - lastProgressTick < stuckTimeout;
561
}
562
563
private boolean retryPath() {
564
if (navigationTarget == null || pathRetries >= maxPathRetries) return false;
565
pathRetries++;
566
lastProgressLocation = golem.getLocation().clone();
567
lastProgressTick = clock;
568
return golem.getPathfinder().moveTo(navigationTarget, moveSpeed);
569
}
570
571
private boolean beginPathToBlock(Block target, State newState) {
572
if (target == null) return false;
573
574
List<Block> positions = new ArrayList<>();
575
for (BlockFace face : HORIZONTAL) {
576
Block feet = target.getRelative(face);
577
if (isStandable(feet)) positions.add(feet);
578
}
579
positions.sort(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)
580
.distanceSquared(golem.getLocation())));
581
582
// Try each valid side once. After a side has produced a native path,
583
// Minecraft owns that path; we do not recalculate it every brain tick.
584
for (Block feet : positions) {
585
if (beginPath(feet.getLocation().add(0.5, 0.0, 0.5), newState)) return true;
586
}
587
return false;
588
}
589
590
private boolean reachedNavigationTarget() {
591
if (navigationTarget == null || navigationTarget.getWorld() != golem.getWorld()) return false;
592
Location now = golem.getLocation();
593
594
// Being inside the selected work block is an unambiguous arrival.
595
if (now.getBlockX() == navigationTarget.getBlockX()
596
&& now.getBlockY() == navigationTarget.getBlockY()
597
&& now.getBlockZ() == navigationTarget.getBlockZ()) {
598
return true;
599
}
600
601
// Native navigation may stop slightly short of the exact block centre.
602
return now.distanceSquared(navigationTarget) <= 1.25 * 1.25;
603
}
604
605
private boolean isStandable(Block feet) {
606
if (!feet.isPassable() || !feet.getRelative(BlockFace.UP).isPassable()) return false;
607
Material below = feet.getRelative(BlockFace.DOWN).getType();
608
return below.isSolid() || below == Material.FARMLAND;
609
}
610
611
private boolean near(Block block) {
612
if (block == null || block.getWorld() != golem.getWorld()) return false;
613
return golem.getLocation().distanceSquared(block.getLocation().add(0.5, 0.5, 0.5)) <= actionDistanceSquared;
614
}
615
616
private boolean withinCropRadius(Block block) {
617
Block chestBlock = block(chest);
618
if (chestBlock == null || block.getWorld() != chestBlock.getWorld()) return false;
619
int dx = block.getX() - chestBlock.getX();
620
int dy = block.getY() - chestBlock.getY();
621
int dz = block.getZ() - chestBlock.getZ();
622
return dx * dx + dy * dy + dz * dz <= cropRadius * cropRadius;
623
}
624
625
private void resetCropTask() {
626
stopNavigation();
627
cropTarget = null;
628
activeCrop = null;
629
plantQueue.clear();
630
state = State.IDLE;
631
nextScanTick = clock + scanInterval;
632
}
633
634
private void stopNavigation() {
635
golem.getPathfinder().stopPathfinding();
636
navigationTarget = null;
637
lastProgressLocation = null;
638
pathRetries = 0;
639
}
640
641
private void markCropUnreachable(BlockRef ref) {
642
if (ref != null) unreachableCrops.put(ref, clock + unreachableCooldown);
643
}
644
645
private void markChestUnreachable(BlockRef ref) {
646
if (ref != null) unreachableChests.put(ref, clock + unreachableCooldown);
647
}
648
649
private void cleanupCooldowns() {
650
unreachableCrops.entrySet().removeIf(entry -> entry.getValue() <= clock);
651
unreachableChests.entrySet().removeIf(entry -> entry.getValue() <= clock);
652
}
653
654
private void clearChest() {
655
chest = null;
656
PersistentDataContainer pdc = golem.getPersistentDataContainer();
657
pdc.remove(keys.chestWorld);
658
pdc.remove(keys.chestX);
659
pdc.remove(keys.chestY);
660
pdc.remove(keys.chestZ);
661
}
662
663
private boolean isChestValid(BlockRef ref) {
664
Block block = block(ref);
665
return isCopperChest(block);
666
}
667
}
668
669
private enum State {
670
IDLE,
671
MOVING_TO_CROP,
672
MOVING_TO_PLANT,
673
MOVING_TO_CHEST,
674
WAITING_FOR_CHEST_SPACE
675
}
676
677
private record BlockRef(UUID worldId, int x, int y, int z) {
678
static BlockRef of(Block block) {
679
return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
680
}
681
}
682
683
private Block block(BlockRef ref) {
684
if (ref == null) return null;
685
World world = Bukkit.getWorld(ref.worldId());
686
if (world == null || !world.isChunkLoaded(ref.x() >> 4, ref.z() >> 4)) return null;
687
return world.getBlockAt(ref.x(), ref.y(), ref.z());
688
}
689
690
private boolean isCopperChest(Block block) {
691
return block != null && block.getType().name().endsWith("COPPER_CHEST");
692
}
693
694
private BlockRef loadChest(CopperGolem golem) {
695
PersistentDataContainer pdc = golem.getPersistentDataContainer();
696
String worldString = pdc.get(keys.chestWorld, PersistentDataType.STRING);
697
Integer x = pdc.get(keys.chestX, PersistentDataType.INTEGER);
698
Integer y = pdc.get(keys.chestY, PersistentDataType.INTEGER);
699
Integer z = pdc.get(keys.chestZ, PersistentDataType.INTEGER);
700
if (worldString == null || x == null || y == null || z == null) return null;
701
try {
702
return new BlockRef(UUID.fromString(worldString), x, y, z);
703
} catch (IllegalArgumentException ex) {
704
return null;
705
}
706
}
707
708
private void saveChest(CopperGolem golem, BlockRef chest) {
709
PersistentDataContainer pdc = golem.getPersistentDataContainer();
710
pdc.set(keys.chestWorld, PersistentDataType.STRING, chest.worldId().toString());
711
pdc.set(keys.chestX, PersistentDataType.INTEGER, chest.x());
712
pdc.set(keys.chestY, PersistentDataType.INTEGER, chest.y());
713
pdc.set(keys.chestZ, PersistentDataType.INTEGER, chest.z());
714
}
715
}
@@ -0,0 +1,715 @@1
package nl.timfalken.copperfarmer;2
3
import com.destroystokyo.paper.entity.Pathfinder;4
import org.bukkit.Bukkit;5
import org.bukkit.Chunk;6
import org.bukkit.Location;7
import org.bukkit.Material;8
import org.bukkit.World;9
import org.bukkit.block.Block;10
import org.bukkit.block.BlockFace;11
import org.bukkit.block.BlockState;12
import org.bukkit.block.data.Ageable;13
import org.bukkit.block.data.BlockData;14
import org.bukkit.entity.CopperGolem;15
import org.bukkit.entity.Entity;16
import org.bukkit.inventory.Inventory;17
import org.bukkit.inventory.InventoryHolder;18
import org.bukkit.inventory.ItemStack;19
import org.bukkit.persistence.PersistentDataContainer;20
import org.bukkit.persistence.PersistentDataType;21
import org.bukkit.plugin.Plugin;22
23
import java.util.ArrayDeque;24
import java.util.ArrayList;25
import java.util.Comparator;26
import java.util.Deque;27
import java.util.HashMap;28
import java.util.HashSet;29
import java.util.List;30
import java.util.Map;31
import java.util.Set;32
import java.util.UUID;33
34
final class FarmerManager {35
private static final BlockFace[] HORIZONTAL = {36
BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST37
};38
39
private final Plugin plugin;40
private final FarmerKeys keys;41
private final CropRegistry cropRegistry;42
private final SeedRecipeCache seedRecipes;43
private final FarmerItemCodec itemCodec;44
private final Map<UUID, Brain> brains = new HashMap<>();45
46
private final int chestChunkRadius;47
private final int cropRadius;48
private final long scanInterval;49
private final double moveSpeed;50
private final long stuckTimeout;51
private final int maxPathRetries;52
private final long unreachableCooldown;53
private final double actionDistanceSquared;54
private final int cargoSlots;55
private final boolean preventOxidation;56
57
private long clock;58
59
FarmerManager(Plugin plugin, FarmerKeys keys, CropRegistry cropRegistry, SeedRecipeCache seedRecipes,60
FarmerItemCodec itemCodec) {61
this.plugin = plugin;62
this.keys = keys;63
this.cropRegistry = cropRegistry;64
this.seedRecipes = seedRecipes;65
this.itemCodec = itemCodec;66
this.chestChunkRadius = Math.max(0, plugin.getConfig().getInt("chest-search-chunk-radius", 2));67
this.cropRadius = Math.max(1, plugin.getConfig().getInt("crop-radius", 15));68
this.scanInterval = Math.max(20, plugin.getConfig().getLong("scan-interval-ticks", 200));69
this.moveSpeed = Math.max(0.1, plugin.getConfig().getDouble("move-speed", 1.0));70
this.stuckTimeout = Math.max(20, plugin.getConfig().getLong("stuck-timeout-ticks", 60));71
this.maxPathRetries = Math.max(0, plugin.getConfig().getInt("max-path-retries", 1));72
this.unreachableCooldown = Math.max(20, plugin.getConfig().getLong("unreachable-crop-cooldown-ticks", 600));73
double actionDistance = Math.max(1.25, plugin.getConfig().getDouble("action-distance", 2.25));74
this.actionDistanceSquared = actionDistance * actionDistance;75
this.cargoSlots = Math.max(1, plugin.getConfig().getInt("cargo-slots", 9));76
this.preventOxidation = plugin.getConfig().getBoolean("prevent-oxidation", true);77
}78
79
void tick(long elapsedTicks) {80
clock += elapsedTicks;81
var iterator = brains.entrySet().iterator();82
while (iterator.hasNext()) {83
Brain brain = iterator.next().getValue();84
if (!brain.golem.isValid() || brain.golem.isDead()) {85
iterator.remove();86
continue;87
}88
try {89
brain.tick();90
} catch (RuntimeException ex) {91
plugin.getLogger().warning("Farmer " + brain.golem.getUniqueId() + " tick failed: " + ex.getMessage());92
}93
}94
}95
96
void register(CopperGolem golem) {97
if (!isFarmer(golem)) return;98
configureEntity(golem);99
brains.computeIfAbsent(golem.getUniqueId(), ignored -> new Brain(golem));100
}101
102
void unregister(Entity entity) {103
brains.remove(entity.getUniqueId());104
}105
106
boolean isFarmer(Entity entity) {107
return entity instanceof CopperGolem108
&& entity.getPersistentDataContainer().has(keys.farmerEntity, PersistentDataType.BYTE);109
}110
111
void configureEntity(CopperGolem golem) {112
plugin.getServer().getMobGoals().removeAllGoals(golem);113
golem.setAI(true);114
golem.setAware(true);115
golem.setCanPickupItems(false);116
golem.getPathfinder().setCanFloat(true);117
golem.getPathfinder().setCanPassDoors(true);118
golem.getPathfinder().setCanOpenDoors(false);119
golem.setGolemState(CopperGolem.State.IDLE);120
if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());121
var equipment = golem.getEquipment();122
if (equipment != null) {123
equipment.setItemInMainHand(itemCodec.readTool(golem));124
equipment.setItemInMainHandDropChance(0.0f);125
}126
}127
128
List<ItemStack> deathDrops(CopperGolem golem) {129
Brain brain = brains.remove(golem.getUniqueId());130
FarmerCargo cargo = brain != null ? brain.cargo : new FarmerCargo(golem, keys, cargoSlots);131
ItemStack tool = brain != null ? brain.tool.clone() : itemCodec.readTool(golem);132
List<ItemStack> drops = new ArrayList<>();133
drops.add(tool);134
drops.addAll(cargo.snapshot());135
cargo.clear();136
return drops;137
}138
139
private final class Brain {140
private final CopperGolem golem;141
private final FarmerCargo cargo;142
private final ItemStack tool;143
private State state = State.IDLE;144
private BlockRef chest;145
private BlockRef cropTarget;146
private CropRegistry.Crop activeCrop;147
private final Deque<BlockRef> plantQueue = new ArrayDeque<>();148
private final Map<BlockRef, Long> unreachableCrops = new HashMap<>();149
private final Map<BlockRef, Long> unreachableChests = new HashMap<>();150
151
private Location navigationTarget;152
private Location lastProgressLocation;153
private long lastProgressTick;154
private int pathRetries;155
private long nextScanTick;156
157
Brain(CopperGolem golem) {158
this.golem = golem;159
this.cargo = new FarmerCargo(golem, keys, cargoSlots);160
this.tool = itemCodec.readTool(golem);161
this.chest = loadChest(golem);162
this.nextScanTick = clock;163
}164
165
void tick() {166
if (preventOxidation && golem.getOxidizing() != CopperGolem.Oxidizing.waxed()) {167
golem.setOxidizing(CopperGolem.Oxidizing.waxed());168
}169
cleanupCooldowns();170
171
if (!isChestValid(chest)) {172
clearChest();173
}174
175
switch (state) {176
case IDLE -> tickIdle();177
case MOVING_TO_CROP -> tickMovingToCrop();178
case MOVING_TO_PLANT -> tickMovingToPlant();179
case MOVING_TO_CHEST -> tickMovingToChest();180
case WAITING_FOR_CHEST_SPACE -> tickWaitingForChestSpace();181
}182
}183
184
private void tickIdle() {185
if (chest == null) {186
if (clock < nextScanTick) return;187
nextScanTick = clock + scanInterval;188
if (!bindNearestChest()) return;189
}190
191
if (!cargo.isEmpty()) {192
beginReturnToChest();193
return;194
}195
196
if (clock < nextScanTick) return;197
nextScanTick = clock + scanInterval;198
199
Block target = findMatureCrop();200
if (target == null) return;201
202
CropRegistry.Crop crop = cropRegistry.get(target.getType());203
if (crop == null) {204
markCropUnreachable(BlockRef.of(target));205
return;206
}207
208
cropTarget = BlockRef.of(target);209
activeCrop = crop;210
if (!beginPathToBlock(target, State.MOVING_TO_CROP)) {211
markCropUnreachable(cropTarget);212
cropTarget = null;213
activeCrop = null;214
state = State.IDLE;215
}216
}217
218
private void tickMovingToCrop() {219
Block cropBlock = block(cropTarget);220
if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()221
|| !cropRegistry.isReady(cropBlock)) {222
stopNavigation();223
resetCropTask();224
return;225
}226
227
if (reachedNavigationTarget() && near(cropBlock)) {228
stopNavigation();229
harvest(cropBlock, activeCrop);230
return;231
}232
233
if (!navigationHealthy()) {234
if (!retryPath()) {235
markCropUnreachable(cropTarget);236
resetCropTask();237
}238
}239
}240
241
private void tickMovingToPlant() {242
if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {243
plantQueue.clear();244
beginReturnToChest();245
return;246
}247
248
BlockRef targetRef = plantQueue.peekFirst();249
Block target = block(targetRef);250
if (target == null || !canPlantOn(target, activeCrop)) {251
plantQueue.pollFirst();252
advancePlantQueue();253
return;254
}255
256
if (reachedNavigationTarget() && near(target)) {257
stopNavigation();258
if (cargo.remove(activeCrop.seed(), 1)) {259
golem.swingMainHand();260
target.setType(activeCrop.block(), false);261
}262
plantQueue.pollFirst();263
advancePlantQueue();264
return;265
}266
267
if (!navigationHealthy() && !retryPath()) {268
plantQueue.pollFirst();269
advancePlantQueue();270
}271
}272
273
private void tickMovingToChest() {274
Block chestBlock = block(chest);275
if (!isCopperChest(chestBlock)) {276
clearChest();277
state = State.IDLE;278
nextScanTick = clock;279
return;280
}281
282
if (reachedNavigationTarget() && near(chestBlock)) {283
stopNavigation();284
deposit(chestBlock);285
return;286
}287
288
if (!navigationHealthy() && !retryPath()) {289
markChestUnreachable(chest);290
clearChest();291
state = State.IDLE;292
nextScanTick = clock;293
}294
}295
296
private void tickWaitingForChestSpace() {297
if (cargo.isEmpty()) {298
state = State.IDLE;299
nextScanTick = clock + scanInterval;300
return;301
}302
if (!isChestValid(chest)) {303
clearChest();304
state = State.IDLE;305
nextScanTick = clock;306
return;307
}308
if (clock >= nextScanTick) {309
nextScanTick = clock + scanInterval;310
beginReturnToChest();311
}312
}313
314
private void harvest(Block cropBlock, CropRegistry.Crop crop) {315
golem.swingMainHand();316
BlockData oldData = cropBlock.getBlockData().clone();317
List<ItemStack> calculatedDrops = new ArrayList<>(cropBlock.getDrops(tool.clone(), golem));318
319
cropBlock.setType(Material.AIR, false);320
List<ItemStack> overflow = cargo.addAll(calculatedDrops);321
for (ItemStack item : overflow) {322
cropBlock.getWorld().dropItemNaturally(cropBlock.getLocation().add(0.5, 0.5, 0.5), item);323
}324
325
if (!crop.breakOnlyFruit()) {326
ensureSeed(crop.seed());327
if (cargo.remove(crop.seed(), 1)) {328
if (oldData instanceof Ageable ageable) ageable.setAge(0);329
cropBlock.setBlockData(oldData, false);330
}331
}332
333
cropTarget = null;334
335
if (!crop.breakOnlyFruit() && crop.farmland() && cargo.count(crop.seed()) > 0) {336
buildPlantQueue(cropBlock, crop);337
if (!plantQueue.isEmpty()) {338
activeCrop = crop;339
advancePlantQueue();340
return;341
}342
}343
344
activeCrop = null;345
beginReturnToChest();346
}347
348
private boolean ensureSeed(Material requiredSeed) {349
if (cargo.count(requiredSeed) > 0) return true;350
for (ItemStack stack : cargo.snapshot()) {351
SeedRecipeCache.Conversion conversion = seedRecipes.find(stack.getType(), requiredSeed);352
if (conversion == null || cargo.count(conversion.input()) < conversion.inputCount()) continue;353
if (!cargo.remove(conversion.input(), conversion.inputCount())) continue;354
ItemStack overflow = cargo.add(conversion.output());355
if (overflow != null && !overflow.isEmpty()) {356
// The recipe was legitimately crafted; if the internal bag cannot357
// contain all output, spill only that excess into the world.358
golem.getWorld().dropItemNaturally(golem.getLocation(), overflow);359
}360
return cargo.count(requiredSeed) > 0;361
}362
return false;363
}364
365
private void buildPlantQueue(Block harvestedCropBlock, CropRegistry.Crop crop) {366
plantQueue.clear();367
Block startFarmland = harvestedCropBlock.getRelative(BlockFace.DOWN);368
if (startFarmland.getType() != Material.FARMLAND) return;369
370
Set<BlockRef> visited = new HashSet<>();371
Deque<Block> search = new ArrayDeque<>();372
search.add(startFarmland);373
visited.add(BlockRef.of(startFarmland));374
375
while (!search.isEmpty()) {376
Block farmland = search.pollFirst();377
Block above = farmland.getRelative(BlockFace.UP);378
if (above.getType().isAir() && withinCropRadius(above) && canPlantOn(above, crop)) {379
plantQueue.add(BlockRef.of(above));380
}381
382
for (BlockFace face : HORIZONTAL) {383
Block next = farmland.getRelative(face);384
if (next.getType() != Material.FARMLAND || !withinCropRadius(next)) continue;385
BlockRef ref = BlockRef.of(next);386
if (visited.add(ref)) search.addLast(next);387
}388
}389
}390
391
private void advancePlantQueue() {392
while (!plantQueue.isEmpty()) {393
if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {394
plantQueue.clear();395
break;396
}397
Block target = block(plantQueue.peekFirst());398
if (target == null || !canPlantOn(target, activeCrop)) {399
plantQueue.pollFirst();400
continue;401
}402
if (beginPathToBlock(target, State.MOVING_TO_PLANT)) return;403
plantQueue.pollFirst();404
}405
beginReturnToChest();406
}407
408
private boolean canPlantOn(Block cropSpace, CropRegistry.Crop crop) {409
if (!crop.farmland()) return false;410
return cropSpace.getType().isAir() && cropSpace.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;411
}412
413
private void beginReturnToChest() {414
plantQueue.clear();415
activeCrop = null;416
cropTarget = null;417
418
if (cargo.isEmpty()) {419
state = State.IDLE;420
nextScanTick = clock + scanInterval;421
return;422
}423
if (chest == null && !bindNearestChest()) {424
state = State.IDLE;425
nextScanTick = clock + scanInterval;426
return;427
}428
429
Block chestBlock = block(chest);430
if (chestBlock == null || !beginPathToBlock(chestBlock, State.MOVING_TO_CHEST)) {431
markChestUnreachable(chest);432
clearChest();433
state = State.IDLE;434
nextScanTick = clock + scanInterval;435
}436
}437
438
private void deposit(Block chestBlock) {439
BlockState state = chestBlock.getState();440
if (!(state instanceof InventoryHolder holder)) {441
clearChest();442
this.state = State.IDLE;443
nextScanTick = clock;444
return;445
}446
447
Inventory inventory = holder.getInventory();448
List<ItemStack> leftovers = new ArrayList<>();449
for (ItemStack item : cargo.snapshot()) {450
Map<Integer, ItemStack> notInserted = inventory.addItem(item.clone());451
leftovers.addAll(notInserted.values());452
}453
cargo.replaceWith(leftovers);454
455
if (cargo.isEmpty()) {456
this.state = State.IDLE;457
nextScanTick = clock + scanInterval;458
} else {459
this.state = State.WAITING_FOR_CHEST_SPACE;460
nextScanTick = clock + scanInterval;461
}462
}463
464
private Block findMatureCrop() {465
Block chestBlock = block(chest);466
if (chestBlock == null) return null;467
World world = chestBlock.getWorld();468
int radiusSquared = cropRadius * cropRadius;469
Location golemLocation = golem.getLocation();470
List<Block> candidates = new ArrayList<>();471
472
int minY = Math.max(world.getMinHeight(), chestBlock.getY() - cropRadius);473
int maxY = Math.min(world.getMaxHeight() - 1, chestBlock.getY() + cropRadius);474
475
for (int x = chestBlock.getX() - cropRadius; x <= chestBlock.getX() + cropRadius; x++) {476
for (int z = chestBlock.getZ() - cropRadius; z <= chestBlock.getZ() + cropRadius; z++) {477
if (!world.isChunkLoaded(x >> 4, z >> 4)) continue;478
int dx = x - chestBlock.getX();479
int dz = z - chestBlock.getZ();480
for (int y = minY; y <= maxY; y++) {481
int dy = y - chestBlock.getY();482
if (dx * dx + dy * dy + dz * dz > radiusSquared) continue;483
Block block = world.getBlockAt(x, y, z);484
if (!cropRegistry.isReady(block)) continue;485
BlockRef ref = BlockRef.of(block);486
Long blockedUntil = unreachableCrops.get(ref);487
if (blockedUntil != null && blockedUntil > clock) continue;488
candidates.add(block);489
}490
}491
}492
493
return candidates.stream()494
.min(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)495
.distanceSquared(golemLocation)))496
.orElse(null);497
}498
499
private boolean bindNearestChest() {500
Location origin = golem.getLocation();501
World world = golem.getWorld();502
int centerX = golem.getChunk().getX();503
int centerZ = golem.getChunk().getZ();504
Block best = null;505
double bestDistance = Double.MAX_VALUE;506
507
for (int cx = centerX - chestChunkRadius; cx <= centerX + chestChunkRadius; cx++) {508
for (int cz = centerZ - chestChunkRadius; cz <= centerZ + chestChunkRadius; cz++) {509
if (!world.isChunkLoaded(cx, cz)) continue;510
Chunk chunk = world.getChunkAt(cx, cz);511
for (BlockState tile : chunk.getTileEntities()) {512
Block block = tile.getBlock();513
if (!isCopperChest(block)) continue;514
BlockRef ref = BlockRef.of(block);515
Long blockedUntil = unreachableChests.get(ref);516
if (blockedUntil != null && blockedUntil > clock) continue;517
double distance = block.getLocation().add(0.5, 0.5, 0.5).distanceSquared(origin);518
if (distance < bestDistance) {519
bestDistance = distance;520
best = block;521
}522
}523
}524
}525
526
if (best == null) return false;527
chest = BlockRef.of(best);528
saveChest(golem, chest);529
return true;530
}531
532
private boolean beginPath(Location destination, State newState) {533
navigationTarget = destination.clone();534
pathRetries = 0;535
lastProgressLocation = golem.getLocation().clone();536
lastProgressTick = clock;537
state = newState;538
539
// If native navigation considers this too close to build a path, the540
// state machine can still perform the action on the next brain tick.541
if (reachedNavigationTarget()) {542
golem.getPathfinder().stopPathfinding();543
return true;544
}545
return golem.getPathfinder().moveTo(destination, moveSpeed);546
}547
548
private boolean navigationHealthy() {549
if (navigationTarget == null) return false;550
Location now = golem.getLocation();551
552
if (lastProgressLocation == null || lastProgressLocation.getWorld() != now.getWorld()553
|| lastProgressLocation.distanceSquared(now) >= 0.04) {554
lastProgressLocation = now.clone();555
lastProgressTick = clock;556
}557
558
Pathfinder pathfinder = golem.getPathfinder();559
if (!pathfinder.hasPath()) return false;560
return clock - lastProgressTick < stuckTimeout;561
}562
563
private boolean retryPath() {564
if (navigationTarget == null || pathRetries >= maxPathRetries) return false;565
pathRetries++;566
lastProgressLocation = golem.getLocation().clone();567
lastProgressTick = clock;568
return golem.getPathfinder().moveTo(navigationTarget, moveSpeed);569
}570
571
private boolean beginPathToBlock(Block target, State newState) {572
if (target == null) return false;573
574
List<Block> positions = new ArrayList<>();575
for (BlockFace face : HORIZONTAL) {576
Block feet = target.getRelative(face);577
if (isStandable(feet)) positions.add(feet);578
}579
positions.sort(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)580
.distanceSquared(golem.getLocation())));581
582
// Try each valid side once. After a side has produced a native path,583
// Minecraft owns that path; we do not recalculate it every brain tick.584
for (Block feet : positions) {585
if (beginPath(feet.getLocation().add(0.5, 0.0, 0.5), newState)) return true;586
}587
return false;588
}589
590
private boolean reachedNavigationTarget() {591
if (navigationTarget == null || navigationTarget.getWorld() != golem.getWorld()) return false;592
Location now = golem.getLocation();593
594
// Being inside the selected work block is an unambiguous arrival.595
if (now.getBlockX() == navigationTarget.getBlockX()596
&& now.getBlockY() == navigationTarget.getBlockY()597
&& now.getBlockZ() == navigationTarget.getBlockZ()) {598
return true;599
}600
601
// Native navigation may stop slightly short of the exact block centre.602
return now.distanceSquared(navigationTarget) <= 1.25 * 1.25;603
}604
605
private boolean isStandable(Block feet) {606
if (!feet.isPassable() || !feet.getRelative(BlockFace.UP).isPassable()) return false;607
Material below = feet.getRelative(BlockFace.DOWN).getType();608
return below.isSolid() || below == Material.FARMLAND;609
}610
611
private boolean near(Block block) {612
if (block == null || block.getWorld() != golem.getWorld()) return false;613
return golem.getLocation().distanceSquared(block.getLocation().add(0.5, 0.5, 0.5)) <= actionDistanceSquared;614
}615
616
private boolean withinCropRadius(Block block) {617
Block chestBlock = block(chest);618
if (chestBlock == null || block.getWorld() != chestBlock.getWorld()) return false;619
int dx = block.getX() - chestBlock.getX();620
int dy = block.getY() - chestBlock.getY();621
int dz = block.getZ() - chestBlock.getZ();622
return dx * dx + dy * dy + dz * dz <= cropRadius * cropRadius;623
}624
625
private void resetCropTask() {626
stopNavigation();627
cropTarget = null;628
activeCrop = null;629
plantQueue.clear();630
state = State.IDLE;631
nextScanTick = clock + scanInterval;632
}633
634
private void stopNavigation() {635
golem.getPathfinder().stopPathfinding();636
navigationTarget = null;637
lastProgressLocation = null;638
pathRetries = 0;639
}640
641
private void markCropUnreachable(BlockRef ref) {642
if (ref != null) unreachableCrops.put(ref, clock + unreachableCooldown);643
}644
645
private void markChestUnreachable(BlockRef ref) {646
if (ref != null) unreachableChests.put(ref, clock + unreachableCooldown);647
}648
649
private void cleanupCooldowns() {650
unreachableCrops.entrySet().removeIf(entry -> entry.getValue() <= clock);651
unreachableChests.entrySet().removeIf(entry -> entry.getValue() <= clock);652
}653
654
private void clearChest() {655
chest = null;656
PersistentDataContainer pdc = golem.getPersistentDataContainer();657
pdc.remove(keys.chestWorld);658
pdc.remove(keys.chestX);659
pdc.remove(keys.chestY);660
pdc.remove(keys.chestZ);661
}662
663
private boolean isChestValid(BlockRef ref) {664
Block block = block(ref);665
return isCopperChest(block);666
}667
}668
669
private enum State {670
IDLE,671
MOVING_TO_CROP,672
MOVING_TO_PLANT,673
MOVING_TO_CHEST,674
WAITING_FOR_CHEST_SPACE675
}676
677
private record BlockRef(UUID worldId, int x, int y, int z) {678
static BlockRef of(Block block) {679
return new BlockRef(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());680
}681
}682
683
private Block block(BlockRef ref) {684
if (ref == null) return null;685
World world = Bukkit.getWorld(ref.worldId());686
if (world == null || !world.isChunkLoaded(ref.x() >> 4, ref.z() >> 4)) return null;687
return world.getBlockAt(ref.x(), ref.y(), ref.z());688
}689
690
private boolean isCopperChest(Block block) {691
return block != null && block.getType().name().endsWith("COPPER_CHEST");692
}693
694
private BlockRef loadChest(CopperGolem golem) {695
PersistentDataContainer pdc = golem.getPersistentDataContainer();696
String worldString = pdc.get(keys.chestWorld, PersistentDataType.STRING);697
Integer x = pdc.get(keys.chestX, PersistentDataType.INTEGER);698
Integer y = pdc.get(keys.chestY, PersistentDataType.INTEGER);699
Integer z = pdc.get(keys.chestZ, PersistentDataType.INTEGER);700
if (worldString == null || x == null || y == null || z == null) return null;701
try {702
return new BlockRef(UUID.fromString(worldString), x, y, z);703
} catch (IllegalArgumentException ex) {704
return null;705
}706
}707
708
private void saveChest(CopperGolem golem, BlockRef chest) {709
PersistentDataContainer pdc = golem.getPersistentDataContainer();710
pdc.set(keys.chestWorld, PersistentDataType.STRING, chest.worldId().toString());711
pdc.set(keys.chestX, PersistentDataType.INTEGER, chest.x());712
pdc.set(keys.chestY, PersistentDataType.INTEGER, chest.y());713
pdc.set(keys.chestZ, PersistentDataType.INTEGER, chest.z());714
}715
}@@ -0,0 +1,102 @@
1
package nl.timfalken.copperfarmer;
2
3
import org.bukkit.Bukkit;
4
import org.bukkit.Material;
5
import org.bukkit.inventory.ItemStack;
6
import org.bukkit.inventory.Recipe;
7
import org.bukkit.inventory.RecipeChoice;
8
import org.bukkit.inventory.ShapedRecipe;
9
import org.bukkit.inventory.ShapelessRecipe;
10
import org.bukkit.plugin.Plugin;
11
12
import java.util.ArrayList;
13
import java.util.EnumMap;
14
import java.util.Iterator;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
19
final class SeedRecipeCache {
20
record Conversion(Material input, int inputCount, ItemStack output) {}
21
22
private final Plugin plugin;
23
private final Set<Material> acceptedSeedOutputs;
24
private final Map<Material, List<Conversion>> byInput = new EnumMap<>(Material.class);
25
private int inspected;
26
private int cached;
27
28
SeedRecipeCache(Plugin plugin, Set<Material> acceptedSeedOutputs) {
29
this.plugin = plugin;
30
this.acceptedSeedOutputs = acceptedSeedOutputs;
31
}
32
33
void build() {
34
byInput.clear();
35
inspected = 0;
36
cached = 0;
37
38
Iterator<Recipe> iterator = Bukkit.recipeIterator();
39
while (iterator.hasNext()) {
40
Recipe recipe = iterator.next();
41
inspected++;
42
43
ItemStack result = recipe.getResult();
44
if (result.isEmpty() || !acceptedSeedOutputs.contains(result.getType())) continue;
45
46
List<RecipeChoice> ingredients = ingredientChoices(recipe);
47
if (ingredients == null || ingredients.isEmpty()) continue;
48
49
// We deliberately only infer conversions where every ingredient can be
50
// satisfied by the same material. That safely models "crop -> seed"
51
// without trying to become a general-purpose autocrafter.
52
for (Material material : Material.values()) {
53
if (!material.isItem() || material.isAir()) continue;
54
ItemStack test = new ItemStack(material);
55
boolean allMatch = true;
56
for (RecipeChoice choice : ingredients) {
57
if (choice == null || !choice.test(test)) {
58
allMatch = false;
59
break;
60
}
61
}
62
if (!allMatch) continue;
63
64
Conversion conversion = new Conversion(material, ingredients.size(), result.clone());
65
byInput.computeIfAbsent(material, ignored -> new ArrayList<>()).add(conversion);
66
cached++;
67
}
68
}
69
70
plugin.getLogger().info("Seed recipe cache: inspected " + inspected
71
+ " recipes, cached " + cached + " crop-to-seed material mappings.");
72
}
73
74
private List<RecipeChoice> ingredientChoices(Recipe recipe) {
75
if (recipe instanceof ShapelessRecipe shapeless) {
76
return new ArrayList<>(shapeless.getChoiceList());
77
}
78
if (recipe instanceof ShapedRecipe shaped) {
79
List<RecipeChoice> choices = new ArrayList<>();
80
Map<Character, RecipeChoice> choiceMap = shaped.getChoiceMap();
81
for (String row : shaped.getShape()) {
82
for (int i = 0; i < row.length(); i++) {
83
char symbol = row.charAt(i);
84
if (symbol == ' ') continue;
85
RecipeChoice choice = choiceMap.get(symbol);
86
if (choice != null) choices.add(choice);
87
}
88
}
89
return choices;
90
}
91
return null;
92
}
93
94
Conversion find(Material input, Material requiredSeed) {
95
List<Conversion> options = byInput.get(input);
96
if (options == null) return null;
97
for (Conversion conversion : options) {
98
if (conversion.output().getType() == requiredSeed) return conversion;
99
}
100
return null;
101
}
102
}
@@ -0,0 +1,102 @@1
package nl.timfalken.copperfarmer;2
3
import org.bukkit.Bukkit;4
import org.bukkit.Material;5
import org.bukkit.inventory.ItemStack;6
import org.bukkit.inventory.Recipe;7
import org.bukkit.inventory.RecipeChoice;8
import org.bukkit.inventory.ShapedRecipe;9
import org.bukkit.inventory.ShapelessRecipe;10
import org.bukkit.plugin.Plugin;11
12
import java.util.ArrayList;13
import java.util.EnumMap;14
import java.util.Iterator;15
import java.util.List;16
import java.util.Map;17
import java.util.Set;18
19
final class SeedRecipeCache {20
record Conversion(Material input, int inputCount, ItemStack output) {}21
22
private final Plugin plugin;23
private final Set<Material> acceptedSeedOutputs;24
private final Map<Material, List<Conversion>> byInput = new EnumMap<>(Material.class);25
private int inspected;26
private int cached;27
28
SeedRecipeCache(Plugin plugin, Set<Material> acceptedSeedOutputs) {29
this.plugin = plugin;30
this.acceptedSeedOutputs = acceptedSeedOutputs;31
}32
33
void build() {34
byInput.clear();35
inspected = 0;36
cached = 0;37
38
Iterator<Recipe> iterator = Bukkit.recipeIterator();39
while (iterator.hasNext()) {40
Recipe recipe = iterator.next();41
inspected++;42
43
ItemStack result = recipe.getResult();44
if (result.isEmpty() || !acceptedSeedOutputs.contains(result.getType())) continue;45
46
List<RecipeChoice> ingredients = ingredientChoices(recipe);47
if (ingredients == null || ingredients.isEmpty()) continue;48
49
// We deliberately only infer conversions where every ingredient can be50
// satisfied by the same material. That safely models "crop -> seed"51
// without trying to become a general-purpose autocrafter.52
for (Material material : Material.values()) {53
if (!material.isItem() || material.isAir()) continue;54
ItemStack test = new ItemStack(material);55
boolean allMatch = true;56
for (RecipeChoice choice : ingredients) {57
if (choice == null || !choice.test(test)) {58
allMatch = false;59
break;60
}61
}62
if (!allMatch) continue;63
64
Conversion conversion = new Conversion(material, ingredients.size(), result.clone());65
byInput.computeIfAbsent(material, ignored -> new ArrayList<>()).add(conversion);66
cached++;67
}68
}69
70
plugin.getLogger().info("Seed recipe cache: inspected " + inspected71
+ " recipes, cached " + cached + " crop-to-seed material mappings.");72
}73
74
private List<RecipeChoice> ingredientChoices(Recipe recipe) {75
if (recipe instanceof ShapelessRecipe shapeless) {76
return new ArrayList<>(shapeless.getChoiceList());77
}78
if (recipe instanceof ShapedRecipe shaped) {79
List<RecipeChoice> choices = new ArrayList<>();80
Map<Character, RecipeChoice> choiceMap = shaped.getChoiceMap();81
for (String row : shaped.getShape()) {82
for (int i = 0; i < row.length(); i++) {83
char symbol = row.charAt(i);84
if (symbol == ' ') continue;85
RecipeChoice choice = choiceMap.get(symbol);86
if (choice != null) choices.add(choice);87
}88
}89
return choices;90
}91
return null;92
}93
94
Conversion find(Material input, Material requiredSeed) {95
List<Conversion> options = byInput.get(input);96
if (options == null) return null;97
for (Conversion conversion : options) {98
if (conversion.output().getType() == requiredSeed) return conversion;99
}100
return null;101
}102
}@@ -0,0 +1,33 @@
1
# How many chunks around a newly spawned / chestless farmer are searched.
2
chest-search-chunk-radius: 2
3
4
# Crops must be within this Euclidean distance of the bound chest.
5
crop-radius: 15
6
7
# An idle farmer scans for a mature crop this often. 200 ticks = 10 seconds.
8
scan-interval-ticks: 200
9
10
# State-machine update interval. Pathfinding itself remains vanilla.
11
brain-tick-interval: 5
12
13
# Vanilla pathfinder speed multiplier. 1.0 = normal mob speed.
14
move-speed: 1.0
15
16
# Consider a farmer stuck after this many ticks without meaningful movement.
17
stuck-timeout-ticks: 60
18
19
# Number of fresh path calculations allowed after the initial path fails/stalls.
20
max-path-retries: 1
21
22
# Don't repeatedly select an unreachable crop until this cooldown expires.
23
unreachable-crop-cooldown-ticks: 600
24
25
# Distance from the target block at which harvesting/planting/depositing is allowed.
26
action-distance: 2.25
27
28
# Maximum internal cargo stacks. Partial stacks are combined first.
29
cargo-slots: 9
30
31
# Farmer golems are waxed internally so they do not eventually oxidise into statues.
32
# Set false if you deliberately want normal Copper Golem weathering.
33
prevent-oxidation: true
@@ -0,0 +1,33 @@1
# How many chunks around a newly spawned / chestless farmer are searched.2
chest-search-chunk-radius: 23
4
# Crops must be within this Euclidean distance of the bound chest.5
crop-radius: 156
7
# An idle farmer scans for a mature crop this often. 200 ticks = 10 seconds.8
scan-interval-ticks: 2009
10
# State-machine update interval. Pathfinding itself remains vanilla.11
brain-tick-interval: 512
13
# Vanilla pathfinder speed multiplier. 1.0 = normal mob speed.14
move-speed: 1.015
16
# Consider a farmer stuck after this many ticks without meaningful movement.17
stuck-timeout-ticks: 6018
19
# Number of fresh path calculations allowed after the initial path fails/stalls.20
max-path-retries: 121
22
# Don't repeatedly select an unreachable crop until this cooldown expires.23
unreachable-crop-cooldown-ticks: 60024
25
# Distance from the target block at which harvesting/planting/depositing is allowed.26
action-distance: 2.2527
28
# Maximum internal cargo stacks. Partial stacks are combined first.29
cargo-slots: 930
31
# Farmer golems are waxed internally so they do not eventually oxidise into statues.32
# Set false if you deliberately want normal Copper Golem weathering.33
prevent-oxidation: true@@ -0,0 +1,6 @@
1
name: CopperFarmer
2
version: 0.1.0
3
main: nl.timfalken.copperfarmer.CopperFarmerPlugin
4
api-version: '26.2'
5
author: Tim Falken
6
description: Copper Golems that farm crops and deliver their harvest to copper chests.
@@ -0,0 +1,6 @@1
name: CopperFarmer2
version: 0.1.03
main: nl.timfalken.copperfarmer.CopperFarmerPlugin4
api-version: '26.2'5
author: Tim Falken6
description: Copper Golems that farm crops and deliver their harvest to copper chests.