import 1.7.0
Still needs the 1.7.1 upgrade applied
@@ -0,0 +1,106 @@
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 (or PAT) with `write_repository`
5
# so the job can push the version-bump commit and move the tag.
6
#
7
# Flow:
8
# 1. validate — reject invalid or non-increasing versions
9
# 2. bump — update version in project files, push, retarget tag (ci.skip)
10
# 3. build — produce ContainerPipes-<version>.jar and upload to Package Registry
11
# 4. release — publish a GitLab Release with the jar attached
12
13
workflow:
14
rules:
15
- if: $CI_COMMIT_TAG
16
17
variables:
18
GIT_DEPTH: "0"
19
GIT_FETCH_EXTRA_FLAGS: "--tags"
20
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
21
22
stages:
23
- validate
24
- bump
25
- build
26
- release
27
28
.validate_image:
29
image: alpine:3.20
30
before_script:
31
- apk add --no-cache bash git grep coreutils
32
- git fetch --tags --force origin
33
- chmod +x scripts/release.sh
34
35
validate:version:
36
extends: .validate_image
37
stage: validate
38
script:
39
- ./scripts/release.sh validate
40
artifacts:
41
reports:
42
dotenv: version.env
43
paths:
44
- version.env
45
46
bump:version:
47
extends: .validate_image
48
stage: bump
49
needs:
50
- job: validate:version
51
artifacts: true
52
script:
53
- ./scripts/release.sh bump
54
artifacts:
55
reports:
56
dotenv: version.env
57
paths:
58
- version.env
59
- build.gradle.kts
60
- src/main/resources/plugin.yml
61
- README.md
62
- src/README-*.md
63
- src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java
64
65
build:jar:
66
stage: build
67
image: gradle:8.12-jdk21
68
needs:
69
- job: bump:version
70
artifacts: true
71
before_script:
72
- apt-get update -qq && apt-get install -y -qq curl >/dev/null
73
- chmod +x scripts/release.sh
74
# Checkout may still contain a previous src/README-*.md; keep only the bumped one.
75
- find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
76
script:
77
- test -n "${VERSION}"
78
- gradle --no-daemon clean jar
79
- test -f "build/libs/ContainerPipes-${VERSION}.jar"
80
- ls -la "build/libs/ContainerPipes-${VERSION}.jar"
81
- ./scripts/release.sh upload
82
artifacts:
83
reports:
84
dotenv: version.env
85
paths:
86
- "build/libs/ContainerPipes-*.jar"
87
- version.env
88
expire_in: 30 days
89
90
release:gitlab:
91
stage: release
92
image: registry.gitlab.com/gitlab-org/release-cli:latest
93
needs:
94
- job: build:jar
95
artifacts: true
96
script:
97
- echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"
98
release:
99
name: "ContainerPipes $VERSION"
100
tag_name: "$TAG"
101
description: "Release $VERSION of ContainerPipes."
102
assets:
103
links:
104
- name: "ContainerPipes-$VERSION.jar"
105
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/containerpipes/$VERSION/ContainerPipes-$VERSION.jar"
106
link_type: package
@@ -0,0 +1,106 @@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 (or PAT) with `write_repository`5
# so the job can push the version-bump commit and move the tag.6
#7
# Flow:8
# 1. validate — reject invalid or non-increasing versions9
# 2. bump — update version in project files, push, retarget tag (ci.skip)10
# 3. build — produce ContainerPipes-<version>.jar and upload to Package Registry11
# 4. release — publish a GitLab Release with the jar attached12
13
workflow:14
rules:15
- if: $CI_COMMIT_TAG16
17
variables:18
GIT_DEPTH: "0"19
GIT_FETCH_EXTRA_FLAGS: "--tags"20
GRADLE_OPTS: "-Dorg.gradle.daemon=false"21
22
stages:23
- validate24
- bump25
- build26
- release27
28
.validate_image:29
image: alpine:3.2030
before_script:31
- apk add --no-cache bash git grep coreutils32
- git fetch --tags --force origin33
- chmod +x scripts/release.sh34
35
validate:version:36
extends: .validate_image37
stage: validate38
script:39
- ./scripts/release.sh validate40
artifacts:41
reports:42
dotenv: version.env43
paths:44
- version.env45
46
bump:version:47
extends: .validate_image48
stage: bump49
needs:50
- job: validate:version51
artifacts: true52
script:53
- ./scripts/release.sh bump54
artifacts:55
reports:56
dotenv: version.env57
paths:58
- version.env59
- build.gradle.kts60
- src/main/resources/plugin.yml61
- README.md62
- src/README-*.md63
- src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java64
65
build:jar:66
stage: build67
image: gradle:8.12-jdk2168
needs:69
- job: bump:version70
artifacts: true71
before_script:72
- apt-get update -qq && apt-get install -y -qq curl >/dev/null73
- chmod +x scripts/release.sh74
# Checkout may still contain a previous src/README-*.md; keep only the bumped one.75
- find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete76
script:77
- test -n "${VERSION}"78
- gradle --no-daemon clean jar79
- test -f "build/libs/ContainerPipes-${VERSION}.jar"80
- ls -la "build/libs/ContainerPipes-${VERSION}.jar"81
- ./scripts/release.sh upload82
artifacts:83
reports:84
dotenv: version.env85
paths:86
- "build/libs/ContainerPipes-*.jar"87
- version.env88
expire_in: 30 days89
90
release:gitlab:91
stage: release92
image: registry.gitlab.com/gitlab-org/release-cli:latest93
needs:94
- job: build:jar95
artifacts: true96
script:97
- echo "Publishing GitLab Release for ${TAG} (version ${VERSION})"98
release:99
name: "ContainerPipes $VERSION"100
tag_name: "$TAG"101
description: "Release $VERSION of ContainerPipes."102
assets:103
links:104
- name: "ContainerPipes-$VERSION.jar"105
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/containerpipes/$VERSION/ContainerPipes-$VERSION.jar"106
link_type: package@@ -0,0 +1,12 @@
1
# ContainerPipes 1.7.0
2
3
Adds two endpoint families on top of 1.6.4:
4
5
- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
6
- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
7
8
Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
9
10
Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
11
12
Existing connections.tsv and config.yml remain compatible.
@@ -0,0 +1,12 @@1
# ContainerPipes 1.7.02
3
Adds two endpoint families on top of 1.6.4:4
5
- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.6
- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.7
8
Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.9
10
Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.11
12
Existing connections.tsv and config.yml remain compatible.@@ -0,0 +1,10 @@
1
plugins { java }
2
group = "nl.timfalken"
3
version = "1.7.0"
4
repositories { maven("https://repo.papermc.io/repository/maven-public/") }
5
dependencies { compileOnly("io.papermc.paper:paper-api:26.2-R0.1-SNAPSHOT") }
6
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
7
tasks.jar {
8
archiveBaseName.set("ContainerPipes")
9
archiveVersion.set(project.version.toString())
10
}
@@ -0,0 +1,10 @@1
plugins { java }2
group = "nl.timfalken"3
version = "1.7.0"4
repositories { maven("https://repo.papermc.io/repository/maven-public/") }5
dependencies { compileOnly("io.papermc.paper:paper-api:26.2-R0.1-SNAPSHOT") }6
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }7
tasks.jar {8
archiveBaseName.set("ContainerPipes")9
archiveVersion.set(project.version.toString())10
}@@ -0,0 +1,156 @@
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
bump_and_push() {
93
local version="${1:?version required}"
94
local tag="${2:?tag required}"
95
local token="${CI_PUSH_TOKEN:?Set CI/CD variable CI_PUSH_TOKEN (Project Access Token with write_repository)}"
96
local branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"
97
98
git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"
99
git config user.name "GitLab CI"
100
101
bump_files "$version"
102
103
git add -A
104
if git diff --cached --quiet; then
105
echo "No version file changes to commit (already at ${version})."
106
else
107
git commit -m "chore: bump version to ${version}"
108
fi
109
110
git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
111
112
# Push commit and retarget the release tag without starting a new pipeline.
113
git push origin "HEAD:refs/heads/${branch}" -o ci.skip
114
git tag -f "$tag"
115
git push origin "refs/tags/${tag}" --force -o ci.skip
116
117
echo "Pushed version bump to ${branch} and moved tag ${tag} (ci.skip)."
118
}
119
120
upload_package() {
121
local version="${1:?version required}"
122
local jar="build/libs/ContainerPipes-${version}.jar"
123
local package_url
124
125
if [[ ! -f "$jar" ]]; then
126
echo "ERROR: Expected jar not found: ${jar}"
127
ls -la build/libs/ || true
128
exit 1
129
fi
130
131
package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/containerpipes/${version}/ContainerPipes-${version}.jar"
132
curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
133
--upload-file "$jar" \
134
"$package_url"
135
136
echo "Uploaded ${jar}"
137
echo "PACKAGE_URL=${package_url}" > package.env
138
}
139
140
case "${1:-}" in
141
validate) validate ;;
142
bump)
143
# shellcheck disable=SC1091
144
source version.env
145
bump_and_push "$VERSION" "$TAG"
146
;;
147
upload)
148
# shellcheck disable=SC1091
149
source version.env
150
upload_package "$VERSION"
151
;;
152
*)
153
echo "Usage: $0 {validate|bump|upload}"
154
exit 1
155
;;
156
esac
@@ -0,0 +1,156 @@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
bump_and_push() {93
local version="${1:?version required}"94
local tag="${2:?tag required}"95
local token="${CI_PUSH_TOKEN:?Set CI/CD variable CI_PUSH_TOKEN (Project Access Token with write_repository)}"96
local branch="${CI_DEFAULT_BRANCH:?CI_DEFAULT_BRANCH is required}"97
98
git config user.email "gitlab-ci@${CI_SERVER_HOST:-gitlab.com}"99
git config user.name "GitLab CI"100
101
bump_files "$version"102
103
git add -A104
if git diff --cached --quiet; then105
echo "No version file changes to commit (already at ${version})."106
else107
git commit -m "chore: bump version to ${version}"108
fi109
110
git remote set-url origin "https://oauth2:${token}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"111
112
# Push commit and retarget the release tag without starting a new pipeline.113
git push origin "HEAD:refs/heads/${branch}" -o ci.skip114
git tag -f "$tag"115
git push origin "refs/tags/${tag}" --force -o ci.skip116
117
echo "Pushed version bump to ${branch} and moved tag ${tag} (ci.skip)."118
}119
120
upload_package() {121
local version="${1:?version required}"122
local jar="build/libs/ContainerPipes-${version}.jar"123
local package_url124
125
if [[ ! -f "$jar" ]]; then126
echo "ERROR: Expected jar not found: ${jar}"127
ls -la build/libs/ || true128
exit 1129
fi130
131
package_url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/containerpipes/${version}/ContainerPipes-${version}.jar"132
curl --fail --show-error --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \133
--upload-file "$jar" \134
"$package_url"135
136
echo "Uploaded ${jar}"137
echo "PACKAGE_URL=${package_url}" > package.env138
}139
140
case "${1:-}" in141
validate) validate ;;142
bump)143
# shellcheck disable=SC1091144
source version.env145
bump_and_push "$VERSION" "$TAG"146
;;147
upload)148
# shellcheck disable=SC1091149
source version.env150
upload_package "$VERSION"151
;;152
*)153
echo "Usage: $0 {validate|bump|upload}"154
exit 1155
;;156
esac@@ -0,0 +1 @@
1
rootProject.name = "ContainerPipes"
@@ -0,0 +1 @@1
rootProject.name = "ContainerPipes"@@ -0,0 +1,12 @@
1
# ContainerPipes 1.7.0
2
3
Adds two endpoint families on top of 1.6.4:
4
5
- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.
6
- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.
7
8
Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.
9
10
Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.
11
12
Existing connections.tsv and config.yml remain compatible.
@@ -0,0 +1,12 @@1
# ContainerPipes 1.7.02
3
Adds two endpoint families on top of 1.6.4:4
5
- **Crafter destinations**: item pipes may terminate at a Crafter. A Crafter cannot be a source. Insertion reads the live Crafter state, respects disabled slots, and uses hopper-style Crafter ordering without a persistent destination-slot cache.6
- **Liquid cauldron pipes**: CAULDRON, WATER_CAULDRON, LAVA_CAULDRON and POWDER_SNOW_CAULDRON remain valid pipe endpoints. Water and lava move one cauldron level per transfer interval. Only liquid-container -> liquid-container connections are allowed. Powder snow is retained as a valid endpoint state but is not transferred as a liquid.7
8
Liquid pipes have no filter UI. Shift + shears still removes them. Water/lava transfers use DRIPPING_WATER / DRIPPING_LAVA particles instead of the normal item-transfer animation.9
10
Cauldron state changes wake the liquid network through CauldronLevelChangeEvent, covering normal rain, dripstone, bottle/bucket and similar vanilla changes. Internal pipe changes update and wake the cached liquid state directly. Sleeping connections retain the existing emergency probe as a fallback.11
12
Existing connections.tsv and config.yml remain compatible.@@ -0,0 +1,802 @@
1
package nl.timfalken.containerpipes;
2
3
import java.lang.reflect.*;
4
import java.util.*;
5
import java.util.concurrent.ConcurrentHashMap;
6
7
/**
8
* Runtime bridge for Crafter destinations and liquid-cauldron pipes.
9
*
10
* This class intentionally uses reflection for the event bridge so it can be
11
* packaged against the already-verified Paper 26.2 plugin bytecode without
12
* introducing new binary-signature assumptions. It does NOT sit in the normal
13
* item-transfer hot path except for the tiny Crafter destination check.
14
*/
15
public final class AdvancedEndpointsPatch {
16
private AdvancedEndpointsPatch() {}
17
18
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
19
private static final Map<MethodKey, Method> METHODS = new ConcurrentHashMap<>();
20
private static final Map<FieldKey, Field> FIELDS = new ConcurrentHashMap<>();
21
22
public static boolean isExtendedContainer(Object block) {
23
String name = materialName(block);
24
return "CRAFTER".equals(name) || isCauldronMaterial(name);
25
}
26
27
public static boolean isCrafterInventory(Object inventory) {
28
if (inventory == null) return false;
29
try {
30
Object type = call(inventory, "getType");
31
return type != null && "CRAFTER".equals(String.valueOf(type));
32
} catch (Throwable ignored) {
33
return false;
34
}
35
}
36
37
/**
38
* Vanilla-equivalent hopper-style insertion for a Crafter destination.
39
* No persistent slot cache is used. Disabled slots are queried from the
40
* live Crafter blockstate for every insertion.
41
*/
42
public static boolean insertOneCrafter(Object inventory, Object sourceStack) {
43
if (inventory == null || sourceStack == null) return false;
44
try {
45
Object sourceType = call(sourceStack, "getType");
46
if (sourceType == null || "AIR".equals(String.valueOf(sourceType))) return false;
47
48
Object location = call(inventory, "getLocation");
49
if (location == null) return false;
50
Object block = call(location, "getBlock");
51
if (!"CRAFTER".equals(materialName(block))) return false;
52
Object crafter = call(block, "getState");
53
54
int size = ((Number) call(inventory, "getSize")).intValue();
55
int inventoryMax = ((Number) call(inventory, "getMaxStackSize")).intValue();
56
57
// Vanilla automation first fills the first enabled empty slot.
58
for (int slot = 0; slot < size; slot++) {
59
if ((Boolean) call(crafter, "isSlotDisabled", new Class<?>[]{int.class}, slot)) continue;
60
Object existing = call(inventory, "getItem", new Class<?>[]{int.class}, slot);
61
if (isEmptyItem(existing)) {
62
Object one = cloneOne(sourceStack);
63
// Re-read directly before the write. If another plugin changed
64
// the slot during this synchronous operation, fail safely.
65
Object actual = call(inventory, "getItem", new Class<?>[]{int.class}, slot);
66
if (!isEmptyItem(actual)) return false;
67
call(inventory, "setItem", new Class<?>[]{int.class, itemStackClass()}, slot, one);
68
return true;
69
}
70
}
71
72
// If all enabled slots are occupied, vanilla Crafter automation feeds
73
// the smallest compatible stack; ties retain normal slot order.
74
int bestSlot = -1;
75
int bestAmount = Integer.MAX_VALUE;
76
Object bestStack = null;
77
for (int slot = 0; slot < size; slot++) {
78
if ((Boolean) call(crafter, "isSlotDisabled", new Class<?>[]{int.class}, slot)) continue;
79
Object existing = call(inventory, "getItem", new Class<?>[]{int.class}, slot);
80
if (isEmptyItem(existing)) continue;
81
if (!(Boolean) call(existing, "isSimilar", new Class<?>[]{itemStackClass()}, sourceStack)) continue;
82
int amount = ((Number) call(existing, "getAmount")).intValue();
83
int itemMax = ((Number) call(existing, "getMaxStackSize")).intValue();
84
int max = Math.min(itemMax, inventoryMax);
85
if (amount >= max) continue;
86
if (amount < bestAmount) {
87
bestAmount = amount;
88
bestSlot = slot;
89
bestStack = existing;
90
}
91
}
92
if (bestSlot < 0) return false;
93
94
Object actual = call(inventory, "getItem", new Class<?>[]{int.class}, bestSlot);
95
if (!sameStackExact(bestStack, actual)) return false;
96
Object merged = call(actual, "clone");
97
call(merged, "setAmount", new Class<?>[]{int.class}, bestAmount + 1);
98
call(inventory, "setItem", new Class<?>[]{int.class, itemStackClass()}, bestSlot, merged);
99
return true;
100
} catch (Throwable ignored) {
101
return false;
102
}
103
}
104
105
106
/** Return true when the plugin's normal pipe click handler must stop. */
107
public static boolean suppressPipeInteract(Object plugin, Object event) {
108
State state = STATES.get(plugin);
109
if (state == null) return false;
110
try { return state.suppressPipeInteract(event); }
111
catch (Throwable ignored) { return false; }
112
}
113
114
public static void enable(Object plugin) {
115
try {
116
State old = STATES.remove(plugin);
117
if (old != null) old.disable();
118
State state = new State(plugin);
119
STATES.put(plugin, state);
120
state.enable();
121
} catch (Throwable t) {
122
log(plugin, "Could not enable Crafter/liquid-pipe extension", t);
123
}
124
}
125
126
public static void disable(Object plugin) {
127
State state = STATES.remove(plugin);
128
if (state != null) state.disable();
129
}
130
131
public static void connectionChanged(Object plugin, Object connection, boolean added) {
132
State state = STATES.get(plugin);
133
if (state == null) return;
134
try { state.connectionChanged(connection, added); }
135
catch (Throwable t) { log(plugin, "Could not update liquid-pipe index", t); }
136
}
137
138
private static final class State {
139
final Object plugin;
140
final Map<Long, LiquidConnection> liquidConnections = new LinkedHashMap<>();
141
final Map<EndpointKey, Set<Long>> byEndpoint = new HashMap<>();
142
final Set<Long> active = new LinkedHashSet<>();
143
final Map<Long, Long> sleepingUntil = new HashMap<>();
144
final Map<EndpointKey, FluidState> fluidCache = new HashMap<>();
145
final Map<Long, Long> lastParticleTick = new HashMap<>();
146
Object schedulerTask;
147
Object listenerProxy;
148
Object executorProxy;
149
long tick;
150
long lastResync;
151
152
State(Object plugin) { this.plugin = plugin; }
153
154
void enable() throws Exception {
155
resyncConnections();
156
registerEvents();
157
Object server = call(plugin, "getServer");
158
Object scheduler = call(server, "getScheduler");
159
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
160
schedulerTask = call(scheduler, "runTaskTimer",
161
new Class<?>[]{pluginClass, Runnable.class, long.class, long.class},
162
plugin, (Runnable) this::tick, 1L, 1L);
163
}
164
165
void disable() {
166
try { if (schedulerTask != null) call(schedulerTask, "cancel"); } catch (Throwable ignored) {}
167
liquidConnections.clear();
168
byEndpoint.clear();
169
active.clear();
170
sleepingUntil.clear();
171
fluidCache.clear();
172
}
173
174
void registerEvents() throws Exception {
175
ClassLoader cl = plugin.getClass().getClassLoader();
176
Class<?> listener = Class.forName("org.bukkit.event.Listener", false, cl);
177
Class<?> executor = Class.forName("org.bukkit.plugin.EventExecutor", false, cl);
178
listenerProxy = Proxy.newProxyInstance(cl, new Class<?>[]{listener}, (p,m,a) -> proxyObjectMethod(p,m,a));
179
executorProxy = Proxy.newProxyInstance(cl, new Class<?>[]{executor}, (p,m,a) -> {
180
Object objectResult = proxyObjectMethod(p,m,a);
181
if (m.getDeclaringClass() == Object.class) return objectResult;
182
if ("execute".equals(m.getName()) && a != null && a.length == 2) handleEvent(a[1]);
183
return null;
184
});
185
186
Object pm = call(call(plugin, "getServer"), "getPluginManager");
187
Class<?> eventPriority = Class.forName("org.bukkit.event.EventPriority", false, cl);
188
@SuppressWarnings({"unchecked","rawtypes"})
189
Object lowest = Enum.valueOf((Class<? extends Enum>) eventPriority.asSubclass(Enum.class), "LOWEST");
190
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, cl);
191
192
String[] eventNames = {
193
"org.bukkit.event.player.PlayerInteractEvent",
194
"org.bukkit.event.block.CauldronLevelChangeEvent",
195
"org.bukkit.event.world.ChunkLoadEvent"
196
};
197
for (String name : eventNames) {
198
Class<?> eventClass = Class.forName(name, false, cl);
199
call(pm, "registerEvent",
200
new Class<?>[]{Class.class, listener, eventPriority, executor, pluginClass, boolean.class},
201
eventClass, listenerProxy, lowest, executorProxy, plugin, false);
202
}
203
}
204
205
void handleEvent(Object event) {
206
try {
207
String name = event.getClass().getName();
208
if (name.endsWith("PlayerInteractEvent")) handleBlockInteract(event);
209
else if (name.endsWith("CauldronLevelChangeEvent")) {
210
Object block = call(event, "getBlock");
211
scheduleWakeBlock(block, 1L);
212
} else if (name.endsWith("ChunkLoadEvent")) {
213
// Connections are intentionally not tagged with a persisted pipe
214
// kind, so an endpoint that was unloaded during plugin startup can
215
// only be classified once its chunks exist. Re-evaluate then.
216
resyncConnections();
217
Object chunk = call(event, "getChunk");
218
wakeChunk(chunk);
219
}
220
} catch (Throwable ignored) {}
221
}
222
223
void handleBlockInteract(Object event) throws Exception {
224
Object hand = call(event, "getHand");
225
Object action = call(event, "getAction");
226
if (hand == null || !"HAND".equals(String.valueOf(hand))) return;
227
if (action == null || !"RIGHT_CLICK_BLOCK".equals(String.valueOf(action))) return;
228
Object player = call(event, "getPlayer");
229
if (!(Boolean) call(player, "isSneaking")) return;
230
Object block = call(event, "getClickedBlock");
231
if (block == null) return;
232
233
String clickedType = materialName(block);
234
boolean crafter = "CRAFTER".equals(clickedType);
235
boolean destinationLiquid = isCauldronMaterial(clickedType);
236
237
Object held = call(event, "getItem");
238
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));
239
240
@SuppressWarnings("unchecked")
241
Map<Object,Object> selections = (Map<Object,Object>) field(plugin, "selections");
242
Object playerId = call(player, "getUniqueId");
243
Object selection = selections.get(playerId);
244
245
// When a liquid source is already selected, the second click must be
246
// another liquid container even if the clicked destination is an ordinary
247
// chest/furnace. Likewise item networks may not terminate in a cauldron.
248
if (selection != null) {
249
Object sourceEndpoint = call(selection, "endpoint");
250
Object sourceBlock = blockForEndpoint(sourceEndpoint);
251
boolean sourceLiquid = sourceBlock != null && isCauldronMaterial(materialName(sourceBlock));
252
if (sourceLiquid != destinationLiquid) {
253
selections.remove(playerId);
254
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
255
return;
256
}
257
// item -> crafter and liquid -> liquid continue into the normal
258
// ContainerPipes route creation path.
259
return;
260
}
261
262
if (!crafter && !destinationLiquid) return;
263
264
Object blockFace = call(event, "getBlockFace");
265
LiquidConnection endpointConnection = destinationLiquid ? liquidConnectionAt(block, blockFace) : null;
266
if (endpointConnection != null) {
267
// Liquid pipes have no filter UI. Shears are still allowed through
268
// so the plugin's normal shift+shears removal path remains intact.
269
if (!shears) call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
270
return;
271
}
272
273
// A Crafter is destination-only. First-clicking it as a source is a
274
// silent no-op, except shears on an existing ordinary item endpoint.
275
if (crafter && !shears) {
276
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
277
}
278
}
279
280
boolean suppressPipeInteract(Object event) throws Exception {
281
Object entity = call(event, "getRightClicked");
282
@SuppressWarnings("unchecked")
283
Set<String> tags = (Set<String>) call(entity, "getScoreboardTags");
284
long id = -1;
285
for (String tag : tags) {
286
if (!tag.startsWith("containerpipes-filter:")) continue;
287
try { id = Long.parseLong(tag.substring(tag.indexOf(':') + 1)); } catch (NumberFormatException ignored) {}
288
}
289
if (id < 0 || !liquidConnections.containsKey(id)) return false;
290
Object player = call(event, "getPlayer");
291
Object inventory = call(player, "getInventory");
292
Object held = call(inventory, "getItemInMainHand");
293
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));
294
boolean sneaking = (Boolean) call(player, "isSneaking");
295
return !(shears && sneaking);
296
}
297
298
void handlePipeInteract(Object event) throws Exception {
299
Object entity = call(event, "getRightClicked");
300
@SuppressWarnings("unchecked")
301
Set<String> tags = (Set<String>) call(entity, "getScoreboardTags");
302
long id = -1;
303
for (String tag : tags) {
304
if (!tag.startsWith("containerpipes-filter:")) continue;
305
try { id = Long.parseLong(tag.substring(tag.indexOf(':') + 1)); } catch (NumberFormatException ignored) {}
306
}
307
if (id < 0 || !liquidConnections.containsKey(id)) return;
308
Object player = call(event, "getPlayer");
309
Object inventory = call(player, "getInventory");
310
Object held = call(inventory, "getItemInMainHand");
311
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));
312
boolean sneaking = (Boolean) call(player, "isSneaking");
313
if (!(shears && sneaking)) {
314
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
315
}
316
}
317
318
void tick() {
319
try {
320
tick++;
321
if (tick - lastResync >= 400) {
322
resyncConnections();
323
lastResync = tick;
324
}
325
326
int interval = Math.max(1, configInt("transfer-interval-ticks", 3));
327
if (tick % interval != 0) return;
328
329
// Emergency wakeup for missed external events. Keep the same general
330
// cadence as item-pipe sleeping probes, but liquid networks are tiny.
331
long probe = Math.max(20, configInt("performance.sleeping-probe-interval-ticks", 200));
332
if (!sleepingUntil.isEmpty()) {
333
ArrayList<Long> wake = new ArrayList<>();
334
for (Map.Entry<Long,Long> e : sleepingUntil.entrySet()) {
335
if (tick >= e.getValue()) wake.add(e.getKey());
336
}
337
for (long id : wake) {
338
sleepingUntil.remove(id);
339
active.add(id);
340
LiquidConnection c = liquidConnections.get(id);
341
if (c != null) {
342
refreshFluid(c.source);
343
refreshFluid(c.destination);
344
}
345
}
346
}
347
348
if (active.isEmpty()) return;
349
ArrayList<Long> cycle = new ArrayList<>(active);
350
for (long id : cycle) {
351
LiquidConnection connection = liquidConnections.get(id);
352
if (connection == null) { active.remove(id); continue; }
353
if (transferOneLevel(connection)) continue;
354
connection.failed++;
355
int idleAfter = Math.max(1, configInt("performance.idle-after-failed-attempts", 3));
356
if (connection.failed >= idleAfter) {
357
connection.failed = 0;
358
active.remove(id);
359
sleepingUntil.put(id, tick + probe);
360
}
361
}
362
} catch (Throwable t) {
363
log(plugin, "Liquid transfer tick failed", t);
364
}
365
}
366
367
boolean transferOneLevel(LiquidConnection connection) throws Exception {
368
Object sourceBlock = blockForEndpoint(connection.source.raw);
369
Object destinationBlock = blockForEndpoint(connection.destination.raw);
370
if (sourceBlock == null || destinationBlock == null) return false;
371
372
FluidState source = readFluid(sourceBlock);
373
FluidState destination = readFluid(destinationBlock);
374
fluidCache.put(connection.source.key, source);
375
fluidCache.put(connection.destination.key, destination);
376
377
if (!source.transferable()) return false;
378
if (!destination.accepts(source.type)) return false;
379
380
if (source.type == FluidType.WATER) {
381
setWaterLevel(sourceBlock, source.level - 1);
382
setWaterLevel(destinationBlock, destination.type == FluidType.EMPTY ? 1 : destination.level + 1);
383
} else if (source.type == FluidType.LAVA) {
384
setEmpty(sourceBlock);
385
setLava(destinationBlock);
386
} else {
387
return false;
388
}
389
390
FluidState newSource = readFluid(sourceBlock);
391
FluidState newDestination = readFluid(destinationBlock);
392
fluidCache.put(connection.source.key, newSource);
393
fluidCache.put(connection.destination.key, newDestination);
394
connection.failed = 0;
395
396
wakeEndpoint(connection.source.key);
397
wakeEndpoint(connection.destination.key);
398
animateLiquid(connection, source.type);
399
return true;
400
}
401
402
void setWaterLevel(Object block, int level) throws Exception {
403
if (level <= 0) { setEmpty(block); return; }
404
if (!"WATER_CAULDRON".equals(materialName(block))) setBlockType(block, "WATER_CAULDRON");
405
Object data = call(block, "getBlockData");
406
call(data, "setLevel", new Class<?>[]{int.class}, level);
407
call(block, "setBlockData", new Class<?>[]{Class.forName("org.bukkit.block.data.BlockData", false, plugin.getClass().getClassLoader())}, data);
408
}
409
410
void setLava(Object block) throws Exception { setBlockType(block, "LAVA_CAULDRON"); }
411
void setEmpty(Object block) throws Exception { setBlockType(block, "CAULDRON"); }
412
413
void setBlockType(Object block, String materialName) throws Exception {
414
Class<?> materialClass = Class.forName("org.bukkit.Material", false, plugin.getClass().getClassLoader());
415
@SuppressWarnings({"rawtypes","unchecked"})
416
Object material = Enum.valueOf((Class<? extends Enum>) materialClass.asSubclass(Enum.class), materialName);
417
call(block, "setType", new Class<?>[]{materialClass}, material);
418
}
419
420
FluidState readFluid(Object block) throws Exception {
421
String name = materialName(block);
422
if ("CAULDRON".equals(name)) return new FluidState(FluidType.EMPTY, 0, 0);
423
if ("LAVA_CAULDRON".equals(name)) return new FluidState(FluidType.LAVA, 1, 1);
424
if ("WATER_CAULDRON".equals(name)) {
425
Object data = call(block, "getBlockData");
426
int level = ((Number) call(data, "getLevel")).intValue();
427
int max = ((Number) call(data, "getMaximumLevel")).intValue();
428
return new FluidState(FluidType.WATER, level, max);
429
}
430
// Keep a pipe attached if a cauldron temporarily contains an unsupported
431
// medium (e.g. powder snow), but never mix/transfer it as a liquid.
432
if (isCauldronMaterial(name)) return new FluidState(FluidType.OTHER, 1, 1);
433
return new FluidState(FluidType.OTHER, 0, 0);
434
}
435
436
void scheduleWakeBlock(Object block, long delay) throws Exception {
437
Object server = call(plugin, "getServer");
438
Object scheduler = call(server, "getScheduler");
439
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
440
call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin,
441
(Runnable) () -> {
442
try {
443
EndpointKey key = endpointKeyForBlock(block);
444
refreshFluidByKey(key);
445
wakeEndpoint(key);
446
} catch (Throwable ignored) {}
447
}, delay);
448
}
449
450
void wakeChunk(Object chunk) throws Exception {
451
Object world = call(chunk, "getWorld");
452
UUID worldId = (UUID) call(world, "getUID");
453
int cx = ((Number) call(chunk, "getX")).intValue();
454
int cz = ((Number) call(chunk, "getZ")).intValue();
455
for (LiquidConnection c : liquidConnections.values()) {
456
if (!c.source.key.world.equals(worldId)) continue;
457
if ((c.source.x >> 4) == cx && (c.source.z >> 4) == cz
458
|| (c.destination.x >> 4) == cx && (c.destination.z >> 4) == cz) {
459
active.add(c.id);
460
sleepingUntil.remove(c.id);
461
}
462
}
463
}
464
465
void wakeEndpoint(EndpointKey key) {
466
Set<Long> ids = byEndpoint.get(key);
467
if (ids == null) return;
468
for (long id : ids) {
469
active.add(id);
470
sleepingUntil.remove(id);
471
}
472
}
473
474
void refreshFluid(EndpointView endpoint) {
475
try {
476
Object block = blockForEndpoint(endpoint.raw);
477
if (block != null) fluidCache.put(endpoint.key, readFluid(block));
478
} catch (Throwable ignored) {}
479
}
480
481
void refreshFluidByKey(EndpointKey key) {
482
try {
483
Object world = getWorld(key.world);
484
if (world == null) return;
485
int x = unpackX(key.packed), y = unpackY(key.packed), z = unpackZ(key.packed);
486
Object block = call(world, "getBlockAt", new Class<?>[]{int.class,int.class,int.class}, x,y,z);
487
fluidCache.put(key, readFluid(block));
488
} catch (Throwable ignored) {}
489
}
490
491
void animateLiquid(LiquidConnection connection, FluidType type) {
492
try {
493
int cooldown = Math.max(0, configInt("particles.transfer-animation-cooldown-ticks", 100));
494
Long previous = lastParticleTick.get(connection.id);
495
if (previous != null && tick - previous < cooldown) return;
496
lastParticleTick.put(connection.id, tick);
497
498
Object world = getWorld(connection.source.key.world);
499
if (world == null) return;
500
String particleName = type == FluidType.LAVA ? "DRIPPING_LAVA" : "DRIPPING_WATER";
501
Class<?> particleClass = Class.forName("org.bukkit.Particle", false, plugin.getClass().getClassLoader());
502
@SuppressWarnings({"rawtypes","unchecked"})
503
Object particle = Enum.valueOf((Class<? extends Enum>) particleClass.asSubclass(Enum.class), particleName);
504
505
ArrayList<double[]> points = connection.particlePoints();
506
int stepTicks = Math.max(1, configInt("transfer-particle-step-ticks", 3));
507
int perStep = Math.max(1, configInt("transfer-particle-points-per-step", 2));
508
Class<?> locationClass = Class.forName("org.bukkit.Location", false, plugin.getClass().getClassLoader());
509
Constructor<?> locationCtor = locationClass.getConstructor(Class.forName("org.bukkit.World", false, plugin.getClass().getClassLoader()), double.class,double.class,double.class);
510
Object scheduler = call(call(plugin, "getServer"), "getScheduler");
511
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
512
513
for (int i = 0; i < points.size(); i += perStep) {
514
int from = i;
515
int to = Math.min(points.size(), i + perStep);
516
long delay = (long)(i / perStep) * stepTicks;
517
Runnable r = () -> {
518
for (int p = from; p < to; p++) {
519
try {
520
double[] xyz = points.get(p);
521
Object loc = locationCtor.newInstance(world, xyz[0], xyz[1], xyz[2]);
522
call(world, "spawnParticle", new Class<?>[]{particleClass, locationClass, int.class}, particle, loc, 1);
523
} catch (Throwable ignored) {}
524
}
525
};
526
call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin, r, delay);
527
}
528
} catch (Throwable ignored) {}
529
}
530
531
int configInt(String path, int fallback) {
532
try {
533
Object cfg = call(plugin, "getConfig");
534
return ((Number) call(cfg, "getInt", new Class<?>[]{String.class,int.class}, path, fallback)).intValue();
535
} catch (Throwable ignored) { return fallback; }
536
}
537
538
void resyncConnections() throws Exception {
539
@SuppressWarnings("unchecked")
540
Map<Long,Object> connections = (Map<Long,Object>) field(plugin, "connections");
541
Set<Long> seen = new HashSet<>();
542
for (Map.Entry<Long,Object> e : connections.entrySet()) {
543
seen.add(e.getKey());
544
inspectConnection(e.getValue(), true);
545
}
546
ArrayList<Long> stale = new ArrayList<>();
547
for (long id : liquidConnections.keySet()) if (!seen.contains(id)) stale.add(id);
548
for (long id : stale) removeLiquid(id);
549
}
550
551
void connectionChanged(Object connection, boolean added) throws Exception {
552
long id = ((Number) call(connection, "id")).longValue();
553
if (!added) { removeLiquid(id); return; }
554
inspectConnection(connection, false);
555
}
556
557
void inspectConnection(Object raw, boolean resync) throws Exception {
558
long id = ((Number) call(raw, "id")).longValue();
559
Object sourceRaw = call(raw, "source");
560
Object destinationRaw = call(raw, "destination");
561
EndpointView source = endpointView(sourceRaw);
562
EndpointView destination = endpointView(destinationRaw);
563
Object sourceBlock = blockForEndpoint(sourceRaw);
564
Object destinationBlock = blockForEndpoint(destinationRaw);
565
LiquidConnection existing = liquidConnections.get(id);
566
// If an endpoint chunk is currently unloaded, preserve a liquid
567
// classification we already know instead of forgetting it. New/unseen
568
// connections are classified as soon as both endpoints are loaded.
569
if (sourceBlock == null || destinationBlock == null) {
570
if (existing != null) return;
571
return;
572
}
573
boolean liquid = isCauldronMaterial(materialName(sourceBlock))
574
&& isCauldronMaterial(materialName(destinationBlock));
575
if (!liquid) { removeLiquid(id); return; }
576
577
578
if (existing != null && existing.source.key.equals(source.key) && existing.destination.key.equals(destination.key)) return;
579
removeLiquid(id);
580
LiquidConnection c = new LiquidConnection(id, raw, source, destination, readPath(raw));
581
liquidConnections.put(id, c);
582
byEndpoint.computeIfAbsent(source.key, k -> new LinkedHashSet<>()).add(id);
583
byEndpoint.computeIfAbsent(destination.key, k -> new LinkedHashSet<>()).add(id);
584
refreshFluid(source);
585
refreshFluid(destination);
586
active.add(id);
587
sleepingUntil.remove(id);
588
}
589
590
void removeLiquid(long id) {
591
LiquidConnection c = liquidConnections.remove(id);
592
active.remove(id);
593
sleepingUntil.remove(id);
594
lastParticleTick.remove(id);
595
if (c == null) return;
596
removeIndex(c.source.key, id);
597
removeIndex(c.destination.key, id);
598
}
599
600
void removeIndex(EndpointKey key, long id) {
601
Set<Long> ids = byEndpoint.get(key);
602
if (ids == null) return;
603
ids.remove(id);
604
if (ids.isEmpty()) byEndpoint.remove(key);
605
}
606
607
LiquidConnection liquidConnectionAt(Object block, Object face) {
608
try {
609
UUID world = (UUID) call(call(block, "getWorld"), "getUID");
610
int x = ((Number) call(block, "getX")).intValue();
611
int y = ((Number) call(block, "getY")).intValue();
612
int z = ((Number) call(block, "getZ")).intValue();
613
String faceName = String.valueOf(face);
614
for (LiquidConnection c : liquidConnections.values()) {
615
if (c.source.matches(world,x,y,z,faceName) || c.destination.matches(world,x,y,z,faceName)) return c;
616
}
617
} catch (Throwable ignored) {}
618
return null;
619
}
620
621
Object blockForEndpoint(Object endpoint) throws Exception {
622
UUID worldId = (UUID) call(endpoint, "world");
623
int x = ((Number) call(endpoint, "x")).intValue();
624
int y = ((Number) call(endpoint, "y")).intValue();
625
int z = ((Number) call(endpoint, "z")).intValue();
626
Object world = getWorld(worldId);
627
if (world == null) return null;
628
boolean loaded = (Boolean) call(world, "isChunkLoaded", new Class<?>[]{int.class,int.class}, x >> 4, z >> 4);
629
if (!loaded) return null;
630
return call(world, "getBlockAt", new Class<?>[]{int.class,int.class,int.class}, x,y,z);
631
}
632
633
Object getWorld(UUID id) throws Exception {
634
Class<?> bukkit = Class.forName("org.bukkit.Bukkit", false, plugin.getClass().getClassLoader());
635
Method m = bukkit.getMethod("getWorld", UUID.class);
636
return m.invoke(null, id);
637
}
638
639
EndpointKey endpointKeyForBlock(Object block) throws Exception {
640
UUID world = (UUID) call(call(block, "getWorld"), "getUID");
641
int x = ((Number) call(block, "getX")).intValue();
642
int y = ((Number) call(block, "getY")).intValue();
643
int z = ((Number) call(block, "getZ")).intValue();
644
return new EndpointKey(world, pack(x,y,z));
645
}
646
647
EndpointView endpointView(Object endpoint) throws Exception {
648
UUID world = (UUID) call(endpoint, "world");
649
int x = ((Number) call(endpoint, "x")).intValue();
650
int y = ((Number) call(endpoint, "y")).intValue();
651
int z = ((Number) call(endpoint, "z")).intValue();
652
String face = String.valueOf(call(endpoint, "face"));
653
return new EndpointView(endpoint, new EndpointKey(world, pack(x,y,z)), x,y,z,face);
654
}
655
656
ArrayList<int[]> readPath(Object connection) throws Exception {
657
ArrayList<int[]> out = new ArrayList<>();
658
for (Object p : (List<?>) call(connection, "path")) {
659
out.add(new int[]{((Number)call(p,"x")).intValue(), ((Number)call(p,"y")).intValue(), ((Number)call(p,"z")).intValue()});
660
}
661
return out;
662
}
663
}
664
665
private enum FluidType { EMPTY, WATER, LAVA, OTHER }
666
private record FluidState(FluidType type, int level, int max) {
667
boolean transferable() { return (type == FluidType.WATER || type == FluidType.LAVA) && level > 0; }
668
boolean accepts(FluidType incoming) {
669
if (incoming != FluidType.WATER && incoming != FluidType.LAVA) return false;
670
if (type == FluidType.EMPTY) return true;
671
if (type != incoming) return false;
672
return level < max;
673
}
674
}
675
private record EndpointKey(UUID world, long packed) {}
676
private record EndpointView(Object raw, EndpointKey key, int x, int y, int z, String face) {
677
boolean matches(UUID w,int bx,int by,int bz,String f){return key.world.equals(w)&&x==bx&&y==by&&z==bz&&face.equals(f);}
678
}
679
private static final class LiquidConnection {
680
final long id; final Object raw; final EndpointView source,destination; final ArrayList<int[]> path; int failed;
681
LiquidConnection(long id,Object raw,EndpointView source,EndpointView destination,ArrayList<int[]> path){this.id=id;this.raw=raw;this.source=source;this.destination=destination;this.path=path;}
682
ArrayList<double[]> particlePoints(){
683
ArrayList<double[]> points=new ArrayList<>(path.size()+2);
684
points.add(new double[]{source.x+0.5,source.y+0.5,source.z+0.5});
685
for(int[]p:path)points.add(new double[]{p[0]+0.5,p[1]+0.5,p[2]+0.5});
686
points.add(new double[]{destination.x+0.5,destination.y+0.5,destination.z+0.5});
687
return points;
688
}
689
}
690
691
private static Object proxyObjectMethod(Object proxy, Method method, Object[] args) {
692
if (method.getDeclaringClass() != Object.class) return null;
693
return switch (method.getName()) {
694
case "hashCode" -> System.identityHashCode(proxy);
695
case "equals" -> proxy == (args == null || args.length == 0 ? null : args[0]);
696
case "toString" -> "ContainerPipesRuntimeListener";
697
default -> null;
698
};
699
}
700
701
private static boolean isCauldronMaterial(String name) {
702
return "CAULDRON".equals(name) || "WATER_CAULDRON".equals(name)
703
|| "LAVA_CAULDRON".equals(name) || "POWDER_SNOW_CAULDRON".equals(name);
704
}
705
706
private static String materialName(Object block) {
707
if (block == null) return "";
708
try { return String.valueOf(call(block, "getType")); }
709
catch (Throwable ignored) { return ""; }
710
}
711
712
private static boolean isEmptyItem(Object item) {
713
if (item == null) return true;
714
try { return "AIR".equals(String.valueOf(call(item, "getType"))); }
715
catch (Throwable ignored) { return true; }
716
}
717
718
private static Object cloneOne(Object item) throws Exception {
719
Object clone = call(item, "clone");
720
call(clone, "setAmount", new Class<?>[]{int.class}, 1);
721
return clone;
722
}
723
724
private static boolean sameStackExact(Object a, Object b) throws Exception {
725
if (isEmptyItem(a) || isEmptyItem(b)) return isEmptyItem(a) == isEmptyItem(b);
726
int aa = ((Number) call(a, "getAmount")).intValue();
727
int bb = ((Number) call(b, "getAmount")).intValue();
728
return aa == bb && (Boolean) call(a, "isSimilar", new Class<?>[]{itemStackClass()}, b);
729
}
730
731
private static Class<?> itemStackClass() throws ClassNotFoundException {
732
ClassLoader cl = Thread.currentThread().getContextClassLoader();
733
try { return Class.forName("org.bukkit.inventory.ItemStack", false, cl); }
734
catch (ClassNotFoundException e) { return Class.forName("org.bukkit.inventory.ItemStack"); }
735
}
736
737
private static Object field(Object target, String name) throws Exception {
738
FieldKey key = new FieldKey(target.getClass(), name);
739
Field f = FIELDS.get(key);
740
if (f == null) {
741
for (Class<?> c = target.getClass(); c != null; c = c.getSuperclass()) {
742
try { f = c.getDeclaredField(name); f.setAccessible(true); FIELDS.put(key,f); break; }
743
catch (NoSuchFieldException ignored) {}
744
}
745
}
746
if (f == null) throw new NoSuchFieldException(name);
747
return f.get(target);
748
}
749
750
private static Object call(Object target, String name, Object... args) throws Exception {
751
return call(target, name, new Class<?>[0], args);
752
}
753
private static Object call(Object target, String name, Class<?>[] hinted, Object... args) throws Exception {
754
if (target == null) throw new NullPointerException(name);
755
Method method = findMethod(target.getClass(), name, hinted, args);
756
return method.invoke(target, args);
757
}
758
private static Method findMethod(Class<?> owner, String name, Class<?>[] hinted, Object[] args) throws Exception {
759
MethodKey key = new MethodKey(owner,name,signatureKey(hinted,args));
760
Method cached = METHODS.get(key);
761
if (cached != null) return cached;
762
for (Class<?> c=owner;c!=null;c=c.getSuperclass()) {
763
for (Method m:c.getDeclaredMethods()) if (matches(m,name,hinted,args)) {m.setAccessible(true);METHODS.put(key,m);return m;}
764
}
765
for(Method m:owner.getMethods())if(matches(m,name,hinted,args)){m.setAccessible(true);METHODS.put(key,m);return m;}
766
throw new NoSuchMethodException(owner.getName()+"."+name);
767
}
768
private static boolean matches(Method m,String name,Class<?>[] hinted,Object[] args){
769
if(!m.getName().equals(name)||m.getParameterCount()!=args.length)return false;
770
Class<?>[] p=m.getParameterTypes();
771
for(int i=0;i<p.length;i++){
772
Class<?> wanted=hinted.length==args.length?hinted[i]:(args[i]==null?null:args[i].getClass());
773
if(wanted==null)continue;
774
if(p[i].isPrimitive()){
775
if(!primitiveWrap(p[i]).isAssignableFrom(primitiveWrap(wanted)))return false;
776
}else if(!p[i].isAssignableFrom(wanted)&&args[i]!=null&&!p[i].isInstance(args[i]))return false;
777
}
778
return true;
779
}
780
private static Class<?> primitiveWrap(Class<?> c){
781
if(!c.isPrimitive())return c;
782
if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;
783
if(c==double.class)return Double.class;if(c==float.class)return Float.class;if(c==short.class)return Short.class;
784
if(c==byte.class)return Byte.class;if(c==char.class)return Character.class;return c;
785
}
786
private static List<Class<?>> signatureKey(Class<?>[] hinted,Object[]args){
787
ArrayList<Class<?>> out=new ArrayList<>(args.length);
788
for(int i=0;i<args.length;i++)out.add(hinted.length==args.length?primitiveWrap(hinted[i]):(args[i]==null?Object.class:args[i].getClass()));
789
return out;
790
}
791
792
private static long pack(int x,int y,int z){return((long)(x&0x3FFFFFF)<<38)|((long)(z&0x3FFFFFF)<<12)|(y&0xFFFL);}
793
private static int unpackX(long p){int x=(int)(p>>38);return x>=0x2000000?x-0x4000000:x;}
794
private static int unpackY(long p){int y=(int)(p&0xFFF);return y>=0x800?y-0x1000:y;}
795
private static int unpackZ(long p){int z=(int)((p>>12)&0x3FFFFFF);return z>=0x2000000?z-0x4000000:z;}
796
797
private static void log(Object plugin,String message,Throwable t){
798
try{Object logger=call(plugin,"getLogger");call(logger,"warning",new Class<?>[]{String.class},message+": "+t);}catch(Throwable ignored){}
799
}
800
private record MethodKey(Class<?> owner,String name,List<Class<?>>args){}
801
private record FieldKey(Class<?> owner,String name){}
802
}
@@ -0,0 +1,802 @@1
package nl.timfalken.containerpipes;2
3
import java.lang.reflect.*;4
import java.util.*;5
import java.util.concurrent.ConcurrentHashMap;6
7
/**8
* Runtime bridge for Crafter destinations and liquid-cauldron pipes.9
*10
* This class intentionally uses reflection for the event bridge so it can be11
* packaged against the already-verified Paper 26.2 plugin bytecode without12
* introducing new binary-signature assumptions. It does NOT sit in the normal13
* item-transfer hot path except for the tiny Crafter destination check.14
*/15
public final class AdvancedEndpointsPatch {16
private AdvancedEndpointsPatch() {}17
18
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());19
private static final Map<MethodKey, Method> METHODS = new ConcurrentHashMap<>();20
private static final Map<FieldKey, Field> FIELDS = new ConcurrentHashMap<>();21
22
public static boolean isExtendedContainer(Object block) {23
String name = materialName(block);24
return "CRAFTER".equals(name) || isCauldronMaterial(name);25
}26
27
public static boolean isCrafterInventory(Object inventory) {28
if (inventory == null) return false;29
try {30
Object type = call(inventory, "getType");31
return type != null && "CRAFTER".equals(String.valueOf(type));32
} catch (Throwable ignored) {33
return false;34
}35
}36
37
/**38
* Vanilla-equivalent hopper-style insertion for a Crafter destination.39
* No persistent slot cache is used. Disabled slots are queried from the40
* live Crafter blockstate for every insertion.41
*/42
public static boolean insertOneCrafter(Object inventory, Object sourceStack) {43
if (inventory == null || sourceStack == null) return false;44
try {45
Object sourceType = call(sourceStack, "getType");46
if (sourceType == null || "AIR".equals(String.valueOf(sourceType))) return false;47
48
Object location = call(inventory, "getLocation");49
if (location == null) return false;50
Object block = call(location, "getBlock");51
if (!"CRAFTER".equals(materialName(block))) return false;52
Object crafter = call(block, "getState");53
54
int size = ((Number) call(inventory, "getSize")).intValue();55
int inventoryMax = ((Number) call(inventory, "getMaxStackSize")).intValue();56
57
// Vanilla automation first fills the first enabled empty slot.58
for (int slot = 0; slot < size; slot++) {59
if ((Boolean) call(crafter, "isSlotDisabled", new Class<?>[]{int.class}, slot)) continue;60
Object existing = call(inventory, "getItem", new Class<?>[]{int.class}, slot);61
if (isEmptyItem(existing)) {62
Object one = cloneOne(sourceStack);63
// Re-read directly before the write. If another plugin changed64
// the slot during this synchronous operation, fail safely.65
Object actual = call(inventory, "getItem", new Class<?>[]{int.class}, slot);66
if (!isEmptyItem(actual)) return false;67
call(inventory, "setItem", new Class<?>[]{int.class, itemStackClass()}, slot, one);68
return true;69
}70
}71
72
// If all enabled slots are occupied, vanilla Crafter automation feeds73
// the smallest compatible stack; ties retain normal slot order.74
int bestSlot = -1;75
int bestAmount = Integer.MAX_VALUE;76
Object bestStack = null;77
for (int slot = 0; slot < size; slot++) {78
if ((Boolean) call(crafter, "isSlotDisabled", new Class<?>[]{int.class}, slot)) continue;79
Object existing = call(inventory, "getItem", new Class<?>[]{int.class}, slot);80
if (isEmptyItem(existing)) continue;81
if (!(Boolean) call(existing, "isSimilar", new Class<?>[]{itemStackClass()}, sourceStack)) continue;82
int amount = ((Number) call(existing, "getAmount")).intValue();83
int itemMax = ((Number) call(existing, "getMaxStackSize")).intValue();84
int max = Math.min(itemMax, inventoryMax);85
if (amount >= max) continue;86
if (amount < bestAmount) {87
bestAmount = amount;88
bestSlot = slot;89
bestStack = existing;90
}91
}92
if (bestSlot < 0) return false;93
94
Object actual = call(inventory, "getItem", new Class<?>[]{int.class}, bestSlot);95
if (!sameStackExact(bestStack, actual)) return false;96
Object merged = call(actual, "clone");97
call(merged, "setAmount", new Class<?>[]{int.class}, bestAmount + 1);98
call(inventory, "setItem", new Class<?>[]{int.class, itemStackClass()}, bestSlot, merged);99
return true;100
} catch (Throwable ignored) {101
return false;102
}103
}104
105
106
/** Return true when the plugin's normal pipe click handler must stop. */107
public static boolean suppressPipeInteract(Object plugin, Object event) {108
State state = STATES.get(plugin);109
if (state == null) return false;110
try { return state.suppressPipeInteract(event); }111
catch (Throwable ignored) { return false; }112
}113
114
public static void enable(Object plugin) {115
try {116
State old = STATES.remove(plugin);117
if (old != null) old.disable();118
State state = new State(plugin);119
STATES.put(plugin, state);120
state.enable();121
} catch (Throwable t) {122
log(plugin, "Could not enable Crafter/liquid-pipe extension", t);123
}124
}125
126
public static void disable(Object plugin) {127
State state = STATES.remove(plugin);128
if (state != null) state.disable();129
}130
131
public static void connectionChanged(Object plugin, Object connection, boolean added) {132
State state = STATES.get(plugin);133
if (state == null) return;134
try { state.connectionChanged(connection, added); }135
catch (Throwable t) { log(plugin, "Could not update liquid-pipe index", t); }136
}137
138
private static final class State {139
final Object plugin;140
final Map<Long, LiquidConnection> liquidConnections = new LinkedHashMap<>();141
final Map<EndpointKey, Set<Long>> byEndpoint = new HashMap<>();142
final Set<Long> active = new LinkedHashSet<>();143
final Map<Long, Long> sleepingUntil = new HashMap<>();144
final Map<EndpointKey, FluidState> fluidCache = new HashMap<>();145
final Map<Long, Long> lastParticleTick = new HashMap<>();146
Object schedulerTask;147
Object listenerProxy;148
Object executorProxy;149
long tick;150
long lastResync;151
152
State(Object plugin) { this.plugin = plugin; }153
154
void enable() throws Exception {155
resyncConnections();156
registerEvents();157
Object server = call(plugin, "getServer");158
Object scheduler = call(server, "getScheduler");159
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());160
schedulerTask = call(scheduler, "runTaskTimer",161
new Class<?>[]{pluginClass, Runnable.class, long.class, long.class},162
plugin, (Runnable) this::tick, 1L, 1L);163
}164
165
void disable() {166
try { if (schedulerTask != null) call(schedulerTask, "cancel"); } catch (Throwable ignored) {}167
liquidConnections.clear();168
byEndpoint.clear();169
active.clear();170
sleepingUntil.clear();171
fluidCache.clear();172
}173
174
void registerEvents() throws Exception {175
ClassLoader cl = plugin.getClass().getClassLoader();176
Class<?> listener = Class.forName("org.bukkit.event.Listener", false, cl);177
Class<?> executor = Class.forName("org.bukkit.plugin.EventExecutor", false, cl);178
listenerProxy = Proxy.newProxyInstance(cl, new Class<?>[]{listener}, (p,m,a) -> proxyObjectMethod(p,m,a));179
executorProxy = Proxy.newProxyInstance(cl, new Class<?>[]{executor}, (p,m,a) -> {180
Object objectResult = proxyObjectMethod(p,m,a);181
if (m.getDeclaringClass() == Object.class) return objectResult;182
if ("execute".equals(m.getName()) && a != null && a.length == 2) handleEvent(a[1]);183
return null;184
});185
186
Object pm = call(call(plugin, "getServer"), "getPluginManager");187
Class<?> eventPriority = Class.forName("org.bukkit.event.EventPriority", false, cl);188
@SuppressWarnings({"unchecked","rawtypes"})189
Object lowest = Enum.valueOf((Class<? extends Enum>) eventPriority.asSubclass(Enum.class), "LOWEST");190
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, cl);191
192
String[] eventNames = {193
"org.bukkit.event.player.PlayerInteractEvent",194
"org.bukkit.event.block.CauldronLevelChangeEvent",195
"org.bukkit.event.world.ChunkLoadEvent"196
};197
for (String name : eventNames) {198
Class<?> eventClass = Class.forName(name, false, cl);199
call(pm, "registerEvent",200
new Class<?>[]{Class.class, listener, eventPriority, executor, pluginClass, boolean.class},201
eventClass, listenerProxy, lowest, executorProxy, plugin, false);202
}203
}204
205
void handleEvent(Object event) {206
try {207
String name = event.getClass().getName();208
if (name.endsWith("PlayerInteractEvent")) handleBlockInteract(event);209
else if (name.endsWith("CauldronLevelChangeEvent")) {210
Object block = call(event, "getBlock");211
scheduleWakeBlock(block, 1L);212
} else if (name.endsWith("ChunkLoadEvent")) {213
// Connections are intentionally not tagged with a persisted pipe214
// kind, so an endpoint that was unloaded during plugin startup can215
// only be classified once its chunks exist. Re-evaluate then.216
resyncConnections();217
Object chunk = call(event, "getChunk");218
wakeChunk(chunk);219
}220
} catch (Throwable ignored) {}221
}222
223
void handleBlockInteract(Object event) throws Exception {224
Object hand = call(event, "getHand");225
Object action = call(event, "getAction");226
if (hand == null || !"HAND".equals(String.valueOf(hand))) return;227
if (action == null || !"RIGHT_CLICK_BLOCK".equals(String.valueOf(action))) return;228
Object player = call(event, "getPlayer");229
if (!(Boolean) call(player, "isSneaking")) return;230
Object block = call(event, "getClickedBlock");231
if (block == null) return;232
233
String clickedType = materialName(block);234
boolean crafter = "CRAFTER".equals(clickedType);235
boolean destinationLiquid = isCauldronMaterial(clickedType);236
237
Object held = call(event, "getItem");238
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));239
240
@SuppressWarnings("unchecked")241
Map<Object,Object> selections = (Map<Object,Object>) field(plugin, "selections");242
Object playerId = call(player, "getUniqueId");243
Object selection = selections.get(playerId);244
245
// When a liquid source is already selected, the second click must be246
// another liquid container even if the clicked destination is an ordinary247
// chest/furnace. Likewise item networks may not terminate in a cauldron.248
if (selection != null) {249
Object sourceEndpoint = call(selection, "endpoint");250
Object sourceBlock = blockForEndpoint(sourceEndpoint);251
boolean sourceLiquid = sourceBlock != null && isCauldronMaterial(materialName(sourceBlock));252
if (sourceLiquid != destinationLiquid) {253
selections.remove(playerId);254
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);255
return;256
}257
// item -> crafter and liquid -> liquid continue into the normal258
// ContainerPipes route creation path.259
return;260
}261
262
if (!crafter && !destinationLiquid) return;263
264
Object blockFace = call(event, "getBlockFace");265
LiquidConnection endpointConnection = destinationLiquid ? liquidConnectionAt(block, blockFace) : null;266
if (endpointConnection != null) {267
// Liquid pipes have no filter UI. Shears are still allowed through268
// so the plugin's normal shift+shears removal path remains intact.269
if (!shears) call(event, "setCancelled", new Class<?>[]{boolean.class}, true);270
return;271
}272
273
// A Crafter is destination-only. First-clicking it as a source is a274
// silent no-op, except shears on an existing ordinary item endpoint.275
if (crafter && !shears) {276
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);277
}278
}279
280
boolean suppressPipeInteract(Object event) throws Exception {281
Object entity = call(event, "getRightClicked");282
@SuppressWarnings("unchecked")283
Set<String> tags = (Set<String>) call(entity, "getScoreboardTags");284
long id = -1;285
for (String tag : tags) {286
if (!tag.startsWith("containerpipes-filter:")) continue;287
try { id = Long.parseLong(tag.substring(tag.indexOf(':') + 1)); } catch (NumberFormatException ignored) {}288
}289
if (id < 0 || !liquidConnections.containsKey(id)) return false;290
Object player = call(event, "getPlayer");291
Object inventory = call(player, "getInventory");292
Object held = call(inventory, "getItemInMainHand");293
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));294
boolean sneaking = (Boolean) call(player, "isSneaking");295
return !(shears && sneaking);296
}297
298
void handlePipeInteract(Object event) throws Exception {299
Object entity = call(event, "getRightClicked");300
@SuppressWarnings("unchecked")301
Set<String> tags = (Set<String>) call(entity, "getScoreboardTags");302
long id = -1;303
for (String tag : tags) {304
if (!tag.startsWith("containerpipes-filter:")) continue;305
try { id = Long.parseLong(tag.substring(tag.indexOf(':') + 1)); } catch (NumberFormatException ignored) {}306
}307
if (id < 0 || !liquidConnections.containsKey(id)) return;308
Object player = call(event, "getPlayer");309
Object inventory = call(player, "getInventory");310
Object held = call(inventory, "getItemInMainHand");311
boolean shears = held != null && "SHEARS".equals(String.valueOf(call(held, "getType")));312
boolean sneaking = (Boolean) call(player, "isSneaking");313
if (!(shears && sneaking)) {314
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);315
}316
}317
318
void tick() {319
try {320
tick++;321
if (tick - lastResync >= 400) {322
resyncConnections();323
lastResync = tick;324
}325
326
int interval = Math.max(1, configInt("transfer-interval-ticks", 3));327
if (tick % interval != 0) return;328
329
// Emergency wakeup for missed external events. Keep the same general330
// cadence as item-pipe sleeping probes, but liquid networks are tiny.331
long probe = Math.max(20, configInt("performance.sleeping-probe-interval-ticks", 200));332
if (!sleepingUntil.isEmpty()) {333
ArrayList<Long> wake = new ArrayList<>();334
for (Map.Entry<Long,Long> e : sleepingUntil.entrySet()) {335
if (tick >= e.getValue()) wake.add(e.getKey());336
}337
for (long id : wake) {338
sleepingUntil.remove(id);339
active.add(id);340
LiquidConnection c = liquidConnections.get(id);341
if (c != null) {342
refreshFluid(c.source);343
refreshFluid(c.destination);344
}345
}346
}347
348
if (active.isEmpty()) return;349
ArrayList<Long> cycle = new ArrayList<>(active);350
for (long id : cycle) {351
LiquidConnection connection = liquidConnections.get(id);352
if (connection == null) { active.remove(id); continue; }353
if (transferOneLevel(connection)) continue;354
connection.failed++;355
int idleAfter = Math.max(1, configInt("performance.idle-after-failed-attempts", 3));356
if (connection.failed >= idleAfter) {357
connection.failed = 0;358
active.remove(id);359
sleepingUntil.put(id, tick + probe);360
}361
}362
} catch (Throwable t) {363
log(plugin, "Liquid transfer tick failed", t);364
}365
}366
367
boolean transferOneLevel(LiquidConnection connection) throws Exception {368
Object sourceBlock = blockForEndpoint(connection.source.raw);369
Object destinationBlock = blockForEndpoint(connection.destination.raw);370
if (sourceBlock == null || destinationBlock == null) return false;371
372
FluidState source = readFluid(sourceBlock);373
FluidState destination = readFluid(destinationBlock);374
fluidCache.put(connection.source.key, source);375
fluidCache.put(connection.destination.key, destination);376
377
if (!source.transferable()) return false;378
if (!destination.accepts(source.type)) return false;379
380
if (source.type == FluidType.WATER) {381
setWaterLevel(sourceBlock, source.level - 1);382
setWaterLevel(destinationBlock, destination.type == FluidType.EMPTY ? 1 : destination.level + 1);383
} else if (source.type == FluidType.LAVA) {384
setEmpty(sourceBlock);385
setLava(destinationBlock);386
} else {387
return false;388
}389
390
FluidState newSource = readFluid(sourceBlock);391
FluidState newDestination = readFluid(destinationBlock);392
fluidCache.put(connection.source.key, newSource);393
fluidCache.put(connection.destination.key, newDestination);394
connection.failed = 0;395
396
wakeEndpoint(connection.source.key);397
wakeEndpoint(connection.destination.key);398
animateLiquid(connection, source.type);399
return true;400
}401
402
void setWaterLevel(Object block, int level) throws Exception {403
if (level <= 0) { setEmpty(block); return; }404
if (!"WATER_CAULDRON".equals(materialName(block))) setBlockType(block, "WATER_CAULDRON");405
Object data = call(block, "getBlockData");406
call(data, "setLevel", new Class<?>[]{int.class}, level);407
call(block, "setBlockData", new Class<?>[]{Class.forName("org.bukkit.block.data.BlockData", false, plugin.getClass().getClassLoader())}, data);408
}409
410
void setLava(Object block) throws Exception { setBlockType(block, "LAVA_CAULDRON"); }411
void setEmpty(Object block) throws Exception { setBlockType(block, "CAULDRON"); }412
413
void setBlockType(Object block, String materialName) throws Exception {414
Class<?> materialClass = Class.forName("org.bukkit.Material", false, plugin.getClass().getClassLoader());415
@SuppressWarnings({"rawtypes","unchecked"})416
Object material = Enum.valueOf((Class<? extends Enum>) materialClass.asSubclass(Enum.class), materialName);417
call(block, "setType", new Class<?>[]{materialClass}, material);418
}419
420
FluidState readFluid(Object block) throws Exception {421
String name = materialName(block);422
if ("CAULDRON".equals(name)) return new FluidState(FluidType.EMPTY, 0, 0);423
if ("LAVA_CAULDRON".equals(name)) return new FluidState(FluidType.LAVA, 1, 1);424
if ("WATER_CAULDRON".equals(name)) {425
Object data = call(block, "getBlockData");426
int level = ((Number) call(data, "getLevel")).intValue();427
int max = ((Number) call(data, "getMaximumLevel")).intValue();428
return new FluidState(FluidType.WATER, level, max);429
}430
// Keep a pipe attached if a cauldron temporarily contains an unsupported431
// medium (e.g. powder snow), but never mix/transfer it as a liquid.432
if (isCauldronMaterial(name)) return new FluidState(FluidType.OTHER, 1, 1);433
return new FluidState(FluidType.OTHER, 0, 0);434
}435
436
void scheduleWakeBlock(Object block, long delay) throws Exception {437
Object server = call(plugin, "getServer");438
Object scheduler = call(server, "getScheduler");439
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());440
call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin,441
(Runnable) () -> {442
try {443
EndpointKey key = endpointKeyForBlock(block);444
refreshFluidByKey(key);445
wakeEndpoint(key);446
} catch (Throwable ignored) {}447
}, delay);448
}449
450
void wakeChunk(Object chunk) throws Exception {451
Object world = call(chunk, "getWorld");452
UUID worldId = (UUID) call(world, "getUID");453
int cx = ((Number) call(chunk, "getX")).intValue();454
int cz = ((Number) call(chunk, "getZ")).intValue();455
for (LiquidConnection c : liquidConnections.values()) {456
if (!c.source.key.world.equals(worldId)) continue;457
if ((c.source.x >> 4) == cx && (c.source.z >> 4) == cz458
|| (c.destination.x >> 4) == cx && (c.destination.z >> 4) == cz) {459
active.add(c.id);460
sleepingUntil.remove(c.id);461
}462
}463
}464
465
void wakeEndpoint(EndpointKey key) {466
Set<Long> ids = byEndpoint.get(key);467
if (ids == null) return;468
for (long id : ids) {469
active.add(id);470
sleepingUntil.remove(id);471
}472
}473
474
void refreshFluid(EndpointView endpoint) {475
try {476
Object block = blockForEndpoint(endpoint.raw);477
if (block != null) fluidCache.put(endpoint.key, readFluid(block));478
} catch (Throwable ignored) {}479
}480
481
void refreshFluidByKey(EndpointKey key) {482
try {483
Object world = getWorld(key.world);484
if (world == null) return;485
int x = unpackX(key.packed), y = unpackY(key.packed), z = unpackZ(key.packed);486
Object block = call(world, "getBlockAt", new Class<?>[]{int.class,int.class,int.class}, x,y,z);487
fluidCache.put(key, readFluid(block));488
} catch (Throwable ignored) {}489
}490
491
void animateLiquid(LiquidConnection connection, FluidType type) {492
try {493
int cooldown = Math.max(0, configInt("particles.transfer-animation-cooldown-ticks", 100));494
Long previous = lastParticleTick.get(connection.id);495
if (previous != null && tick - previous < cooldown) return;496
lastParticleTick.put(connection.id, tick);497
498
Object world = getWorld(connection.source.key.world);499
if (world == null) return;500
String particleName = type == FluidType.LAVA ? "DRIPPING_LAVA" : "DRIPPING_WATER";501
Class<?> particleClass = Class.forName("org.bukkit.Particle", false, plugin.getClass().getClassLoader());502
@SuppressWarnings({"rawtypes","unchecked"})503
Object particle = Enum.valueOf((Class<? extends Enum>) particleClass.asSubclass(Enum.class), particleName);504
505
ArrayList<double[]> points = connection.particlePoints();506
int stepTicks = Math.max(1, configInt("transfer-particle-step-ticks", 3));507
int perStep = Math.max(1, configInt("transfer-particle-points-per-step", 2));508
Class<?> locationClass = Class.forName("org.bukkit.Location", false, plugin.getClass().getClassLoader());509
Constructor<?> locationCtor = locationClass.getConstructor(Class.forName("org.bukkit.World", false, plugin.getClass().getClassLoader()), double.class,double.class,double.class);510
Object scheduler = call(call(plugin, "getServer"), "getScheduler");511
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());512
513
for (int i = 0; i < points.size(); i += perStep) {514
int from = i;515
int to = Math.min(points.size(), i + perStep);516
long delay = (long)(i / perStep) * stepTicks;517
Runnable r = () -> {518
for (int p = from; p < to; p++) {519
try {520
double[] xyz = points.get(p);521
Object loc = locationCtor.newInstance(world, xyz[0], xyz[1], xyz[2]);522
call(world, "spawnParticle", new Class<?>[]{particleClass, locationClass, int.class}, particle, loc, 1);523
} catch (Throwable ignored) {}524
}525
};526
call(scheduler, "runTaskLater", new Class<?>[]{pluginClass, Runnable.class, long.class}, plugin, r, delay);527
}528
} catch (Throwable ignored) {}529
}530
531
int configInt(String path, int fallback) {532
try {533
Object cfg = call(plugin, "getConfig");534
return ((Number) call(cfg, "getInt", new Class<?>[]{String.class,int.class}, path, fallback)).intValue();535
} catch (Throwable ignored) { return fallback; }536
}537
538
void resyncConnections() throws Exception {539
@SuppressWarnings("unchecked")540
Map<Long,Object> connections = (Map<Long,Object>) field(plugin, "connections");541
Set<Long> seen = new HashSet<>();542
for (Map.Entry<Long,Object> e : connections.entrySet()) {543
seen.add(e.getKey());544
inspectConnection(e.getValue(), true);545
}546
ArrayList<Long> stale = new ArrayList<>();547
for (long id : liquidConnections.keySet()) if (!seen.contains(id)) stale.add(id);548
for (long id : stale) removeLiquid(id);549
}550
551
void connectionChanged(Object connection, boolean added) throws Exception {552
long id = ((Number) call(connection, "id")).longValue();553
if (!added) { removeLiquid(id); return; }554
inspectConnection(connection, false);555
}556
557
void inspectConnection(Object raw, boolean resync) throws Exception {558
long id = ((Number) call(raw, "id")).longValue();559
Object sourceRaw = call(raw, "source");560
Object destinationRaw = call(raw, "destination");561
EndpointView source = endpointView(sourceRaw);562
EndpointView destination = endpointView(destinationRaw);563
Object sourceBlock = blockForEndpoint(sourceRaw);564
Object destinationBlock = blockForEndpoint(destinationRaw);565
LiquidConnection existing = liquidConnections.get(id);566
// If an endpoint chunk is currently unloaded, preserve a liquid567
// classification we already know instead of forgetting it. New/unseen568
// connections are classified as soon as both endpoints are loaded.569
if (sourceBlock == null || destinationBlock == null) {570
if (existing != null) return;571
return;572
}573
boolean liquid = isCauldronMaterial(materialName(sourceBlock))574
&& isCauldronMaterial(materialName(destinationBlock));575
if (!liquid) { removeLiquid(id); return; }576
577
578
if (existing != null && existing.source.key.equals(source.key) && existing.destination.key.equals(destination.key)) return;579
removeLiquid(id);580
LiquidConnection c = new LiquidConnection(id, raw, source, destination, readPath(raw));581
liquidConnections.put(id, c);582
byEndpoint.computeIfAbsent(source.key, k -> new LinkedHashSet<>()).add(id);583
byEndpoint.computeIfAbsent(destination.key, k -> new LinkedHashSet<>()).add(id);584
refreshFluid(source);585
refreshFluid(destination);586
active.add(id);587
sleepingUntil.remove(id);588
}589
590
void removeLiquid(long id) {591
LiquidConnection c = liquidConnections.remove(id);592
active.remove(id);593
sleepingUntil.remove(id);594
lastParticleTick.remove(id);595
if (c == null) return;596
removeIndex(c.source.key, id);597
removeIndex(c.destination.key, id);598
}599
600
void removeIndex(EndpointKey key, long id) {601
Set<Long> ids = byEndpoint.get(key);602
if (ids == null) return;603
ids.remove(id);604
if (ids.isEmpty()) byEndpoint.remove(key);605
}606
607
LiquidConnection liquidConnectionAt(Object block, Object face) {608
try {609
UUID world = (UUID) call(call(block, "getWorld"), "getUID");610
int x = ((Number) call(block, "getX")).intValue();611
int y = ((Number) call(block, "getY")).intValue();612
int z = ((Number) call(block, "getZ")).intValue();613
String faceName = String.valueOf(face);614
for (LiquidConnection c : liquidConnections.values()) {615
if (c.source.matches(world,x,y,z,faceName) || c.destination.matches(world,x,y,z,faceName)) return c;616
}617
} catch (Throwable ignored) {}618
return null;619
}620
621
Object blockForEndpoint(Object endpoint) throws Exception {622
UUID worldId = (UUID) call(endpoint, "world");623
int x = ((Number) call(endpoint, "x")).intValue();624
int y = ((Number) call(endpoint, "y")).intValue();625
int z = ((Number) call(endpoint, "z")).intValue();626
Object world = getWorld(worldId);627
if (world == null) return null;628
boolean loaded = (Boolean) call(world, "isChunkLoaded", new Class<?>[]{int.class,int.class}, x >> 4, z >> 4);629
if (!loaded) return null;630
return call(world, "getBlockAt", new Class<?>[]{int.class,int.class,int.class}, x,y,z);631
}632
633
Object getWorld(UUID id) throws Exception {634
Class<?> bukkit = Class.forName("org.bukkit.Bukkit", false, plugin.getClass().getClassLoader());635
Method m = bukkit.getMethod("getWorld", UUID.class);636
return m.invoke(null, id);637
}638
639
EndpointKey endpointKeyForBlock(Object block) throws Exception {640
UUID world = (UUID) call(call(block, "getWorld"), "getUID");641
int x = ((Number) call(block, "getX")).intValue();642
int y = ((Number) call(block, "getY")).intValue();643
int z = ((Number) call(block, "getZ")).intValue();644
return new EndpointKey(world, pack(x,y,z));645
}646
647
EndpointView endpointView(Object endpoint) throws Exception {648
UUID world = (UUID) call(endpoint, "world");649
int x = ((Number) call(endpoint, "x")).intValue();650
int y = ((Number) call(endpoint, "y")).intValue();651
int z = ((Number) call(endpoint, "z")).intValue();652
String face = String.valueOf(call(endpoint, "face"));653
return new EndpointView(endpoint, new EndpointKey(world, pack(x,y,z)), x,y,z,face);654
}655
656
ArrayList<int[]> readPath(Object connection) throws Exception {657
ArrayList<int[]> out = new ArrayList<>();658
for (Object p : (List<?>) call(connection, "path")) {659
out.add(new int[]{((Number)call(p,"x")).intValue(), ((Number)call(p,"y")).intValue(), ((Number)call(p,"z")).intValue()});660
}661
return out;662
}663
}664
665
private enum FluidType { EMPTY, WATER, LAVA, OTHER }666
private record FluidState(FluidType type, int level, int max) {667
boolean transferable() { return (type == FluidType.WATER || type == FluidType.LAVA) && level > 0; }668
boolean accepts(FluidType incoming) {669
if (incoming != FluidType.WATER && incoming != FluidType.LAVA) return false;670
if (type == FluidType.EMPTY) return true;671
if (type != incoming) return false;672
return level < max;673
}674
}675
private record EndpointKey(UUID world, long packed) {}676
private record EndpointView(Object raw, EndpointKey key, int x, int y, int z, String face) {677
boolean matches(UUID w,int bx,int by,int bz,String f){return key.world.equals(w)&&x==bx&&y==by&&z==bz&&face.equals(f);}678
}679
private static final class LiquidConnection {680
final long id; final Object raw; final EndpointView source,destination; final ArrayList<int[]> path; int failed;681
LiquidConnection(long id,Object raw,EndpointView source,EndpointView destination,ArrayList<int[]> path){this.id=id;this.raw=raw;this.source=source;this.destination=destination;this.path=path;}682
ArrayList<double[]> particlePoints(){683
ArrayList<double[]> points=new ArrayList<>(path.size()+2);684
points.add(new double[]{source.x+0.5,source.y+0.5,source.z+0.5});685
for(int[]p:path)points.add(new double[]{p[0]+0.5,p[1]+0.5,p[2]+0.5});686
points.add(new double[]{destination.x+0.5,destination.y+0.5,destination.z+0.5});687
return points;688
}689
}690
691
private static Object proxyObjectMethod(Object proxy, Method method, Object[] args) {692
if (method.getDeclaringClass() != Object.class) return null;693
return switch (method.getName()) {694
case "hashCode" -> System.identityHashCode(proxy);695
case "equals" -> proxy == (args == null || args.length == 0 ? null : args[0]);696
case "toString" -> "ContainerPipesRuntimeListener";697
default -> null;698
};699
}700
701
private static boolean isCauldronMaterial(String name) {702
return "CAULDRON".equals(name) || "WATER_CAULDRON".equals(name)703
|| "LAVA_CAULDRON".equals(name) || "POWDER_SNOW_CAULDRON".equals(name);704
}705
706
private static String materialName(Object block) {707
if (block == null) return "";708
try { return String.valueOf(call(block, "getType")); }709
catch (Throwable ignored) { return ""; }710
}711
712
private static boolean isEmptyItem(Object item) {713
if (item == null) return true;714
try { return "AIR".equals(String.valueOf(call(item, "getType"))); }715
catch (Throwable ignored) { return true; }716
}717
718
private static Object cloneOne(Object item) throws Exception {719
Object clone = call(item, "clone");720
call(clone, "setAmount", new Class<?>[]{int.class}, 1);721
return clone;722
}723
724
private static boolean sameStackExact(Object a, Object b) throws Exception {725
if (isEmptyItem(a) || isEmptyItem(b)) return isEmptyItem(a) == isEmptyItem(b);726
int aa = ((Number) call(a, "getAmount")).intValue();727
int bb = ((Number) call(b, "getAmount")).intValue();728
return aa == bb && (Boolean) call(a, "isSimilar", new Class<?>[]{itemStackClass()}, b);729
}730
731
private static Class<?> itemStackClass() throws ClassNotFoundException {732
ClassLoader cl = Thread.currentThread().getContextClassLoader();733
try { return Class.forName("org.bukkit.inventory.ItemStack", false, cl); }734
catch (ClassNotFoundException e) { return Class.forName("org.bukkit.inventory.ItemStack"); }735
}736
737
private static Object field(Object target, String name) throws Exception {738
FieldKey key = new FieldKey(target.getClass(), name);739
Field f = FIELDS.get(key);740
if (f == null) {741
for (Class<?> c = target.getClass(); c != null; c = c.getSuperclass()) {742
try { f = c.getDeclaredField(name); f.setAccessible(true); FIELDS.put(key,f); break; }743
catch (NoSuchFieldException ignored) {}744
}745
}746
if (f == null) throw new NoSuchFieldException(name);747
return f.get(target);748
}749
750
private static Object call(Object target, String name, Object... args) throws Exception {751
return call(target, name, new Class<?>[0], args);752
}753
private static Object call(Object target, String name, Class<?>[] hinted, Object... args) throws Exception {754
if (target == null) throw new NullPointerException(name);755
Method method = findMethod(target.getClass(), name, hinted, args);756
return method.invoke(target, args);757
}758
private static Method findMethod(Class<?> owner, String name, Class<?>[] hinted, Object[] args) throws Exception {759
MethodKey key = new MethodKey(owner,name,signatureKey(hinted,args));760
Method cached = METHODS.get(key);761
if (cached != null) return cached;762
for (Class<?> c=owner;c!=null;c=c.getSuperclass()) {763
for (Method m:c.getDeclaredMethods()) if (matches(m,name,hinted,args)) {m.setAccessible(true);METHODS.put(key,m);return m;}764
}765
for(Method m:owner.getMethods())if(matches(m,name,hinted,args)){m.setAccessible(true);METHODS.put(key,m);return m;}766
throw new NoSuchMethodException(owner.getName()+"."+name);767
}768
private static boolean matches(Method m,String name,Class<?>[] hinted,Object[] args){769
if(!m.getName().equals(name)||m.getParameterCount()!=args.length)return false;770
Class<?>[] p=m.getParameterTypes();771
for(int i=0;i<p.length;i++){772
Class<?> wanted=hinted.length==args.length?hinted[i]:(args[i]==null?null:args[i].getClass());773
if(wanted==null)continue;774
if(p[i].isPrimitive()){775
if(!primitiveWrap(p[i]).isAssignableFrom(primitiveWrap(wanted)))return false;776
}else if(!p[i].isAssignableFrom(wanted)&&args[i]!=null&&!p[i].isInstance(args[i]))return false;777
}778
return true;779
}780
private static Class<?> primitiveWrap(Class<?> c){781
if(!c.isPrimitive())return c;782
if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;783
if(c==double.class)return Double.class;if(c==float.class)return Float.class;if(c==short.class)return Short.class;784
if(c==byte.class)return Byte.class;if(c==char.class)return Character.class;return c;785
}786
private static List<Class<?>> signatureKey(Class<?>[] hinted,Object[]args){787
ArrayList<Class<?>> out=new ArrayList<>(args.length);788
for(int i=0;i<args.length;i++)out.add(hinted.length==args.length?primitiveWrap(hinted[i]):(args[i]==null?Object.class:args[i].getClass()));789
return out;790
}791
792
private static long pack(int x,int y,int z){return((long)(x&0x3FFFFFF)<<38)|((long)(z&0x3FFFFFF)<<12)|(y&0xFFFL);}793
private static int unpackX(long p){int x=(int)(p>>38);return x>=0x2000000?x-0x4000000:x;}794
private static int unpackY(long p){int y=(int)(p&0xFFF);return y>=0x800?y-0x1000:y;}795
private static int unpackZ(long p){int z=(int)((p>>12)&0x3FFFFFF);return z>=0x2000000?z-0x4000000:z;}796
797
private static void log(Object plugin,String message,Throwable t){798
try{Object logger=call(plugin,"getLogger");call(logger,"warning",new Class<?>[]{String.class},message+": "+t);}catch(Throwable ignored){}799
}800
private record MethodKey(Class<?> owner,String name,List<Class<?>>args){}801
private record FieldKey(Class<?> owner,String name){}802
}@@ -0,0 +1,742 @@
1
package nl.timfalken.containerpipes;
2
3
import org.bukkit.*;
4
import org.bukkit.block.*;
5
import org.bukkit.command.*;
6
import org.bukkit.configuration.file.FileConfiguration;
7
import org.bukkit.entity.BlockDisplay;
8
import org.bukkit.entity.Interaction;
9
import org.bukkit.entity.Player;
10
import org.bukkit.event.*;
11
import org.bukkit.event.block.*;
12
import org.bukkit.event.player.PlayerInteractEvent;
13
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
14
import org.bukkit.event.entity.EntityChangeBlockEvent;
15
import org.bukkit.event.inventory.InventoryClickEvent;
16
import org.bukkit.event.inventory.InventoryDragEvent;
17
import org.bukkit.event.inventory.InventoryCloseEvent;
18
import org.bukkit.event.world.*;
19
import org.bukkit.inventory.*;
20
import org.bukkit.event.inventory.InventoryType;
21
import org.bukkit.inventory.EquipmentSlot;
22
import org.bukkit.plugin.java.JavaPlugin;
23
import org.bukkit.scheduler.BukkitTask;
24
import org.bukkit.util.Transformation;
25
import org.joml.AxisAngle4f;
26
import org.joml.Vector3f;
27
28
import java.io.*;
29
import java.nio.charset.StandardCharsets;
30
import java.nio.file.Files;
31
import java.util.*;
32
import java.util.concurrent.atomic.AtomicLong;
33
import java.util.Base64;
34
35
public final class ContainerPipesPlugin extends JavaPlugin implements Listener, CommandExecutor {
36
private final Map<Long, Connection> connections = new LinkedHashMap<>();
37
// O(1) indices: no Bukkit Block or Chunk objects are retained.
38
private final Map<Endpoint, Long> endpointIndex = new HashMap<>();
39
private final Map<WorldBlockPos, Long> routeIndex = new HashMap<>();
40
private final Map<ChunkKey, Set<Long>> connectionsByChunk = new HashMap<>();
41
private final Map<UUID, Selection> selections = new HashMap<>();
42
private final Map<Long, List<UUID>> displayIds = new HashMap<>();
43
private final Map<UUID, Long> lastInteractions = new HashMap<>();
44
private final AtomicLong nextId = new AtomicLong(1);
45
private final Map<Long, FilterHolder> openFilters = new HashMap<>();
46
private File dataFile;
47
private boolean connectionFileWritable = true;
48
private BukkitTask transferTask;
49
private BukkitTask validationTask;
50
51
@Override public void onEnable() {
52
saveDefaultConfig();
53
dataFile = new File(getDataFolder(), "connections.tsv");
54
getServer().getPluginManager().registerEvents(this, this);
55
Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);
56
cleanupTaggedDisplays();
57
loadConnections();
58
startTasks();
59
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
60
getLogger().info("ContainerPipes 1.7.0 enabled with " + connections.size() + " connection(s).");
61
AdvancedEndpointsPatch.enable(this);
62
}
63
64
@Override public void onDisable() {
65
if (transferTask != null) transferTask.cancel();
66
if (validationTask != null) validationTask.cancel();
67
saveConnectionsNow();
68
removeAllDisplays();
69
selections.clear();
70
AdvancedEndpointsPatch.disable(this);
71
}
72
73
private void startTasks() {
74
if (transferTask != null) transferTask.cancel();
75
if (validationTask != null) validationTask.cancel();
76
long transfer = Math.max(1, getConfig().getLong("transfer-interval-ticks", 10));
77
long validate = Math.max(1, getConfig().getLong("validation-interval-ticks", 20));
78
transferTask = Bukkit.getScheduler().runTaskTimer(this,
79
() -> OptimizedTransferPlanner.tick(this), transfer, transfer);
80
validationTask = Bukkit.getScheduler().runTaskTimer(this, this::validateConnections, validate, validate);
81
}
82
83
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
84
public void onInteract(PlayerInteractEvent event) {
85
if (event.getHand() != EquipmentSlot.HAND) return;
86
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isSneaking()) return;
87
Player player = event.getPlayer();
88
long now = System.currentTimeMillis();
89
long debounceMillis = Math.max(0, getConfig().getLong("interaction-debounce-millis", 100));
90
Long previous = lastInteractions.put(player.getUniqueId(), now);
91
if (previous != null && now - previous < debounceMillis) return;
92
Block block = event.getClickedBlock();
93
BlockFace face = event.getBlockFace();
94
if (block == null || !isAllowedContainer(block)) return;
95
if (!player.hasPermission("containerpipes.use")) return;
96
97
ItemStack held = event.getItem();
98
boolean emptyHand = held == null || held.getType().isAir();
99
boolean shears = held != null && held.getType() == Material.SHEARS;
100
if (!emptyHand && !shears) return;
101
event.setCancelled(true);
102
103
if (shears) {
104
Connection existing = findByEndpoint(endpoint(block, face));
105
if (existing != null) {
106
removeConnection(existing.id, true);
107
send(player, "disconnected");
108
} else {
109
selections.remove(player.getUniqueId());
110
send(player, "selection-cancelled");
111
}
112
return;
113
}
114
115
Endpoint clicked = endpoint(block, face);
116
Selection selection = selections.remove(player.getUniqueId());
117
if (selection == null) {
118
Connection existing = findByEndpoint(clicked);
119
if (existing != null) {
120
openFilter(player, existing.id);
121
return;
122
}
123
selections.put(player.getUniqueId(), new Selection(clicked, System.currentTimeMillis()));
124
spawnSelectionParticles(player, clicked);
125
send(player, "selected-source");
126
return;
127
}
128
129
Endpoint source = selection.endpoint;
130
if (!source.world.equals(clicked.world)) { send(player, "different-world"); return; }
131
if (source.equals(clicked)) { send(player, "selection-cancelled"); return; }
132
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "side-in-use"); return; }
133
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));
134
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "too-far"); return; }
135
136
World world = Bukkit.getWorld(source.world);
137
if (world == null) return;
138
BlockPos start = source.outside();
139
BlockPos goal = clicked.outside();
140
Set<BlockPos> occupied = occupiedPipeBlocks(source.world);
141
List<BlockPos> route = findRoute(world, start, goal, maxRange, occupied);
142
if (route == null) { send(player, "no-route"); return; }
143
144
long id = nextId.getAndIncrement();
145
Connection c = new Connection(id, source, clicked, route, List.of());
146
registerConnection(c);
147
saveConnections();
148
spawnDisplays(c);
149
send(player, "connected");
150
}
151
152
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
153
public void onBlockPlace(BlockPlaceEvent event) {
154
if (isPipeRouteBlock(event.getBlockPlaced())) event.setCancelled(true);
155
}
156
157
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
158
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
159
if (event.getReplacedBlockStates().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
160
}
161
162
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
163
public void onBlockGrow(BlockGrowEvent event) { cancelIfPipe(event, event.getBlock()); }
164
165
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
166
public void onBlockSpread(BlockSpreadEvent event) { cancelIfPipe(event, event.getBlock()); }
167
168
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
169
public void onBlockForm(BlockFormEvent event) { cancelIfPipe(event, event.getBlock()); }
170
171
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
172
public void onEntityBlockForm(EntityBlockFormEvent event) { cancelIfPipe(event, event.getBlock()); }
173
174
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
175
public void onEntityChangeBlock(EntityChangeBlockEvent event) { cancelIfPipe(event, event.getBlock()); }
176
177
// Liquids are intentionally allowed to flow through visual pipe routes.
178
// Solid block creation/placement is still protected by the other handlers.
179
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
180
public void onBlockFromTo(BlockFromToEvent event) { }
181
182
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
183
public void onFluidLevelChange(FluidLevelChangeEvent event) { }
184
185
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
186
public void onStructureGrow(StructureGrowEvent event) {
187
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
188
}
189
190
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
191
public void onBlockFertilize(BlockFertilizeEvent event) {
192
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
193
}
194
195
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
196
public void onPortalCreate(PortalCreateEvent event) {
197
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
198
}
199
200
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
201
public void onPistonExtend(BlockPistonExtendEvent event) {
202
BlockFace direction = event.getDirection();
203
if (event.getBlocks().stream().map(block -> block.getRelative(direction)).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
204
}
205
206
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
207
public void onPistonRetract(BlockPistonRetractEvent event) {
208
BlockFace movement = event.getDirection().getOppositeFace();
209
if (event.getBlocks().stream().map(block -> block.getRelative(movement)).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);
210
}
211
212
private void cancelIfPipe(Cancellable event, Block target) {
213
if (isPipeRouteBlock(target)) event.setCancelled(true);
214
}
215
@EventHandler(ignoreCancelled = true)
216
public void onBlockBreak(BlockBreakEvent event) {
217
Block block = event.getBlock();
218
Set<Long> affected = new HashSet<>();
219
for (BlockFace face : BlockFace.values()) {
220
Long id = endpointIndex.get(endpoint(block, face));
221
if (id != null) affected.add(id);
222
}
223
for (long id : affected) removeConnection(id, false);
224
if (!affected.isEmpty()) saveConnections();
225
}
226
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
227
Bukkit.getScheduler().runTask(this, () -> refreshChunk(event.getChunk()));
228
}
229
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) { removeDisplaysInChunk(event.getChunk()); }
230
231
private void validateConnections() {
232
for (Connection c : List.copyOf(connections.values())) {
233
World world = Bukkit.getWorld(c.source.world);
234
if (world == null) continue;
235
if (!isEndpointContainer(c.source) || !isEndpointContainer(c.destination)) { removeConnection(c.id, true); continue; }
236
237
}
238
}
239
240
private boolean isEndpointContainer(Endpoint e) {
241
World w = Bukkit.getWorld(e.world);
242
return w != null && (!w.isChunkLoaded(e.x >> 4, e.z >> 4) || isAllowedContainer(w.getBlockAt(e.x,e.y,e.z)));
243
}
244
245
private boolean destinationCanEverAccept(Connection connection, ItemStack item) {
246
World world = Bukkit.getWorld(connection.destination.world);
247
if (world == null || !world.isChunkLoaded(connection.destination.x >> 4, connection.destination.z >> 4)) return true;
248
Inventory destination = inventoryOf(world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z));
249
if (destination == null) return false;
250
if (destination instanceof FurnaceInventory furnace) return furnace.canSmelt(item) || furnace.isFuel(item);
251
return true;
252
}
253
254
private Inventory inventoryOf(Block block) {
255
BlockState state = block.getState();
256
if (state instanceof Chest chest) return chest.getInventory();
257
if (state instanceof Container container) return container.getInventory();
258
return null;
259
}
260
261
private boolean isAllowedContainer(Block block) {
262
if (AdvancedEndpointsPatch.isExtendedContainer(block)) return true;
263
String n = block.getType().name();
264
if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;
265
return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;
266
}
267
268
private Endpoint endpoint(Block b, BlockFace face) { return new Endpoint(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ(), face); }
269
private Connection findByEndpoint(Endpoint e) {
270
Long id = endpointIndex.get(e);
271
return id == null ? null : connections.get(id);
272
}
273
274
private List<BlockPos> findRoute(World world, BlockPos start, BlockPos goal, int range, Set<BlockPos> occupied) {
275
if (!isRouteSpace(world.getBlockAt(start.x,start.y,start.z), true) || !isRouteSpace(world.getBlockAt(goal.x,goal.y,goal.z), true)) return null;
276
record Node(BlockPos pos, int g, int f) {}
277
PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingInt(Node::f));
278
Map<BlockPos,Integer> g = new HashMap<>();
279
Map<BlockPos,BlockPos> prev = new HashMap<>();
280
open.add(new Node(start,0,start.manhattan(goal))); g.put(start,0);
281
int visited=0, limit=Math.max(4096, range*range*range*4);
282
while(!open.isEmpty() && visited++<limit) {
283
Node n=open.poll(); if(n.g()!=g.getOrDefault(n.pos(),Integer.MAX_VALUE)) continue;
284
if(n.pos().equals(goal)) return reconstruct(prev, goal);
285
for(BlockPos q:n.pos().neighbors()) {
286
if(q.y<world.getMinHeight() || q.y>=world.getMaxHeight()) continue;
287
if(Math.abs(q.x-start.x)>range || Math.abs(q.y-start.y)>range || Math.abs(q.z-start.z)>range) continue;
288
if(!q.equals(goal) && occupied.contains(q)) continue;
289
if(!isRouteSpace(world.getBlockAt(q.x,q.y,q.z), q.equals(goal))) continue;
290
int ng=n.g()+1;
291
if(ng<g.getOrDefault(q,Integer.MAX_VALUE)) { g.put(q,ng); prev.put(q,n.pos()); open.add(new Node(q,ng,ng+q.manhattan(goal))); }
292
}
293
}
294
return null;
295
}
296
private static List<BlockPos> reconstruct(Map<BlockPos,BlockPos> prev, BlockPos goal) { ArrayList<BlockPos> out=new ArrayList<>(); for(BlockPos p=goal;p!=null;p=prev.get(p))out.add(p); Collections.reverse(out); return out; }
297
private boolean isRouteSpace(Block block, boolean endpointOutside) {
298
return block.getType().isAir() || block.isLiquid();
299
}
300
private Set<BlockPos> occupiedPipeBlocks(UUID world) {
301
Set<BlockPos> occupied = new HashSet<>();
302
for (WorldBlockPos p : routeIndex.keySet()) if (p.world.equals(world)) occupied.add(p.pos());
303
return occupied;
304
}
305
306
private void spawnDisplays(Connection c) {
307
removeDisplays(c.id);
308
World world=Bukkit.getWorld(c.source.world); if(world==null)return;
309
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
310
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
311
final Material pipeMaterial = material;
312
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
313
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
314
final Material filteredSourceMaterial=filteredMaterial;
315
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
316
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
317
float sourceEndpointScale=endpointScale("source-endpoint-scale");
318
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
319
List<UUID> ids=new ArrayList<>();
320
List<DisplayPoint> points=polylinePoints(c, spacing);
321
for(DisplayPoint point:points) {
322
Location loc = point.location();
323
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
324
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;
325
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{
326
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
327
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
328
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);
329
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);
330
});
331
ids.add(d.getUniqueId());
332
Interaction hit=world.spawn(loc, Interaction.class, interaction->{
333
interaction.setInteractionWidth(Math.max(0.28f, pointScale));
334
interaction.setInteractionHeight(Math.max(0.28f, pointScale));
335
interaction.setResponsive(true);
336
interaction.setPersistent(false);
337
interaction.addScoreboardTag("containerpipes");
338
interaction.addScoreboardTag("containerpipes-filter:"+c.id);
339
});
340
ids.add(hit.getUniqueId());
341
}
342
displayIds.put(c.id,ids);
343
}
344
345
private List<DisplayPoint> polylinePoints(Connection c,double spacing) {
346
World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();
347
float sourceEndpointScale=endpointScale("source-endpoint-scale");
348
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
349
ArrayList<Location> centers=new ArrayList<>();
350
Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);
351
for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));
352
centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));
353
ArrayList<Location> raw=new ArrayList<>();
354
for(int i=0;i<centers.size()-1;i++) {
355
Location a=centers.get(i),b=centers.get(i+1); double dist=a.distance(b); int steps=Math.max(1,(int)Math.ceil(dist/spacing));
356
for(int j=(i==0?0:1);j<=steps;j++) { double t=(double)j/steps; raw.add(new Location(w,a.getX()+(b.getX()-a.getX())*t,a.getY()+(b.getY()-a.getY())*t,a.getZ()+(b.getZ()-a.getZ())*t)); }
357
}
358
ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());
359
for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));
360
return out;
361
}
362
363
private void spawnSelectionParticles(Player p, Endpoint e) {
364
World w=Bukkit.getWorld(e.world); if(w==null)return; Location l=e.faceCenter(w);
365
int count=Math.max(1,getConfig().getInt("selection-particle-count",12));
366
w.spawnParticle(Particle.HAPPY_VILLAGER,l,count,0.18,0.18,0.18,0);
367
}
368
private void refreshSelectionParticles() {
369
for (Map.Entry<UUID, Selection> entry : selections.entrySet()) {
370
Player player = Bukkit.getPlayer(entry.getKey());
371
if (player != null && player.isOnline()) spawnSelectionParticles(player, entry.getValue().endpoint);
372
}
373
}
374
375
private void animateTransfer(Connection c) {
376
World world = Bukkit.getWorld(c.source.world);
377
if (world == null) return;
378
List<DisplayPoint> displayPoints = polylinePoints(c, Math.max(0.1, getConfig().getDouble("transfer-particle-spacing", 0.25)));
379
if (displayPoints.isEmpty()) return;
380
int stepTicks = Math.max(1, getConfig().getInt("transfer-particle-step-ticks", 1));
381
int pointsPerStep = Math.max(1, getConfig().getInt("transfer-particle-points-per-step", 2));
382
BukkitTask[] task = new BukkitTask[1];
383
int[] index = {0};
384
task[0] = Bukkit.getScheduler().runTaskTimer(this, () -> {
385
if (index[0] >= displayPoints.size()) {
386
task[0].cancel();
387
return;
388
}
389
for (int i = 0; i < pointsPerStep && index[0] < displayPoints.size(); i++, index[0]++) {
390
Location location = displayPoints.get(index[0]).location();
391
if (world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {
392
world.spawnParticle(Particle.END_ROD, location, 1, 0, 0, 0, 0);
393
}
394
}
395
}, 0L, stepTicks);
396
}
397
private void expireSelections(){long max=Math.max(1,getConfig().getLong("selection-timeout-seconds",30))*1000; long now=System.currentTimeMillis(); selections.entrySet().removeIf(e->now-e.getValue().createdAt>max);}
398
399
private void refreshLoadedDisplays(){for(Connection c:connections.values())spawnDisplays(c);}
400
private void refreshChunk(Chunk chunk) {
401
for (long id : connectionIdsInChunk(chunk)) {
402
Connection c = connections.get(id);
403
if (c != null) spawnMissingDisplaysInChunk(c, chunk);
404
}
405
}
406
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}
407
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}
408
private void removeDisplaysInChunk(Chunk chunk){
409
Set<UUID> removed=new HashSet<>();
410
for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}
411
if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);
412
}
413
private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {
414
World world=Bukkit.getWorld(c.source.world); if(world==null)return;
415
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
416
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
417
final Material pipeMaterial=material;
418
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
419
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
420
final Material filteredSourceMaterial=filteredMaterial;
421
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
422
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
423
float sourceEndpointScale=endpointScale("source-endpoint-scale");
424
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
425
List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());
426
for(DisplayPoint point:polylinePoints(c,spacing)) {
427
Location loc=point.location();
428
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;
429
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
430
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{
431
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
432
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
433
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);
434
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);
435
});
436
ids.add(d.getUniqueId());
437
Interaction hit=world.spawn(loc,Interaction.class,interaction->{
438
interaction.setInteractionWidth(Math.max(0.28f,pointScale));
439
interaction.setInteractionHeight(Math.max(0.28f,pointScale));
440
interaction.setResponsive(true);interaction.setPersistent(false);
441
interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);
442
});
443
ids.add(hit.getUniqueId());
444
}
445
}
446
private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}
447
448
private void removeConnection(long id, boolean save) {
449
Connection removed = connections.get(id);
450
if (removed != null) unregisterConnection(removed);
451
removeDisplays(id);
452
if (save) saveConnections();
453
}
454
455
private void clearConnectionIndices() {
456
connections.clear();
457
endpointIndex.clear();
458
routeIndex.clear();
459
connectionsByChunk.clear();
460
}
461
462
private void registerConnection(Connection c) {
463
connections.put(c.id, c);
464
endpointIndex.put(c.source, c.id);
465
endpointIndex.put(c.destination, c.id);
466
UUID world = c.source.world;
467
for (BlockPos p : c.path) routeIndex.put(new WorldBlockPos(world, p), c.id);
468
for (ChunkKey key : c.chunkKeys()) connectionsByChunk.computeIfAbsent(key, ignored -> new HashSet<>()).add(c.id);
469
AdvancedEndpointsPatch.connectionChanged(this, c, true);
470
}
471
472
private void unregisterConnection(Connection c) {
473
connections.remove(c.id);
474
endpointIndex.remove(c.source, c.id);
475
endpointIndex.remove(c.destination, c.id);
476
UUID world = c.source.world;
477
for (BlockPos p : c.path) routeIndex.remove(new WorldBlockPos(world, p), c.id);
478
for (ChunkKey key : c.chunkKeys()) {
479
Set<Long> ids = connectionsByChunk.get(key);
480
if (ids == null) continue;
481
ids.remove(c.id);
482
if (ids.isEmpty()) connectionsByChunk.remove(key);
483
}
484
AdvancedEndpointsPatch.connectionChanged(this, c, false);
485
}
486
487
private Set<Long> connectionIdsInChunk(Chunk chunk) {
488
Set<Long> ids = connectionsByChunk.get(ChunkKey.of(chunk));
489
return ids == null ? Set.of() : Set.copyOf(ids);
490
}
491
492
private void saveConnections(){ PersistenceDebouncer.request(this); }
493
494
private void saveConnectionsNow(){
495
if (!connectionFileWritable) {
496
getLogger().warning("connections.tsv staat in herstelmodus en wordt niet overschreven. Herstel eerst de gemelde ongeldige regels.");
497
return;
498
}
499
try {
500
getDataFolder().mkdirs();
501
java.nio.file.Path target=dataFile.toPath();
502
java.nio.file.Path temporary=target.resolveSibling(target.getFileName()+".tmp");
503
java.nio.file.Path backup=target.resolveSibling(target.getFileName()+".bak");
504
StringBuilder s=new StringBuilder("# ContainerPipes 1.2.5\n");
505
for(Connection c:connections.values())s.append(c.serialize()).append('\n');
506
Files.writeString(temporary,s.toString(),StandardCharsets.UTF_8);
507
if(Files.exists(target))Files.copy(target,backup,java.nio.file.StandardCopyOption.REPLACE_EXISTING);
508
try {
509
Files.move(temporary,target,java.nio.file.StandardCopyOption.REPLACE_EXISTING,java.nio.file.StandardCopyOption.ATOMIC_MOVE);
510
} catch(java.nio.file.AtomicMoveNotSupportedException ignored) {
511
Files.move(temporary,target,java.nio.file.StandardCopyOption.REPLACE_EXISTING);
512
}
513
} catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingen niet opslaan",e);}
514
}
515
private void loadConnections(){
516
clearConnectionIndices();
517
nextId.set(1);
518
connectionFileWritable=true;
519
if(!dataFile.exists())return;
520
int loaded=0;
521
int skipped=0;
522
try {
523
List<String> lines=Files.readAllLines(dataFile.toPath(),StandardCharsets.UTF_8);
524
for(int i=0;i<lines.size();i++) {
525
String line=lines.get(i).trim();
526
if(line.isEmpty()||line.startsWith("#"))continue;
527
try {
528
Connection c=Connection.parse(line);
529
registerConnection(c);
530
nextId.set(Math.max(nextId.get(),c.id+1));
531
loaded++;
532
} catch(Exception entryError) {
533
skipped++;
534
getLogger().warning("Ongeldige verbinding overgeslagen op regel "+(i+1)+": "+entryError.getMessage());
535
}
536
}
537
if(skipped>0) {
538
connectionFileWritable=false;
539
getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen. Bestand blijft ongewijzigd (herstelmodus).");
540
}
541
} catch(Exception e) {
542
connectionFileWritable=false;
543
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen; bestand blijft ongewijzigd",e);
544
}
545
}
546
547
private float endpointScale(String key) {
548
double legacy=getConfig().getDouble("endpoint-scale",0.40);
549
return (float)Math.max(0.05,Math.min(1.0,getConfig().getDouble(key,legacy)));
550
}
551
552
private void send(Player p, String key) {
553
p.sendMessage(legacyMessage(localizedMessage(p, key)));
554
}
555
556
private String localizedMessage(Player player, String key) {
557
String language = playerLanguage(player);
558
String value = getConfig().getString("messages." + language + "." + key, null);
559
if (value == null) value = getConfig().getString("messages.en." + key, null);
560
// Backwards compatibility with 1.2.4 and older configs.
561
if (value == null) value = getConfig().getString("messages." + key, "");
562
return value == null ? "" : value;
563
}
564
565
private String playerLanguage(Player player) {
566
try {
567
Object locale = player.getClass().getMethod("getLocale").invoke(player);
568
if (locale != null && locale.toString().toLowerCase(Locale.ROOT).startsWith("nl")) return "nl";
569
} catch (ReflectiveOperationException ignored) {
570
// Older or unusual implementations fall back to English.
571
}
572
return "en";
573
}
574
575
private String filterTitle(Player player, long id) {
576
String title = getConfig().getString("filter-title." + playerLanguage(player), null);
577
if (title == null) title = getConfig().getString("filter-title.en", "Pipe filter #{id}");
578
return legacyMessage(title.replace("{id}", Long.toString(id)));
579
}
580
581
private String commandText(CommandSender sender, String key) {
582
String language = sender instanceof Player player ? playerLanguage(player) : "en";
583
String value = getConfig().getString("commands." + language + "." + key, null);
584
if (value == null) value = getConfig().getString("commands.en." + key, key);
585
return legacyMessage(value == null ? key : value);
586
}
587
588
private String legacyMessage(String input){
589
if(input==null)return "";
590
return input.replace("<green>","§a").replace("</green>","")
591
.replace("<yellow>","§e").replace("</yellow>","")
592
.replace("<red>","§c").replace("</red>","")
593
.replace("<gray>","§7").replace("</gray>","")
594
.replace("<white>","§f").replace("</white>","")
595
.replace("<bold>","§l").replace("</bold>","§r")
596
.replace("<reset>","§r");
597
}
598
599
600
private boolean isPipeRouteBlock(Block block) {
601
ChunkKey chunk = ChunkKey.of(block);
602
if (!connectionsByChunk.containsKey(chunk)) return false;
603
return routeIndex.containsKey(WorldBlockPos.of(block));
604
}
605
606
private boolean isPipeRouteBlock(World world, BlockPos pos) {
607
ChunkKey chunk = new ChunkKey(world.getUID(), pos.x >> 4, pos.z >> 4);
608
if (!connectionsByChunk.containsKey(chunk)) return false;
609
return routeIndex.containsKey(new WorldBlockPos(world.getUID(), pos));
610
}
611
612
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
613
public void onPipeInteract(PlayerInteractAtEntityEvent event){
614
if (AdvancedEndpointsPatch.suppressPipeInteract(this, event)) return;
615
if(event.getHand()!=EquipmentSlot.HAND)return;
616
long id=connectionIdFrom(event.getRightClicked().getScoreboardTags());
617
if(id<0||!connections.containsKey(id))return;
618
Player player=event.getPlayer();
619
if(!player.hasPermission("containerpipes.use"))return;
620
event.setCancelled(true);
621
622
ItemStack held=player.getInventory().getItemInMainHand();
623
boolean shears=held!=null&&held.getType()==Material.SHEARS;
624
if(shears&&player.isSneaking()){
625
removeConnection(id,true);
626
send(player,"disconnected");
627
return;
628
}
629
630
// Direct pipe clicks always open the filter. With shears this applies
631
// only when the player is not sneaking; shift + shears cuts the pipe.
632
openFilter(player,id);
633
}
634
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}
635
private void openFilter(Player player,long id){
636
Connection c=connections.get(id);if(c==null)return;
637
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,filterTitle(player,id));holder.inventory=inv;
638
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}
639
openFilters.put(id,holder);player.openInventory(inv);
640
}
641
@EventHandler public void onFilterClick(InventoryClickEvent event){
642
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;
643
if(event.getRawSlot()<0)return;
644
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}
645
event.setCancelled(true);
646
ItemStack cursor=event.getCursor();
647
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);
648
else{ItemStack copy=cursor.clone();copy.setAmount(1);event.getInventory().setItem(event.getRawSlot(),copy);}
649
updateFilter(holder.connectionId,event.getInventory());
650
}
651
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}
652
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}
653
private void updateFilterOriginal(long id, Inventory inv) {
654
Connection old = connections.get(id);
655
if (old == null) return;
656
ArrayList<ItemStack> f = new ArrayList<>(5);
657
for (int i = 0; i < 5; i++) {
658
ItemStack x = inv.getItem(i);
659
if (x != null) {
660
x = x.clone();
661
x.setAmount(1);
662
if (!destinationCanEverAccept(old, x)) {
663
x = null;
664
inv.setItem(i, null);
665
}
666
}
667
f.add(x);
668
}
669
Connection replacement = new Connection(old.id, old.source, old.destination, old.path, Collections.unmodifiableList(f));
670
unregisterConnection(old);
671
registerConnection(replacement);
672
saveConnections();
673
spawnDisplays(replacement);
674
}
675
private void updateFilter(long id, Inventory inv) {
676
TransferPolicyPatch.sanitizeFilterAndUpdate(this, id, inv);
677
}
678
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}
679
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}
680
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}
681
682
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
683
if(!sender.hasPermission("containerpipes.admin"))return true;
684
String sub=args.length==0?"status":args[0].toLowerCase(Locale.ROOT);
685
switch(sub){
686
case "status" -> sender.sendMessage(commandText(sender, "status")
687
.replace("{connections}", Integer.toString(connections.size()))
688
.replace("{segments}", Integer.toString(displayIds.values().stream().mapToInt(List::size).sum())));
689
case "reload" -> {
690
reloadConfig();
691
startTasks();
692
refreshLoadedDisplays();
693
sender.sendMessage(commandText(sender, "reloaded"));
694
}
695
case "refresh" -> {
696
cleanupTaggedDisplays();
697
displayIds.clear();
698
refreshLoadedDisplays();
699
sender.sendMessage(commandText(sender, "refreshed"));
700
}
701
default -> sender.sendMessage(commandText(sender, "usage"));
702
} return true;
703
}
704
705
private record WorldBlockPos(UUID world, BlockPos pos) {
706
static WorldBlockPos of(Block block) { return new WorldBlockPos(block.getWorld().getUID(), BlockPos.of(block)); }
707
}
708
private record ChunkKey(UUID world, int x, int z) {
709
static ChunkKey of(Block block) { return new ChunkKey(block.getWorld().getUID(), block.getX() >> 4, block.getZ() >> 4); }
710
static ChunkKey of(Chunk chunk) { return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ()); }
711
}
712
private record Selection(Endpoint endpoint,long createdAt){}
713
private record DisplayPoint(Location location, int type){}
714
private record BlockPos(int x,int y,int z){
715
static BlockPos of(Block b){return new BlockPos(b.getX(),b.getY(),b.getZ());}
716
List<BlockPos> neighbors(){return List.of(new BlockPos(x+1,y,z),new BlockPos(x-1,y,z),new BlockPos(x,y+1,z),new BlockPos(x,y-1,z),new BlockPos(x,y,z+1),new BlockPos(x,y,z-1));}
717
int manhattan(BlockPos o){return Math.abs(x-o.x)+Math.abs(y-o.y)+Math.abs(z-o.z);}
718
String encode(){return x+","+y+","+z;} static BlockPos decode(String s){String[]p=s.split(",");return new BlockPos(Integer.parseInt(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]));}
719
}
720
private record Endpoint(UUID world,int x,int y,int z,BlockFace face){
721
BlockPos outside(){return new BlockPos(x+face.getModX(),y+face.getModY(),z+face.getModZ());}
722
boolean isBlock(Block b){return b.getWorld().getUID().equals(world)&&b.getX()==x&&b.getY()==y&&b.getZ()==z;}
723
double distanceSquared(Endpoint o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return dx*dx+dy*dy+dz*dz;}
724
Location faceCenter(World w){return new Location(w,x+0.5+face.getModX()*0.51,y+0.5+face.getModY()*0.51,z+0.5+face.getModZ()*0.51);}
725
Location attachmentCenter(World w,float scale){double offset=0.5+(scale/2.0);return new Location(w,x+0.5+face.getModX()*offset,y+0.5+face.getModY()*offset,z+0.5+face.getModZ()*offset);}
726
String encode(){return world+","+x+","+y+","+z+","+face.name();}
727
static Endpoint decode(String s){String[]p=s.split(",");return new Endpoint(UUID.fromString(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]),Integer.parseInt(p[3]),BlockFace.valueOf(p[4]));}
728
}
729
private record Connection(long id,Endpoint source,Endpoint destination,List<BlockPos> path,List<ItemStack> filter){
730
boolean hasFilter(){return filter.stream().anyMatch(i->i!=null&&!i.getType().isAir());}
731
String serialize(){return id+"\t"+source.encode()+"\t"+destination.encode()+"\t"+path.stream().map(BlockPos::encode).reduce((a,b)->a+";"+b).orElse("")+"\t"+encodeFilter(filter);}
732
static Connection parse(String line){String[]p=line.split("\\t",5);List<BlockPos>path=p.length<4||p[3].isBlank()?List.of():Arrays.stream(p[3].split(";")).map(BlockPos::decode).toList();List<ItemStack> filter=p.length<5?List.of():decodeFilter(p[4]);return new Connection(Long.parseLong(p[0]),Endpoint.decode(p[1]),Endpoint.decode(p[2]),path,filter);}
733
Set<ChunkKey> chunkKeys() {
734
Set<ChunkKey> keys = new HashSet<>();
735
keys.add(new ChunkKey(source.world, source.x >> 4, source.z >> 4));
736
keys.add(new ChunkKey(destination.world, destination.x >> 4, destination.z >> 4));
737
for (BlockPos p : path) keys.add(new ChunkKey(source.world, p.x >> 4, p.z >> 4));
738
return keys;
739
}
740
boolean touchesChunk(Chunk c){if(!c.getWorld().getUID().equals(source.world))return false;int cx=c.getX(),cz=c.getZ();if((source.x>>4)==cx&&(source.z>>4)==cz)return true;if((destination.x>>4)==cx&&(destination.z>>4)==cz)return true;for(BlockPos p:path)if((p.x>>4)==cx&&(p.z>>4)==cz)return true;return false;}
741
}
742
}
@@ -0,0 +1,742 @@1
package nl.timfalken.containerpipes;2
3
import org.bukkit.*;4
import org.bukkit.block.*;5
import org.bukkit.command.*;6
import org.bukkit.configuration.file.FileConfiguration;7
import org.bukkit.entity.BlockDisplay;8
import org.bukkit.entity.Interaction;9
import org.bukkit.entity.Player;10
import org.bukkit.event.*;11
import org.bukkit.event.block.*;12
import org.bukkit.event.player.PlayerInteractEvent;13
import org.bukkit.event.player.PlayerInteractAtEntityEvent;14
import org.bukkit.event.entity.EntityChangeBlockEvent;15
import org.bukkit.event.inventory.InventoryClickEvent;16
import org.bukkit.event.inventory.InventoryDragEvent;17
import org.bukkit.event.inventory.InventoryCloseEvent;18
import org.bukkit.event.world.*;19
import org.bukkit.inventory.*;20
import org.bukkit.event.inventory.InventoryType;21
import org.bukkit.inventory.EquipmentSlot;22
import org.bukkit.plugin.java.JavaPlugin;23
import org.bukkit.scheduler.BukkitTask;24
import org.bukkit.util.Transformation;25
import org.joml.AxisAngle4f;26
import org.joml.Vector3f;27
28
import java.io.*;29
import java.nio.charset.StandardCharsets;30
import java.nio.file.Files;31
import java.util.*;32
import java.util.concurrent.atomic.AtomicLong;33
import java.util.Base64;34
35
public final class ContainerPipesPlugin extends JavaPlugin implements Listener, CommandExecutor {36
private final Map<Long, Connection> connections = new LinkedHashMap<>();37
// O(1) indices: no Bukkit Block or Chunk objects are retained.38
private final Map<Endpoint, Long> endpointIndex = new HashMap<>();39
private final Map<WorldBlockPos, Long> routeIndex = new HashMap<>();40
private final Map<ChunkKey, Set<Long>> connectionsByChunk = new HashMap<>();41
private final Map<UUID, Selection> selections = new HashMap<>();42
private final Map<Long, List<UUID>> displayIds = new HashMap<>();43
private final Map<UUID, Long> lastInteractions = new HashMap<>();44
private final AtomicLong nextId = new AtomicLong(1);45
private final Map<Long, FilterHolder> openFilters = new HashMap<>();46
private File dataFile;47
private boolean connectionFileWritable = true;48
private BukkitTask transferTask;49
private BukkitTask validationTask;50
51
@Override public void onEnable() {52
saveDefaultConfig();53
dataFile = new File(getDataFolder(), "connections.tsv");54
getServer().getPluginManager().registerEvents(this, this);55
Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);56
cleanupTaggedDisplays();57
loadConnections();58
startTasks();59
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);60
getLogger().info("ContainerPipes 1.7.0 enabled with " + connections.size() + " connection(s).");61
AdvancedEndpointsPatch.enable(this);62
}63
64
@Override public void onDisable() {65
if (transferTask != null) transferTask.cancel();66
if (validationTask != null) validationTask.cancel();67
saveConnectionsNow();68
removeAllDisplays();69
selections.clear();70
AdvancedEndpointsPatch.disable(this);71
}72
73
private void startTasks() {74
if (transferTask != null) transferTask.cancel();75
if (validationTask != null) validationTask.cancel();76
long transfer = Math.max(1, getConfig().getLong("transfer-interval-ticks", 10));77
long validate = Math.max(1, getConfig().getLong("validation-interval-ticks", 20));78
transferTask = Bukkit.getScheduler().runTaskTimer(this,79
() -> OptimizedTransferPlanner.tick(this), transfer, transfer);80
validationTask = Bukkit.getScheduler().runTaskTimer(this, this::validateConnections, validate, validate);81
}82
83
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)84
public void onInteract(PlayerInteractEvent event) {85
if (event.getHand() != EquipmentSlot.HAND) return;86
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isSneaking()) return;87
Player player = event.getPlayer();88
long now = System.currentTimeMillis();89
long debounceMillis = Math.max(0, getConfig().getLong("interaction-debounce-millis", 100));90
Long previous = lastInteractions.put(player.getUniqueId(), now);91
if (previous != null && now - previous < debounceMillis) return;92
Block block = event.getClickedBlock();93
BlockFace face = event.getBlockFace();94
if (block == null || !isAllowedContainer(block)) return;95
if (!player.hasPermission("containerpipes.use")) return;96
97
ItemStack held = event.getItem();98
boolean emptyHand = held == null || held.getType().isAir();99
boolean shears = held != null && held.getType() == Material.SHEARS;100
if (!emptyHand && !shears) return;101
event.setCancelled(true);102
103
if (shears) {104
Connection existing = findByEndpoint(endpoint(block, face));105
if (existing != null) {106
removeConnection(existing.id, true);107
send(player, "disconnected");108
} else {109
selections.remove(player.getUniqueId());110
send(player, "selection-cancelled");111
}112
return;113
}114
115
Endpoint clicked = endpoint(block, face);116
Selection selection = selections.remove(player.getUniqueId());117
if (selection == null) {118
Connection existing = findByEndpoint(clicked);119
if (existing != null) {120
openFilter(player, existing.id);121
return;122
}123
selections.put(player.getUniqueId(), new Selection(clicked, System.currentTimeMillis()));124
spawnSelectionParticles(player, clicked);125
send(player, "selected-source");126
return;127
}128
129
Endpoint source = selection.endpoint;130
if (!source.world.equals(clicked.world)) { send(player, "different-world"); return; }131
if (source.equals(clicked)) { send(player, "selection-cancelled"); return; }132
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "side-in-use"); return; }133
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));134
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "too-far"); return; }135
136
World world = Bukkit.getWorld(source.world);137
if (world == null) return;138
BlockPos start = source.outside();139
BlockPos goal = clicked.outside();140
Set<BlockPos> occupied = occupiedPipeBlocks(source.world);141
List<BlockPos> route = findRoute(world, start, goal, maxRange, occupied);142
if (route == null) { send(player, "no-route"); return; }143
144
long id = nextId.getAndIncrement();145
Connection c = new Connection(id, source, clicked, route, List.of());146
registerConnection(c);147
saveConnections();148
spawnDisplays(c);149
send(player, "connected");150
}151
152
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)153
public void onBlockPlace(BlockPlaceEvent event) {154
if (isPipeRouteBlock(event.getBlockPlaced())) event.setCancelled(true);155
}156
157
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)158
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {159
if (event.getReplacedBlockStates().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);160
}161
162
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)163
public void onBlockGrow(BlockGrowEvent event) { cancelIfPipe(event, event.getBlock()); }164
165
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)166
public void onBlockSpread(BlockSpreadEvent event) { cancelIfPipe(event, event.getBlock()); }167
168
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)169
public void onBlockForm(BlockFormEvent event) { cancelIfPipe(event, event.getBlock()); }170
171
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)172
public void onEntityBlockForm(EntityBlockFormEvent event) { cancelIfPipe(event, event.getBlock()); }173
174
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)175
public void onEntityChangeBlock(EntityChangeBlockEvent event) { cancelIfPipe(event, event.getBlock()); }176
177
// Liquids are intentionally allowed to flow through visual pipe routes.178
// Solid block creation/placement is still protected by the other handlers.179
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)180
public void onBlockFromTo(BlockFromToEvent event) { }181
182
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)183
public void onFluidLevelChange(FluidLevelChangeEvent event) { }184
185
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)186
public void onStructureGrow(StructureGrowEvent event) {187
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);188
}189
190
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)191
public void onBlockFertilize(BlockFertilizeEvent event) {192
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);193
}194
195
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)196
public void onPortalCreate(PortalCreateEvent event) {197
if (event.getBlocks().stream().map(BlockState::getBlock).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);198
}199
200
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)201
public void onPistonExtend(BlockPistonExtendEvent event) {202
BlockFace direction = event.getDirection();203
if (event.getBlocks().stream().map(block -> block.getRelative(direction)).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);204
}205
206
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)207
public void onPistonRetract(BlockPistonRetractEvent event) {208
BlockFace movement = event.getDirection().getOppositeFace();209
if (event.getBlocks().stream().map(block -> block.getRelative(movement)).anyMatch(this::isPipeRouteBlock)) event.setCancelled(true);210
}211
212
private void cancelIfPipe(Cancellable event, Block target) {213
if (isPipeRouteBlock(target)) event.setCancelled(true);214
}215
@EventHandler(ignoreCancelled = true)216
public void onBlockBreak(BlockBreakEvent event) {217
Block block = event.getBlock();218
Set<Long> affected = new HashSet<>();219
for (BlockFace face : BlockFace.values()) {220
Long id = endpointIndex.get(endpoint(block, face));221
if (id != null) affected.add(id);222
}223
for (long id : affected) removeConnection(id, false);224
if (!affected.isEmpty()) saveConnections();225
}226
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {227
Bukkit.getScheduler().runTask(this, () -> refreshChunk(event.getChunk()));228
}229
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) { removeDisplaysInChunk(event.getChunk()); }230
231
private void validateConnections() {232
for (Connection c : List.copyOf(connections.values())) {233
World world = Bukkit.getWorld(c.source.world);234
if (world == null) continue;235
if (!isEndpointContainer(c.source) || !isEndpointContainer(c.destination)) { removeConnection(c.id, true); continue; }236
237
}238
}239
240
private boolean isEndpointContainer(Endpoint e) {241
World w = Bukkit.getWorld(e.world);242
return w != null && (!w.isChunkLoaded(e.x >> 4, e.z >> 4) || isAllowedContainer(w.getBlockAt(e.x,e.y,e.z)));243
}244
245
private boolean destinationCanEverAccept(Connection connection, ItemStack item) {246
World world = Bukkit.getWorld(connection.destination.world);247
if (world == null || !world.isChunkLoaded(connection.destination.x >> 4, connection.destination.z >> 4)) return true;248
Inventory destination = inventoryOf(world.getBlockAt(connection.destination.x, connection.destination.y, connection.destination.z));249
if (destination == null) return false;250
if (destination instanceof FurnaceInventory furnace) return furnace.canSmelt(item) || furnace.isFuel(item);251
return true;252
}253
254
private Inventory inventoryOf(Block block) {255
BlockState state = block.getState();256
if (state instanceof Chest chest) return chest.getInventory();257
if (state instanceof Container container) return container.getInventory();258
return null;259
}260
261
private boolean isAllowedContainer(Block block) {262
if (AdvancedEndpointsPatch.isExtendedContainer(block)) return true;263
String n = block.getType().name();264
if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;265
return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;266
}267
268
private Endpoint endpoint(Block b, BlockFace face) { return new Endpoint(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ(), face); }269
private Connection findByEndpoint(Endpoint e) {270
Long id = endpointIndex.get(e);271
return id == null ? null : connections.get(id);272
}273
274
private List<BlockPos> findRoute(World world, BlockPos start, BlockPos goal, int range, Set<BlockPos> occupied) {275
if (!isRouteSpace(world.getBlockAt(start.x,start.y,start.z), true) || !isRouteSpace(world.getBlockAt(goal.x,goal.y,goal.z), true)) return null;276
record Node(BlockPos pos, int g, int f) {}277
PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingInt(Node::f));278
Map<BlockPos,Integer> g = new HashMap<>();279
Map<BlockPos,BlockPos> prev = new HashMap<>();280
open.add(new Node(start,0,start.manhattan(goal))); g.put(start,0);281
int visited=0, limit=Math.max(4096, range*range*range*4);282
while(!open.isEmpty() && visited++<limit) {283
Node n=open.poll(); if(n.g()!=g.getOrDefault(n.pos(),Integer.MAX_VALUE)) continue;284
if(n.pos().equals(goal)) return reconstruct(prev, goal);285
for(BlockPos q:n.pos().neighbors()) {286
if(q.y<world.getMinHeight() || q.y>=world.getMaxHeight()) continue;287
if(Math.abs(q.x-start.x)>range || Math.abs(q.y-start.y)>range || Math.abs(q.z-start.z)>range) continue;288
if(!q.equals(goal) && occupied.contains(q)) continue;289
if(!isRouteSpace(world.getBlockAt(q.x,q.y,q.z), q.equals(goal))) continue;290
int ng=n.g()+1;291
if(ng<g.getOrDefault(q,Integer.MAX_VALUE)) { g.put(q,ng); prev.put(q,n.pos()); open.add(new Node(q,ng,ng+q.manhattan(goal))); }292
}293
}294
return null;295
}296
private static List<BlockPos> reconstruct(Map<BlockPos,BlockPos> prev, BlockPos goal) { ArrayList<BlockPos> out=new ArrayList<>(); for(BlockPos p=goal;p!=null;p=prev.get(p))out.add(p); Collections.reverse(out); return out; }297
private boolean isRouteSpace(Block block, boolean endpointOutside) {298
return block.getType().isAir() || block.isLiquid();299
}300
private Set<BlockPos> occupiedPipeBlocks(UUID world) {301
Set<BlockPos> occupied = new HashSet<>();302
for (WorldBlockPos p : routeIndex.keySet()) if (p.world.equals(world)) occupied.add(p.pos());303
return occupied;304
}305
306
private void spawnDisplays(Connection c) {307
removeDisplays(c.id);308
World world=Bukkit.getWorld(c.source.world); if(world==null)return;309
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));310
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;311
final Material pipeMaterial = material;312
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));313
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;314
final Material filteredSourceMaterial=filteredMaterial;315
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));316
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));317
float sourceEndpointScale=endpointScale("source-endpoint-scale");318
float destinationEndpointScale=endpointScale("destination-endpoint-scale");319
List<UUID> ids=new ArrayList<>();320
List<DisplayPoint> points=polylinePoints(c, spacing);321
for(DisplayPoint point:points) {322
Location loc = point.location();323
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;324
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;325
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{326
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());327
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));328
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);329
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);330
});331
ids.add(d.getUniqueId());332
Interaction hit=world.spawn(loc, Interaction.class, interaction->{333
interaction.setInteractionWidth(Math.max(0.28f, pointScale));334
interaction.setInteractionHeight(Math.max(0.28f, pointScale));335
interaction.setResponsive(true);336
interaction.setPersistent(false);337
interaction.addScoreboardTag("containerpipes");338
interaction.addScoreboardTag("containerpipes-filter:"+c.id);339
});340
ids.add(hit.getUniqueId());341
}342
displayIds.put(c.id,ids);343
}344
345
private List<DisplayPoint> polylinePoints(Connection c,double spacing) {346
World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();347
float sourceEndpointScale=endpointScale("source-endpoint-scale");348
float destinationEndpointScale=endpointScale("destination-endpoint-scale");349
ArrayList<Location> centers=new ArrayList<>();350
Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);351
for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));352
centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));353
ArrayList<Location> raw=new ArrayList<>();354
for(int i=0;i<centers.size()-1;i++) {355
Location a=centers.get(i),b=centers.get(i+1); double dist=a.distance(b); int steps=Math.max(1,(int)Math.ceil(dist/spacing));356
for(int j=(i==0?0:1);j<=steps;j++) { double t=(double)j/steps; raw.add(new Location(w,a.getX()+(b.getX()-a.getX())*t,a.getY()+(b.getY()-a.getY())*t,a.getZ()+(b.getZ()-a.getZ())*t)); }357
}358
ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());359
for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));360
return out;361
}362
363
private void spawnSelectionParticles(Player p, Endpoint e) {364
World w=Bukkit.getWorld(e.world); if(w==null)return; Location l=e.faceCenter(w);365
int count=Math.max(1,getConfig().getInt("selection-particle-count",12));366
w.spawnParticle(Particle.HAPPY_VILLAGER,l,count,0.18,0.18,0.18,0);367
}368
private void refreshSelectionParticles() {369
for (Map.Entry<UUID, Selection> entry : selections.entrySet()) {370
Player player = Bukkit.getPlayer(entry.getKey());371
if (player != null && player.isOnline()) spawnSelectionParticles(player, entry.getValue().endpoint);372
}373
}374
375
private void animateTransfer(Connection c) {376
World world = Bukkit.getWorld(c.source.world);377
if (world == null) return;378
List<DisplayPoint> displayPoints = polylinePoints(c, Math.max(0.1, getConfig().getDouble("transfer-particle-spacing", 0.25)));379
if (displayPoints.isEmpty()) return;380
int stepTicks = Math.max(1, getConfig().getInt("transfer-particle-step-ticks", 1));381
int pointsPerStep = Math.max(1, getConfig().getInt("transfer-particle-points-per-step", 2));382
BukkitTask[] task = new BukkitTask[1];383
int[] index = {0};384
task[0] = Bukkit.getScheduler().runTaskTimer(this, () -> {385
if (index[0] >= displayPoints.size()) {386
task[0].cancel();387
return;388
}389
for (int i = 0; i < pointsPerStep && index[0] < displayPoints.size(); i++, index[0]++) {390
Location location = displayPoints.get(index[0]).location();391
if (world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {392
world.spawnParticle(Particle.END_ROD, location, 1, 0, 0, 0, 0);393
}394
}395
}, 0L, stepTicks);396
}397
private void expireSelections(){long max=Math.max(1,getConfig().getLong("selection-timeout-seconds",30))*1000; long now=System.currentTimeMillis(); selections.entrySet().removeIf(e->now-e.getValue().createdAt>max);}398
399
private void refreshLoadedDisplays(){for(Connection c:connections.values())spawnDisplays(c);}400
private void refreshChunk(Chunk chunk) {401
for (long id : connectionIdsInChunk(chunk)) {402
Connection c = connections.get(id);403
if (c != null) spawnMissingDisplaysInChunk(c, chunk);404
}405
}406
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}407
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}408
private void removeDisplaysInChunk(Chunk chunk){409
Set<UUID> removed=new HashSet<>();410
for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}411
if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);412
}413
private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {414
World world=Bukkit.getWorld(c.source.world); if(world==null)return;415
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));416
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;417
final Material pipeMaterial=material;418
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));419
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;420
final Material filteredSourceMaterial=filteredMaterial;421
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));422
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));423
float sourceEndpointScale=endpointScale("source-endpoint-scale");424
float destinationEndpointScale=endpointScale("destination-endpoint-scale");425
List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());426
for(DisplayPoint point:polylinePoints(c,spacing)) {427
Location loc=point.location();428
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;429
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;430
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{431
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());432
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));433
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);434
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);435
});436
ids.add(d.getUniqueId());437
Interaction hit=world.spawn(loc,Interaction.class,interaction->{438
interaction.setInteractionWidth(Math.max(0.28f,pointScale));439
interaction.setInteractionHeight(Math.max(0.28f,pointScale));440
interaction.setResponsive(true);interaction.setPersistent(false);441
interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);442
});443
ids.add(hit.getUniqueId());444
}445
}446
private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}447
448
private void removeConnection(long id, boolean save) {449
Connection removed = connections.get(id);450
if (removed != null) unregisterConnection(removed);451
removeDisplays(id);452
if (save) saveConnections();453
}454
455
private void clearConnectionIndices() {456
connections.clear();457
endpointIndex.clear();458
routeIndex.clear();459
connectionsByChunk.clear();460
}461
462
private void registerConnection(Connection c) {463
connections.put(c.id, c);464
endpointIndex.put(c.source, c.id);465
endpointIndex.put(c.destination, c.id);466
UUID world = c.source.world;467
for (BlockPos p : c.path) routeIndex.put(new WorldBlockPos(world, p), c.id);468
for (ChunkKey key : c.chunkKeys()) connectionsByChunk.computeIfAbsent(key, ignored -> new HashSet<>()).add(c.id);469
AdvancedEndpointsPatch.connectionChanged(this, c, true);470
}471
472
private void unregisterConnection(Connection c) {473
connections.remove(c.id);474
endpointIndex.remove(c.source, c.id);475
endpointIndex.remove(c.destination, c.id);476
UUID world = c.source.world;477
for (BlockPos p : c.path) routeIndex.remove(new WorldBlockPos(world, p), c.id);478
for (ChunkKey key : c.chunkKeys()) {479
Set<Long> ids = connectionsByChunk.get(key);480
if (ids == null) continue;481
ids.remove(c.id);482
if (ids.isEmpty()) connectionsByChunk.remove(key);483
}484
AdvancedEndpointsPatch.connectionChanged(this, c, false);485
}486
487
private Set<Long> connectionIdsInChunk(Chunk chunk) {488
Set<Long> ids = connectionsByChunk.get(ChunkKey.of(chunk));489
return ids == null ? Set.of() : Set.copyOf(ids);490
}491
492
private void saveConnections(){ PersistenceDebouncer.request(this); }493
494
private void saveConnectionsNow(){495
if (!connectionFileWritable) {496
getLogger().warning("connections.tsv staat in herstelmodus en wordt niet overschreven. Herstel eerst de gemelde ongeldige regels.");497
return;498
}499
try {500
getDataFolder().mkdirs();501
java.nio.file.Path target=dataFile.toPath();502
java.nio.file.Path temporary=target.resolveSibling(target.getFileName()+".tmp");503
java.nio.file.Path backup=target.resolveSibling(target.getFileName()+".bak");504
StringBuilder s=new StringBuilder("# ContainerPipes 1.2.5\n");505
for(Connection c:connections.values())s.append(c.serialize()).append('\n');506
Files.writeString(temporary,s.toString(),StandardCharsets.UTF_8);507
if(Files.exists(target))Files.copy(target,backup,java.nio.file.StandardCopyOption.REPLACE_EXISTING);508
try {509
Files.move(temporary,target,java.nio.file.StandardCopyOption.REPLACE_EXISTING,java.nio.file.StandardCopyOption.ATOMIC_MOVE);510
} catch(java.nio.file.AtomicMoveNotSupportedException ignored) {511
Files.move(temporary,target,java.nio.file.StandardCopyOption.REPLACE_EXISTING);512
}513
} catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingen niet opslaan",e);}514
}515
private void loadConnections(){516
clearConnectionIndices();517
nextId.set(1);518
connectionFileWritable=true;519
if(!dataFile.exists())return;520
int loaded=0;521
int skipped=0;522
try {523
List<String> lines=Files.readAllLines(dataFile.toPath(),StandardCharsets.UTF_8);524
for(int i=0;i<lines.size();i++) {525
String line=lines.get(i).trim();526
if(line.isEmpty()||line.startsWith("#"))continue;527
try {528
Connection c=Connection.parse(line);529
registerConnection(c);530
nextId.set(Math.max(nextId.get(),c.id+1));531
loaded++;532
} catch(Exception entryError) {533
skipped++;534
getLogger().warning("Ongeldige verbinding overgeslagen op regel "+(i+1)+": "+entryError.getMessage());535
}536
}537
if(skipped>0) {538
connectionFileWritable=false;539
getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen. Bestand blijft ongewijzigd (herstelmodus).");540
}541
} catch(Exception e) {542
connectionFileWritable=false;543
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen; bestand blijft ongewijzigd",e);544
}545
}546
547
private float endpointScale(String key) {548
double legacy=getConfig().getDouble("endpoint-scale",0.40);549
return (float)Math.max(0.05,Math.min(1.0,getConfig().getDouble(key,legacy)));550
}551
552
private void send(Player p, String key) {553
p.sendMessage(legacyMessage(localizedMessage(p, key)));554
}555
556
private String localizedMessage(Player player, String key) {557
String language = playerLanguage(player);558
String value = getConfig().getString("messages." + language + "." + key, null);559
if (value == null) value = getConfig().getString("messages.en." + key, null);560
// Backwards compatibility with 1.2.4 and older configs.561
if (value == null) value = getConfig().getString("messages." + key, "");562
return value == null ? "" : value;563
}564
565
private String playerLanguage(Player player) {566
try {567
Object locale = player.getClass().getMethod("getLocale").invoke(player);568
if (locale != null && locale.toString().toLowerCase(Locale.ROOT).startsWith("nl")) return "nl";569
} catch (ReflectiveOperationException ignored) {570
// Older or unusual implementations fall back to English.571
}572
return "en";573
}574
575
private String filterTitle(Player player, long id) {576
String title = getConfig().getString("filter-title." + playerLanguage(player), null);577
if (title == null) title = getConfig().getString("filter-title.en", "Pipe filter #{id}");578
return legacyMessage(title.replace("{id}", Long.toString(id)));579
}580
581
private String commandText(CommandSender sender, String key) {582
String language = sender instanceof Player player ? playerLanguage(player) : "en";583
String value = getConfig().getString("commands." + language + "." + key, null);584
if (value == null) value = getConfig().getString("commands.en." + key, key);585
return legacyMessage(value == null ? key : value);586
}587
588
private String legacyMessage(String input){589
if(input==null)return "";590
return input.replace("<green>","§a").replace("</green>","")591
.replace("<yellow>","§e").replace("</yellow>","")592
.replace("<red>","§c").replace("</red>","")593
.replace("<gray>","§7").replace("</gray>","")594
.replace("<white>","§f").replace("</white>","")595
.replace("<bold>","§l").replace("</bold>","§r")596
.replace("<reset>","§r");597
}598
599
600
private boolean isPipeRouteBlock(Block block) {601
ChunkKey chunk = ChunkKey.of(block);602
if (!connectionsByChunk.containsKey(chunk)) return false;603
return routeIndex.containsKey(WorldBlockPos.of(block));604
}605
606
private boolean isPipeRouteBlock(World world, BlockPos pos) {607
ChunkKey chunk = new ChunkKey(world.getUID(), pos.x >> 4, pos.z >> 4);608
if (!connectionsByChunk.containsKey(chunk)) return false;609
return routeIndex.containsKey(new WorldBlockPos(world.getUID(), pos));610
}611
612
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)613
public void onPipeInteract(PlayerInteractAtEntityEvent event){614
if (AdvancedEndpointsPatch.suppressPipeInteract(this, event)) return;615
if(event.getHand()!=EquipmentSlot.HAND)return;616
long id=connectionIdFrom(event.getRightClicked().getScoreboardTags());617
if(id<0||!connections.containsKey(id))return;618
Player player=event.getPlayer();619
if(!player.hasPermission("containerpipes.use"))return;620
event.setCancelled(true);621
622
ItemStack held=player.getInventory().getItemInMainHand();623
boolean shears=held!=null&&held.getType()==Material.SHEARS;624
if(shears&&player.isSneaking()){625
removeConnection(id,true);626
send(player,"disconnected");627
return;628
}629
630
// Direct pipe clicks always open the filter. With shears this applies631
// only when the player is not sneaking; shift + shears cuts the pipe.632
openFilter(player,id);633
}634
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}635
private void openFilter(Player player,long id){636
Connection c=connections.get(id);if(c==null)return;637
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,filterTitle(player,id));holder.inventory=inv;638
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}639
openFilters.put(id,holder);player.openInventory(inv);640
}641
@EventHandler public void onFilterClick(InventoryClickEvent event){642
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;643
if(event.getRawSlot()<0)return;644
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}645
event.setCancelled(true);646
ItemStack cursor=event.getCursor();647
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);648
else{ItemStack copy=cursor.clone();copy.setAmount(1);event.getInventory().setItem(event.getRawSlot(),copy);}649
updateFilter(holder.connectionId,event.getInventory());650
}651
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}652
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}653
private void updateFilterOriginal(long id, Inventory inv) {654
Connection old = connections.get(id);655
if (old == null) return;656
ArrayList<ItemStack> f = new ArrayList<>(5);657
for (int i = 0; i < 5; i++) {658
ItemStack x = inv.getItem(i);659
if (x != null) {660
x = x.clone();661
x.setAmount(1);662
if (!destinationCanEverAccept(old, x)) {663
x = null;664
inv.setItem(i, null);665
}666
}667
f.add(x);668
}669
Connection replacement = new Connection(old.id, old.source, old.destination, old.path, Collections.unmodifiableList(f));670
unregisterConnection(old);671
registerConnection(replacement);672
saveConnections();673
spawnDisplays(replacement);674
}675
private void updateFilter(long id, Inventory inv) {676
TransferPolicyPatch.sanitizeFilterAndUpdate(this, id, inv);677
}678
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}679
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}680
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}681
682
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {683
if(!sender.hasPermission("containerpipes.admin"))return true;684
String sub=args.length==0?"status":args[0].toLowerCase(Locale.ROOT);685
switch(sub){686
case "status" -> sender.sendMessage(commandText(sender, "status")687
.replace("{connections}", Integer.toString(connections.size()))688
.replace("{segments}", Integer.toString(displayIds.values().stream().mapToInt(List::size).sum())));689
case "reload" -> {690
reloadConfig();691
startTasks();692
refreshLoadedDisplays();693
sender.sendMessage(commandText(sender, "reloaded"));694
}695
case "refresh" -> {696
cleanupTaggedDisplays();697
displayIds.clear();698
refreshLoadedDisplays();699
sender.sendMessage(commandText(sender, "refreshed"));700
}701
default -> sender.sendMessage(commandText(sender, "usage"));702
} return true;703
}704
705
private record WorldBlockPos(UUID world, BlockPos pos) {706
static WorldBlockPos of(Block block) { return new WorldBlockPos(block.getWorld().getUID(), BlockPos.of(block)); }707
}708
private record ChunkKey(UUID world, int x, int z) {709
static ChunkKey of(Block block) { return new ChunkKey(block.getWorld().getUID(), block.getX() >> 4, block.getZ() >> 4); }710
static ChunkKey of(Chunk chunk) { return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ()); }711
}712
private record Selection(Endpoint endpoint,long createdAt){}713
private record DisplayPoint(Location location, int type){}714
private record BlockPos(int x,int y,int z){715
static BlockPos of(Block b){return new BlockPos(b.getX(),b.getY(),b.getZ());}716
List<BlockPos> neighbors(){return List.of(new BlockPos(x+1,y,z),new BlockPos(x-1,y,z),new BlockPos(x,y+1,z),new BlockPos(x,y-1,z),new BlockPos(x,y,z+1),new BlockPos(x,y,z-1));}717
int manhattan(BlockPos o){return Math.abs(x-o.x)+Math.abs(y-o.y)+Math.abs(z-o.z);}718
String encode(){return x+","+y+","+z;} static BlockPos decode(String s){String[]p=s.split(",");return new BlockPos(Integer.parseInt(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]));}719
}720
private record Endpoint(UUID world,int x,int y,int z,BlockFace face){721
BlockPos outside(){return new BlockPos(x+face.getModX(),y+face.getModY(),z+face.getModZ());}722
boolean isBlock(Block b){return b.getWorld().getUID().equals(world)&&b.getX()==x&&b.getY()==y&&b.getZ()==z;}723
double distanceSquared(Endpoint o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return dx*dx+dy*dy+dz*dz;}724
Location faceCenter(World w){return new Location(w,x+0.5+face.getModX()*0.51,y+0.5+face.getModY()*0.51,z+0.5+face.getModZ()*0.51);}725
Location attachmentCenter(World w,float scale){double offset=0.5+(scale/2.0);return new Location(w,x+0.5+face.getModX()*offset,y+0.5+face.getModY()*offset,z+0.5+face.getModZ()*offset);}726
String encode(){return world+","+x+","+y+","+z+","+face.name();}727
static Endpoint decode(String s){String[]p=s.split(",");return new Endpoint(UUID.fromString(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]),Integer.parseInt(p[3]),BlockFace.valueOf(p[4]));}728
}729
private record Connection(long id,Endpoint source,Endpoint destination,List<BlockPos> path,List<ItemStack> filter){730
boolean hasFilter(){return filter.stream().anyMatch(i->i!=null&&!i.getType().isAir());}731
String serialize(){return id+"\t"+source.encode()+"\t"+destination.encode()+"\t"+path.stream().map(BlockPos::encode).reduce((a,b)->a+";"+b).orElse("")+"\t"+encodeFilter(filter);}732
static Connection parse(String line){String[]p=line.split("\\t",5);List<BlockPos>path=p.length<4||p[3].isBlank()?List.of():Arrays.stream(p[3].split(";")).map(BlockPos::decode).toList();List<ItemStack> filter=p.length<5?List.of():decodeFilter(p[4]);return new Connection(Long.parseLong(p[0]),Endpoint.decode(p[1]),Endpoint.decode(p[2]),path,filter);}733
Set<ChunkKey> chunkKeys() {734
Set<ChunkKey> keys = new HashSet<>();735
keys.add(new ChunkKey(source.world, source.x >> 4, source.z >> 4));736
keys.add(new ChunkKey(destination.world, destination.x >> 4, destination.z >> 4));737
for (BlockPos p : path) keys.add(new ChunkKey(source.world, p.x >> 4, p.z >> 4));738
return keys;739
}740
boolean touchesChunk(Chunk c){if(!c.getWorld().getUID().equals(source.world))return false;int cx=c.getX(),cz=c.getZ();if((source.x>>4)==cx&&(source.z>>4)==cz)return true;if((destination.x>>4)==cx&&(destination.z>>4)==cz)return true;for(BlockPos p:path)if((p.x>>4)==cx&&(p.z>>4)==cz)return true;return false;}741
}742
}@@ -0,0 +1,537 @@
1
package nl.timfalken.containerpipes;
2
3
import org.bukkit.*;
4
import org.bukkit.block.*;
5
import org.bukkit.command.*;
6
import org.bukkit.configuration.file.FileConfiguration;
7
import org.bukkit.entity.BlockDisplay;
8
import org.bukkit.entity.Interaction;
9
import org.bukkit.entity.Player;
10
import org.bukkit.event.*;
11
import org.bukkit.event.block.*;
12
import org.bukkit.event.player.PlayerInteractEvent;
13
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
14
import org.bukkit.event.inventory.InventoryClickEvent;
15
import org.bukkit.event.inventory.InventoryDragEvent;
16
import org.bukkit.event.inventory.InventoryCloseEvent;
17
import org.bukkit.event.world.*;
18
import org.bukkit.inventory.*;
19
import org.bukkit.event.inventory.InventoryType;
20
import org.bukkit.inventory.EquipmentSlot;
21
import org.bukkit.plugin.java.JavaPlugin;
22
import org.bukkit.scheduler.BukkitTask;
23
import org.bukkit.util.Transformation;
24
import org.joml.AxisAngle4f;
25
import org.joml.Vector3f;
26
27
import java.io.*;
28
import java.nio.charset.StandardCharsets;
29
import java.nio.file.Files;
30
import java.util.*;
31
import java.util.concurrent.atomic.AtomicLong;
32
import java.util.Base64;
33
34
public final class ContainerPipesPlugin extends JavaPlugin implements Listener, CommandExecutor {
35
private final Map<Long, Connection> connections = new LinkedHashMap<>();
36
private final Map<UUID, Selection> selections = new HashMap<>();
37
private final Map<Long, List<UUID>> displayIds = new HashMap<>();
38
private final Map<UUID, Long> lastInteractions = new HashMap<>();
39
private final AtomicLong nextId = new AtomicLong(1);
40
private final Map<Long, FilterHolder> openFilters = new HashMap<>();
41
private File dataFile;
42
private BukkitTask transferTask;
43
private BukkitTask validationTask;
44
45
@Override public void onEnable() {
46
saveDefaultConfig();
47
dataFile = new File(getDataFolder(), "connections.tsv");
48
getServer().getPluginManager().registerEvents(this, this);
49
Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);
50
cleanupTaggedDisplays();
51
loadConnections();
52
startTasks();
53
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
54
getLogger().info("ContainerPipes 1.1.0 actief met " + connections.size() + " verbinding(en).");
55
}
56
57
@Override public void onDisable() {
58
if (transferTask != null) transferTask.cancel();
59
if (validationTask != null) validationTask.cancel();
60
saveConnections();
61
removeAllDisplays();
62
selections.clear();
63
}
64
65
private void startTasks() {
66
if (transferTask != null) transferTask.cancel();
67
if (validationTask != null) validationTask.cancel();
68
long transfer = Math.max(1, getConfig().getLong("transfer-interval-ticks", 10));
69
long validate = Math.max(1, getConfig().getLong("validation-interval-ticks", 20));
70
transferTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
71
for (Connection c : List.copyOf(connections.values())) transferOne(c);
72
refreshSelectionParticles();
73
expireSelections();
74
}, transfer, transfer);
75
validationTask = Bukkit.getScheduler().runTaskTimer(this, this::validateConnections, validate, validate);
76
}
77
78
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
79
public void onInteract(PlayerInteractEvent event) {
80
if (event.getHand() != EquipmentSlot.HAND) return;
81
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isSneaking()) return;
82
Player player = event.getPlayer();
83
long now = System.currentTimeMillis();
84
long debounceMillis = Math.max(0, getConfig().getLong("interaction-debounce-millis", 100));
85
Long previous = lastInteractions.put(player.getUniqueId(), now);
86
if (previous != null && now - previous < debounceMillis) return;
87
Block block = event.getClickedBlock();
88
BlockFace face = event.getBlockFace();
89
if (block == null || !isAllowedContainer(block)) return;
90
if (!player.hasPermission("containerpipes.use")) return;
91
92
ItemStack held = event.getItem();
93
boolean emptyHand = held == null || held.getType().isAir();
94
boolean shears = held != null && held.getType() == Material.SHEARS;
95
if (!emptyHand && !shears) return;
96
event.setCancelled(true);
97
98
if (shears) {
99
Connection existing = findByEndpoint(endpoint(block, face));
100
if (existing != null) {
101
removeConnection(existing.id, true);
102
send(player, "messages.disconnected");
103
} else {
104
selections.remove(player.getUniqueId());
105
send(player, "messages.selection-cancelled");
106
}
107
return;
108
}
109
110
Endpoint clicked = endpoint(block, face);
111
Selection selection = selections.remove(player.getUniqueId());
112
if (selection == null) {
113
if (findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; }
114
selections.put(player.getUniqueId(), new Selection(clicked, System.currentTimeMillis()));
115
spawnSelectionParticles(player, clicked);
116
send(player, "messages.selected-source");
117
return;
118
}
119
120
Endpoint source = selection.endpoint;
121
if (!source.world.equals(clicked.world)) { send(player, "messages.different-world"); return; }
122
if (source.equals(clicked)) { send(player, "messages.selection-cancelled"); return; }
123
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; }
124
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));
125
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "messages.too-far"); return; }
126
127
World world = Bukkit.getWorld(source.world);
128
if (world == null) return;
129
BlockPos start = source.outside();
130
BlockPos goal = clicked.outside();
131
Set<BlockPos> occupied = occupiedPipeBlocks();
132
List<BlockPos> route = findRoute(world, start, goal, maxRange, occupied);
133
if (route == null) { send(player, "messages.no-route"); return; }
134
135
long id = nextId.getAndIncrement();
136
Connection c = new Connection(id, source, clicked, route, List.of());
137
connections.put(id, c);
138
saveConnections();
139
spawnDisplays(c);
140
send(player, "messages.connected");
141
}
142
143
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
144
public void onBlockPlace(BlockPlaceEvent event) {
145
if (isPipeRouteBlock(BlockPos.of(event.getBlockPlaced()))) {
146
event.setCancelled(true);
147
send(event.getPlayer(), "messages.pipe-blocked");
148
}
149
}
150
@EventHandler(ignoreCancelled = true)
151
public void onBlockBreak(BlockBreakEvent event) {
152
Block b = event.getBlock();
153
for (Connection c : List.copyOf(connections.values())) {
154
if (c.source.isBlock(b) || c.destination.isBlock(b)) removeConnection(c.id, true);
155
}
156
}
157
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
158
Bukkit.getScheduler().runTask(this, () -> refreshChunk(event.getChunk()));
159
}
160
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) { removeDisplaysInChunk(event.getChunk()); }
161
162
private void validateConnections() {
163
for (Connection c : List.copyOf(connections.values())) {
164
World world = Bukkit.getWorld(c.source.world);
165
if (world == null) continue;
166
if (!isEndpointContainer(c.source) || !isEndpointContainer(c.destination)) { removeConnection(c.id, true); continue; }
167
168
}
169
}
170
171
private boolean isEndpointContainer(Endpoint e) {
172
World w = Bukkit.getWorld(e.world);
173
return w != null && (!w.isChunkLoaded(e.x >> 4, e.z >> 4) || isAllowedContainer(w.getBlockAt(e.x,e.y,e.z)));
174
}
175
176
private void transferOne(Connection c) {
177
World world = Bukkit.getWorld(c.source.world);
178
if (world == null || !world.isChunkLoaded(c.source.x >> 4, c.source.z >> 4) || !world.isChunkLoaded(c.destination.x >> 4, c.destination.z >> 4)) return;
179
Block sourceBlock = world.getBlockAt(c.source.x,c.source.y,c.source.z);
180
Block destBlock = world.getBlockAt(c.destination.x,c.destination.y,c.destination.z);
181
Inventory source = inventoryOf(sourceBlock);
182
Inventory dest = inventoryOf(destBlock);
183
if (source == null || dest == null) return;
184
185
if (source instanceof FurnaceInventory furnace) {
186
ItemStack out = furnace.getResult();
187
if (out != null && !out.getType().isAir() && matchesFilter(c, one(out)) && tryInsert(dest, one(out))) {
188
decrementFurnaceResult(furnace);
189
animateTransfer(c);
190
}
191
return;
192
}
193
194
ItemStack[] contents = source.getStorageContents();
195
for (int slot = 0; slot < contents.length; slot++) {
196
ItemStack stack = contents[slot];
197
if (stack == null || stack.getType().isAir() || stack.getAmount() <= 0) continue;
198
ItemStack single = one(stack);
199
if (!matchesFilter(c, single)) continue;
200
if (tryInsert(dest, single)) {
201
decrement(source, slot, stack);
202
animateTransfer(c);
203
return;
204
}
205
}
206
}
207
208
private boolean tryInsert(Inventory dest, ItemStack single) {
209
if (dest instanceof FurnaceInventory furnace) {
210
boolean smelt = furnace.canSmelt(single);
211
boolean fuel = furnace.isFuel(single);
212
if (smelt && canMerge(furnace.getSmelting(), single, dest.getMaxStackSize())) { furnace.setSmelting(merged(furnace.getSmelting(), single)); return true; }
213
if (fuel && canMerge(furnace.getFuel(), single, dest.getMaxStackSize())) { furnace.setFuel(merged(furnace.getFuel(), single)); return true; }
214
return false;
215
}
216
ItemStack[] storage = dest.getStorageContents();
217
for (int i=0;i<storage.length;i++) {
218
ItemStack existing = storage[i];
219
if (existing != null && existing.isSimilar(single) && existing.getAmount() < Math.min(existing.getMaxStackSize(), dest.getMaxStackSize())) {
220
existing.setAmount(existing.getAmount()+1); dest.setItem(i, existing); return true;
221
}
222
}
223
for (int i=0;i<storage.length;i++) if (storage[i] == null || storage[i].getType().isAir()) { dest.setItem(i, single); return true; }
224
return false;
225
}
226
227
private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {
228
return existing == null || existing.getType().isAir() || (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));
229
}
230
private static ItemStack merged(ItemStack existing, ItemStack add) {
231
if (existing == null || existing.getType().isAir()) return add.clone();
232
ItemStack result = existing.clone(); result.setAmount(existing.getAmount()+1); return result;
233
}
234
private static ItemStack one(ItemStack source) { ItemStack x=source.clone(); x.setAmount(1); return x; }
235
private static void decrement(Inventory inv, int slot, ItemStack stack) { if (stack.getAmount() <= 1) inv.setItem(slot, null); else { stack.setAmount(stack.getAmount()-1); inv.setItem(slot, stack); } }
236
private static void decrementFurnaceResult(FurnaceInventory inv) { ItemStack s=inv.getResult(); if(s==null)return; if(s.getAmount()<=1)inv.setResult(null); else {s.setAmount(s.getAmount()-1);inv.setResult(s);} }
237
238
private Inventory inventoryOf(Block block) {
239
BlockState state = block.getState();
240
if (state instanceof Chest chest) return chest.getInventory();
241
if (state instanceof Container container) return container.getInventory();
242
return null;
243
}
244
245
private boolean isAllowedContainer(Block block) {
246
String n = block.getType().name();
247
if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;
248
return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;
249
}
250
251
private Endpoint endpoint(Block b, BlockFace face) { return new Endpoint(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ(), face); }
252
private Connection findByEndpoint(Endpoint e) { for(Connection c:connections.values()) if(c.source.equals(e)||c.destination.equals(e)) return c; return null; }
253
254
private List<BlockPos> findRoute(World world, BlockPos start, BlockPos goal, int range, Set<BlockPos> occupied) {
255
if (!isRouteSpace(world.getBlockAt(start.x,start.y,start.z), true) || !isRouteSpace(world.getBlockAt(goal.x,goal.y,goal.z), true)) return null;
256
record Node(BlockPos pos, int g, int f) {}
257
PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingInt(Node::f));
258
Map<BlockPos,Integer> g = new HashMap<>();
259
Map<BlockPos,BlockPos> prev = new HashMap<>();
260
open.add(new Node(start,0,start.manhattan(goal))); g.put(start,0);
261
int visited=0, limit=Math.max(4096, range*range*range*4);
262
while(!open.isEmpty() && visited++<limit) {
263
Node n=open.poll(); if(n.g()!=g.getOrDefault(n.pos(),Integer.MAX_VALUE)) continue;
264
if(n.pos().equals(goal)) return reconstruct(prev, goal);
265
for(BlockPos q:n.pos().neighbors()) {
266
if(q.y<world.getMinHeight() || q.y>=world.getMaxHeight()) continue;
267
if(Math.abs(q.x-start.x)>range || Math.abs(q.y-start.y)>range || Math.abs(q.z-start.z)>range) continue;
268
if(!q.equals(goal) && occupied.contains(q)) continue;
269
if(!isRouteSpace(world.getBlockAt(q.x,q.y,q.z), q.equals(goal))) continue;
270
int ng=n.g()+1;
271
if(ng<g.getOrDefault(q,Integer.MAX_VALUE)) { g.put(q,ng); prev.put(q,n.pos()); open.add(new Node(q,ng,ng+q.manhattan(goal))); }
272
}
273
}
274
return null;
275
}
276
private static List<BlockPos> reconstruct(Map<BlockPos,BlockPos> prev, BlockPos goal) { ArrayList<BlockPos> out=new ArrayList<>(); for(BlockPos p=goal;p!=null;p=prev.get(p))out.add(p); Collections.reverse(out); return out; }
277
private boolean isRouteSpace(Block block, boolean endpointOutside) { return block.getType().isAir(); }
278
private Set<BlockPos> occupiedPipeBlocks() { Set<BlockPos>s=new HashSet<>(); for(Connection c:connections.values())s.addAll(c.path); return s; }
279
280
private void spawnDisplays(Connection c) {
281
removeDisplays(c.id);
282
World world=Bukkit.getWorld(c.source.world); if(world==null)return;
283
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
284
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
285
final Material pipeMaterial = material;
286
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
287
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
288
final Material filteredSourceMaterial=filteredMaterial;
289
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
290
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
291
float sourceEndpointScale=endpointScale("source-endpoint-scale");
292
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
293
List<UUID> ids=new ArrayList<>();
294
List<DisplayPoint> points=polylinePoints(c, spacing);
295
for(DisplayPoint point:points) {
296
Location loc = point.location();
297
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
298
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;
299
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{
300
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
301
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
302
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);
303
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);
304
});
305
ids.add(d.getUniqueId());
306
Interaction hit=world.spawn(loc, Interaction.class, interaction->{
307
interaction.setInteractionWidth(Math.max(0.28f, pointScale));
308
interaction.setInteractionHeight(Math.max(0.28f, pointScale));
309
interaction.setResponsive(true);
310
interaction.setPersistent(false);
311
interaction.addScoreboardTag("containerpipes");
312
interaction.addScoreboardTag("containerpipes-filter:"+c.id);
313
});
314
ids.add(hit.getUniqueId());
315
}
316
displayIds.put(c.id,ids);
317
}
318
319
private List<DisplayPoint> polylinePoints(Connection c,double spacing) {
320
World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();
321
float sourceEndpointScale=endpointScale("source-endpoint-scale");
322
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
323
ArrayList<Location> centers=new ArrayList<>();
324
Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);
325
for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));
326
centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));
327
ArrayList<Location> raw=new ArrayList<>();
328
for(int i=0;i<centers.size()-1;i++) {
329
Location a=centers.get(i),b=centers.get(i+1); double dist=a.distance(b); int steps=Math.max(1,(int)Math.ceil(dist/spacing));
330
for(int j=(i==0?0:1);j<=steps;j++) { double t=(double)j/steps; raw.add(new Location(w,a.getX()+(b.getX()-a.getX())*t,a.getY()+(b.getY()-a.getY())*t,a.getZ()+(b.getZ()-a.getZ())*t)); }
331
}
332
ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());
333
for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));
334
return out;
335
}
336
337
private void spawnSelectionParticles(Player p, Endpoint e) {
338
World w=Bukkit.getWorld(e.world); if(w==null)return; Location l=e.faceCenter(w);
339
int count=Math.max(1,getConfig().getInt("selection-particle-count",12));
340
w.spawnParticle(Particle.HAPPY_VILLAGER,l,count,0.18,0.18,0.18,0);
341
}
342
private void refreshSelectionParticles() {
343
for (Map.Entry<UUID, Selection> entry : selections.entrySet()) {
344
Player player = Bukkit.getPlayer(entry.getKey());
345
if (player != null && player.isOnline()) spawnSelectionParticles(player, entry.getValue().endpoint);
346
}
347
}
348
349
private void animateTransfer(Connection c) {
350
World world = Bukkit.getWorld(c.source.world);
351
if (world == null) return;
352
List<DisplayPoint> displayPoints = polylinePoints(c, Math.max(0.1, getConfig().getDouble("transfer-particle-spacing", 0.25)));
353
if (displayPoints.isEmpty()) return;
354
int stepTicks = Math.max(1, getConfig().getInt("transfer-particle-step-ticks", 1));
355
int pointsPerStep = Math.max(1, getConfig().getInt("transfer-particle-points-per-step", 2));
356
BukkitTask[] task = new BukkitTask[1];
357
int[] index = {0};
358
task[0] = Bukkit.getScheduler().runTaskTimer(this, () -> {
359
if (index[0] >= displayPoints.size()) {
360
task[0].cancel();
361
return;
362
}
363
for (int i = 0; i < pointsPerStep && index[0] < displayPoints.size(); i++, index[0]++) {
364
Location location = displayPoints.get(index[0]).location();
365
if (world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {
366
world.spawnParticle(Particle.END_ROD, location, 1, 0, 0, 0, 0);
367
}
368
}
369
}, 0L, stepTicks);
370
}
371
private void expireSelections(){long max=Math.max(1,getConfig().getLong("selection-timeout-seconds",30))*1000; long now=System.currentTimeMillis(); selections.entrySet().removeIf(e->now-e.getValue().createdAt>max);}
372
373
private void refreshLoadedDisplays(){for(Connection c:connections.values())spawnDisplays(c);}
374
private void refreshChunk(Chunk chunk){for(Connection c:connections.values())if(c.touchesChunk(chunk))spawnMissingDisplaysInChunk(c, chunk);}
375
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}
376
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}
377
private void removeDisplaysInChunk(Chunk chunk){
378
Set<UUID> removed=new HashSet<>();
379
for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}
380
if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);
381
}
382
private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {
383
World world=Bukkit.getWorld(c.source.world); if(world==null)return;
384
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
385
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
386
final Material pipeMaterial=material;
387
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
388
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
389
final Material filteredSourceMaterial=filteredMaterial;
390
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
391
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
392
float sourceEndpointScale=endpointScale("source-endpoint-scale");
393
float destinationEndpointScale=endpointScale("destination-endpoint-scale");
394
List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());
395
for(DisplayPoint point:polylinePoints(c,spacing)) {
396
Location loc=point.location();
397
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;
398
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
399
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{
400
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
401
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
402
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);
403
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);
404
});
405
ids.add(d.getUniqueId());
406
Interaction hit=world.spawn(loc,Interaction.class,interaction->{
407
interaction.setInteractionWidth(Math.max(0.28f,pointScale));
408
interaction.setInteractionHeight(Math.max(0.28f,pointScale));
409
interaction.setResponsive(true);interaction.setPersistent(false);
410
interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);
411
});
412
ids.add(hit.getUniqueId());
413
}
414
}
415
private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}
416
417
private void removeConnection(long id,boolean save){connections.remove(id);removeDisplays(id);if(save)saveConnections();}
418
419
private void saveConnections(){
420
try {getDataFolder().mkdirs(); StringBuilder s=new StringBuilder("# ContainerPipes 1.1.0\n"); for(Connection c:connections.values())s.append(c.serialize()).append('\n'); Files.writeString(dataFile.toPath(),s.toString(),StandardCharsets.UTF_8);} catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingen niet opslaan",e);}
421
}
422
private void loadConnections(){
423
connections.clear();
424
nextId.set(1);
425
if(!dataFile.exists())return;
426
int loaded=0;
427
int skipped=0;
428
try {
429
List<String> lines=Files.readAllLines(dataFile.toPath(),StandardCharsets.UTF_8);
430
for(int i=0;i<lines.size();i++) {
431
String line=lines.get(i).trim();
432
if(line.isEmpty()||line.startsWith("#"))continue;
433
try {
434
Connection c=Connection.parse(line);
435
connections.put(c.id,c);
436
nextId.set(Math.max(nextId.get(),c.id+1));
437
loaded++;
438
} catch(Exception entryError) {
439
skipped++;
440
getLogger().warning("Ongeldige verbinding overgeslagen op regel "+(i+1)+": "+entryError.getMessage());
441
}
442
}
443
if(skipped>0)getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen.");
444
} catch(Exception e) {
445
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen",e);
446
}
447
}
448
449
private float endpointScale(String key) {
450
double legacy=getConfig().getDouble("endpoint-scale",0.40);
451
return (float)Math.max(0.05,Math.min(1.0,getConfig().getDouble(key,legacy)));
452
}
453
454
private void send(Player p,String key){p.sendMessage(legacyMessage(getConfig().getString(key,"")));}
455
private String legacyMessage(String input){
456
if(input==null)return "";
457
return input.replace("<green>","§a").replace("</green>","")
458
.replace("<yellow>","§e").replace("</yellow>","")
459
.replace("<red>","§c").replace("</red>","")
460
.replace("<gray>","§7").replace("</gray>","")
461
.replace("<white>","§f").replace("</white>","")
462
.replace("<bold>","§l").replace("</bold>","§r")
463
.replace("<reset>","§r");
464
}
465
466
467
private boolean isPipeRouteBlock(BlockPos pos){for(Connection c:connections.values())if(c.path.contains(pos))return true;return false;}
468
private boolean matchesFilter(Connection c, ItemStack item){if(!c.hasFilter())return true;for(ItemStack f:c.filter)if(f!=null&&!f.getType().isAir()&&f.isSimilar(item))return true;return false;}
469
470
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
471
public void onPipeInteract(PlayerInteractAtEntityEvent event){
472
if(event.getHand()!=EquipmentSlot.HAND || !event.getPlayer().isSneaking())return;
473
ItemStack held=event.getPlayer().getInventory().getItemInMainHand();
474
if(held!=null&&!held.getType().isAir())return;
475
long id=connectionIdFrom(event.getRightClicked().getScoreboardTags());
476
if(id<0||!connections.containsKey(id))return;
477
event.setCancelled(true);openFilter(event.getPlayer(),id);
478
}
479
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}
480
private void openFilter(Player player,long id){
481
Connection c=connections.get(id);if(c==null)return;
482
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,"Buisfilter #"+id);holder.inventory=inv;
483
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}
484
openFilters.put(id,holder);player.openInventory(inv);
485
}
486
@EventHandler public void onFilterClick(InventoryClickEvent event){
487
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;
488
if(event.getRawSlot()<0)return;
489
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}
490
event.setCancelled(true);
491
ItemStack cursor=event.getCursor();
492
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);
493
else{ItemStack copy=cursor.clone();copy.setAmount(1);event.getInventory().setItem(event.getRawSlot(),copy);}
494
updateFilter(holder.connectionId,event.getInventory());
495
}
496
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}
497
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}
498
private void updateFilter(long id,Inventory inv){Connection old=connections.get(id);if(old==null)return;ArrayList<ItemStack> f=new ArrayList<>(5);for(int i=0;i<5;i++){ItemStack x=inv.getItem(i);if(x!=null){x=x.clone();x.setAmount(1);}f.add(x);}connections.put(id,new Connection(old.id,old.source,old.destination,old.path,Collections.unmodifiableList(f)));saveConnections();spawnDisplays(connections.get(id));}
499
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}
500
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}
501
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}
502
503
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
504
if(!sender.hasPermission("containerpipes.admin"))return true;
505
String sub=args.length==0?"status":args[0].toLowerCase(Locale.ROOT);
506
switch(sub){
507
case "status"->sender.sendMessage("ContainerPipes: "+connections.size()+" verbinding(en), "+displayIds.values().stream().mapToInt(List::size).sum()+" displaysegmenten.");
508
case "reload"->{reloadConfig();startTasks();refreshLoadedDisplays();sender.sendMessage("ContainerPipes herladen.");}
509
case "refresh"->{cleanupTaggedDisplays();displayIds.clear();refreshLoadedDisplays();sender.sendMessage("Alle geladen buizen vernieuwd.");}
510
default->sender.sendMessage("Gebruik: /containerpipes <status|reload|refresh>");
511
} return true;
512
}
513
514
private record Selection(Endpoint endpoint,long createdAt){}
515
private record DisplayPoint(Location location, int type){}
516
private record BlockPos(int x,int y,int z){
517
static BlockPos of(Block b){return new BlockPos(b.getX(),b.getY(),b.getZ());}
518
List<BlockPos> neighbors(){return List.of(new BlockPos(x+1,y,z),new BlockPos(x-1,y,z),new BlockPos(x,y+1,z),new BlockPos(x,y-1,z),new BlockPos(x,y,z+1),new BlockPos(x,y,z-1));}
519
int manhattan(BlockPos o){return Math.abs(x-o.x)+Math.abs(y-o.y)+Math.abs(z-o.z);}
520
String encode(){return x+","+y+","+z;} static BlockPos decode(String s){String[]p=s.split(",");return new BlockPos(Integer.parseInt(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]));}
521
}
522
private record Endpoint(UUID world,int x,int y,int z,BlockFace face){
523
BlockPos outside(){return new BlockPos(x+face.getModX(),y+face.getModY(),z+face.getModZ());}
524
boolean isBlock(Block b){return b.getWorld().getUID().equals(world)&&b.getX()==x&&b.getY()==y&&b.getZ()==z;}
525
double distanceSquared(Endpoint o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return dx*dx+dy*dy+dz*dz;}
526
Location faceCenter(World w){return new Location(w,x+0.5+face.getModX()*0.51,y+0.5+face.getModY()*0.51,z+0.5+face.getModZ()*0.51);}
527
Location attachmentCenter(World w,float scale){double offset=0.5+(scale/2.0);return new Location(w,x+0.5+face.getModX()*offset,y+0.5+face.getModY()*offset,z+0.5+face.getModZ()*offset);}
528
String encode(){return world+","+x+","+y+","+z+","+face.name();}
529
static Endpoint decode(String s){String[]p=s.split(",");return new Endpoint(UUID.fromString(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]),Integer.parseInt(p[3]),BlockFace.valueOf(p[4]));}
530
}
531
private record Connection(long id,Endpoint source,Endpoint destination,List<BlockPos> path,List<ItemStack> filter){
532
boolean hasFilter(){return filter.stream().anyMatch(i->i!=null&&!i.getType().isAir());}
533
String serialize(){return id+"\t"+source.encode()+"\t"+destination.encode()+"\t"+path.stream().map(BlockPos::encode).reduce((a,b)->a+";"+b).orElse("")+"\t"+encodeFilter(filter);}
534
static Connection parse(String line){String[]p=line.split("\\t",5);List<BlockPos>path=p.length<4||p[3].isBlank()?List.of():Arrays.stream(p[3].split(";")).map(BlockPos::decode).toList();List<ItemStack> filter=p.length<5?List.of():decodeFilter(p[4]);return new Connection(Long.parseLong(p[0]),Endpoint.decode(p[1]),Endpoint.decode(p[2]),path,filter);}
535
boolean touchesChunk(Chunk c){if(!c.getWorld().getUID().equals(source.world))return false;int cx=c.getX(),cz=c.getZ();if((source.x>>4)==cx&&(source.z>>4)==cz)return true;if((destination.x>>4)==cx&&(destination.z>>4)==cz)return true;for(BlockPos p:path)if((p.x>>4)==cx&&(p.z>>4)==cz)return true;return false;}
536
}
537
}
@@ -0,0 +1,537 @@1
package nl.timfalken.containerpipes;2
3
import org.bukkit.*;4
import org.bukkit.block.*;5
import org.bukkit.command.*;6
import org.bukkit.configuration.file.FileConfiguration;7
import org.bukkit.entity.BlockDisplay;8
import org.bukkit.entity.Interaction;9
import org.bukkit.entity.Player;10
import org.bukkit.event.*;11
import org.bukkit.event.block.*;12
import org.bukkit.event.player.PlayerInteractEvent;13
import org.bukkit.event.player.PlayerInteractAtEntityEvent;14
import org.bukkit.event.inventory.InventoryClickEvent;15
import org.bukkit.event.inventory.InventoryDragEvent;16
import org.bukkit.event.inventory.InventoryCloseEvent;17
import org.bukkit.event.world.*;18
import org.bukkit.inventory.*;19
import org.bukkit.event.inventory.InventoryType;20
import org.bukkit.inventory.EquipmentSlot;21
import org.bukkit.plugin.java.JavaPlugin;22
import org.bukkit.scheduler.BukkitTask;23
import org.bukkit.util.Transformation;24
import org.joml.AxisAngle4f;25
import org.joml.Vector3f;26
27
import java.io.*;28
import java.nio.charset.StandardCharsets;29
import java.nio.file.Files;30
import java.util.*;31
import java.util.concurrent.atomic.AtomicLong;32
import java.util.Base64;33
34
public final class ContainerPipesPlugin extends JavaPlugin implements Listener, CommandExecutor {35
private final Map<Long, Connection> connections = new LinkedHashMap<>();36
private final Map<UUID, Selection> selections = new HashMap<>();37
private final Map<Long, List<UUID>> displayIds = new HashMap<>();38
private final Map<UUID, Long> lastInteractions = new HashMap<>();39
private final AtomicLong nextId = new AtomicLong(1);40
private final Map<Long, FilterHolder> openFilters = new HashMap<>();41
private File dataFile;42
private BukkitTask transferTask;43
private BukkitTask validationTask;44
45
@Override public void onEnable() {46
saveDefaultConfig();47
dataFile = new File(getDataFolder(), "connections.tsv");48
getServer().getPluginManager().registerEvents(this, this);49
Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);50
cleanupTaggedDisplays();51
loadConnections();52
startTasks();53
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);54
getLogger().info("ContainerPipes 1.1.0 actief met " + connections.size() + " verbinding(en).");55
}56
57
@Override public void onDisable() {58
if (transferTask != null) transferTask.cancel();59
if (validationTask != null) validationTask.cancel();60
saveConnections();61
removeAllDisplays();62
selections.clear();63
}64
65
private void startTasks() {66
if (transferTask != null) transferTask.cancel();67
if (validationTask != null) validationTask.cancel();68
long transfer = Math.max(1, getConfig().getLong("transfer-interval-ticks", 10));69
long validate = Math.max(1, getConfig().getLong("validation-interval-ticks", 20));70
transferTask = Bukkit.getScheduler().runTaskTimer(this, () -> {71
for (Connection c : List.copyOf(connections.values())) transferOne(c);72
refreshSelectionParticles();73
expireSelections();74
}, transfer, transfer);75
validationTask = Bukkit.getScheduler().runTaskTimer(this, this::validateConnections, validate, validate);76
}77
78
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)79
public void onInteract(PlayerInteractEvent event) {80
if (event.getHand() != EquipmentSlot.HAND) return;81
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isSneaking()) return;82
Player player = event.getPlayer();83
long now = System.currentTimeMillis();84
long debounceMillis = Math.max(0, getConfig().getLong("interaction-debounce-millis", 100));85
Long previous = lastInteractions.put(player.getUniqueId(), now);86
if (previous != null && now - previous < debounceMillis) return;87
Block block = event.getClickedBlock();88
BlockFace face = event.getBlockFace();89
if (block == null || !isAllowedContainer(block)) return;90
if (!player.hasPermission("containerpipes.use")) return;91
92
ItemStack held = event.getItem();93
boolean emptyHand = held == null || held.getType().isAir();94
boolean shears = held != null && held.getType() == Material.SHEARS;95
if (!emptyHand && !shears) return;96
event.setCancelled(true);97
98
if (shears) {99
Connection existing = findByEndpoint(endpoint(block, face));100
if (existing != null) {101
removeConnection(existing.id, true);102
send(player, "messages.disconnected");103
} else {104
selections.remove(player.getUniqueId());105
send(player, "messages.selection-cancelled");106
}107
return;108
}109
110
Endpoint clicked = endpoint(block, face);111
Selection selection = selections.remove(player.getUniqueId());112
if (selection == null) {113
if (findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; }114
selections.put(player.getUniqueId(), new Selection(clicked, System.currentTimeMillis()));115
spawnSelectionParticles(player, clicked);116
send(player, "messages.selected-source");117
return;118
}119
120
Endpoint source = selection.endpoint;121
if (!source.world.equals(clicked.world)) { send(player, "messages.different-world"); return; }122
if (source.equals(clicked)) { send(player, "messages.selection-cancelled"); return; }123
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; }124
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));125
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "messages.too-far"); return; }126
127
World world = Bukkit.getWorld(source.world);128
if (world == null) return;129
BlockPos start = source.outside();130
BlockPos goal = clicked.outside();131
Set<BlockPos> occupied = occupiedPipeBlocks();132
List<BlockPos> route = findRoute(world, start, goal, maxRange, occupied);133
if (route == null) { send(player, "messages.no-route"); return; }134
135
long id = nextId.getAndIncrement();136
Connection c = new Connection(id, source, clicked, route, List.of());137
connections.put(id, c);138
saveConnections();139
spawnDisplays(c);140
send(player, "messages.connected");141
}142
143
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)144
public void onBlockPlace(BlockPlaceEvent event) {145
if (isPipeRouteBlock(BlockPos.of(event.getBlockPlaced()))) {146
event.setCancelled(true);147
send(event.getPlayer(), "messages.pipe-blocked");148
}149
}150
@EventHandler(ignoreCancelled = true)151
public void onBlockBreak(BlockBreakEvent event) {152
Block b = event.getBlock();153
for (Connection c : List.copyOf(connections.values())) {154
if (c.source.isBlock(b) || c.destination.isBlock(b)) removeConnection(c.id, true);155
}156
}157
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {158
Bukkit.getScheduler().runTask(this, () -> refreshChunk(event.getChunk()));159
}160
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) { removeDisplaysInChunk(event.getChunk()); }161
162
private void validateConnections() {163
for (Connection c : List.copyOf(connections.values())) {164
World world = Bukkit.getWorld(c.source.world);165
if (world == null) continue;166
if (!isEndpointContainer(c.source) || !isEndpointContainer(c.destination)) { removeConnection(c.id, true); continue; }167
168
}169
}170
171
private boolean isEndpointContainer(Endpoint e) {172
World w = Bukkit.getWorld(e.world);173
return w != null && (!w.isChunkLoaded(e.x >> 4, e.z >> 4) || isAllowedContainer(w.getBlockAt(e.x,e.y,e.z)));174
}175
176
private void transferOne(Connection c) {177
World world = Bukkit.getWorld(c.source.world);178
if (world == null || !world.isChunkLoaded(c.source.x >> 4, c.source.z >> 4) || !world.isChunkLoaded(c.destination.x >> 4, c.destination.z >> 4)) return;179
Block sourceBlock = world.getBlockAt(c.source.x,c.source.y,c.source.z);180
Block destBlock = world.getBlockAt(c.destination.x,c.destination.y,c.destination.z);181
Inventory source = inventoryOf(sourceBlock);182
Inventory dest = inventoryOf(destBlock);183
if (source == null || dest == null) return;184
185
if (source instanceof FurnaceInventory furnace) {186
ItemStack out = furnace.getResult();187
if (out != null && !out.getType().isAir() && matchesFilter(c, one(out)) && tryInsert(dest, one(out))) {188
decrementFurnaceResult(furnace);189
animateTransfer(c);190
}191
return;192
}193
194
ItemStack[] contents = source.getStorageContents();195
for (int slot = 0; slot < contents.length; slot++) {196
ItemStack stack = contents[slot];197
if (stack == null || stack.getType().isAir() || stack.getAmount() <= 0) continue;198
ItemStack single = one(stack);199
if (!matchesFilter(c, single)) continue;200
if (tryInsert(dest, single)) {201
decrement(source, slot, stack);202
animateTransfer(c);203
return;204
}205
}206
}207
208
private boolean tryInsert(Inventory dest, ItemStack single) {209
if (dest instanceof FurnaceInventory furnace) {210
boolean smelt = furnace.canSmelt(single);211
boolean fuel = furnace.isFuel(single);212
if (smelt && canMerge(furnace.getSmelting(), single, dest.getMaxStackSize())) { furnace.setSmelting(merged(furnace.getSmelting(), single)); return true; }213
if (fuel && canMerge(furnace.getFuel(), single, dest.getMaxStackSize())) { furnace.setFuel(merged(furnace.getFuel(), single)); return true; }214
return false;215
}216
ItemStack[] storage = dest.getStorageContents();217
for (int i=0;i<storage.length;i++) {218
ItemStack existing = storage[i];219
if (existing != null && existing.isSimilar(single) && existing.getAmount() < Math.min(existing.getMaxStackSize(), dest.getMaxStackSize())) {220
existing.setAmount(existing.getAmount()+1); dest.setItem(i, existing); return true;221
}222
}223
for (int i=0;i<storage.length;i++) if (storage[i] == null || storage[i].getType().isAir()) { dest.setItem(i, single); return true; }224
return false;225
}226
227
private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {228
return existing == null || existing.getType().isAir() || (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));229
}230
private static ItemStack merged(ItemStack existing, ItemStack add) {231
if (existing == null || existing.getType().isAir()) return add.clone();232
ItemStack result = existing.clone(); result.setAmount(existing.getAmount()+1); return result;233
}234
private static ItemStack one(ItemStack source) { ItemStack x=source.clone(); x.setAmount(1); return x; }235
private static void decrement(Inventory inv, int slot, ItemStack stack) { if (stack.getAmount() <= 1) inv.setItem(slot, null); else { stack.setAmount(stack.getAmount()-1); inv.setItem(slot, stack); } }236
private static void decrementFurnaceResult(FurnaceInventory inv) { ItemStack s=inv.getResult(); if(s==null)return; if(s.getAmount()<=1)inv.setResult(null); else {s.setAmount(s.getAmount()-1);inv.setResult(s);} }237
238
private Inventory inventoryOf(Block block) {239
BlockState state = block.getState();240
if (state instanceof Chest chest) return chest.getInventory();241
if (state instanceof Container container) return container.getInventory();242
return null;243
}244
245
private boolean isAllowedContainer(Block block) {246
String n = block.getType().name();247
if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true;248
return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container;249
}250
251
private Endpoint endpoint(Block b, BlockFace face) { return new Endpoint(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ(), face); }252
private Connection findByEndpoint(Endpoint e) { for(Connection c:connections.values()) if(c.source.equals(e)||c.destination.equals(e)) return c; return null; }253
254
private List<BlockPos> findRoute(World world, BlockPos start, BlockPos goal, int range, Set<BlockPos> occupied) {255
if (!isRouteSpace(world.getBlockAt(start.x,start.y,start.z), true) || !isRouteSpace(world.getBlockAt(goal.x,goal.y,goal.z), true)) return null;256
record Node(BlockPos pos, int g, int f) {}257
PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingInt(Node::f));258
Map<BlockPos,Integer> g = new HashMap<>();259
Map<BlockPos,BlockPos> prev = new HashMap<>();260
open.add(new Node(start,0,start.manhattan(goal))); g.put(start,0);261
int visited=0, limit=Math.max(4096, range*range*range*4);262
while(!open.isEmpty() && visited++<limit) {263
Node n=open.poll(); if(n.g()!=g.getOrDefault(n.pos(),Integer.MAX_VALUE)) continue;264
if(n.pos().equals(goal)) return reconstruct(prev, goal);265
for(BlockPos q:n.pos().neighbors()) {266
if(q.y<world.getMinHeight() || q.y>=world.getMaxHeight()) continue;267
if(Math.abs(q.x-start.x)>range || Math.abs(q.y-start.y)>range || Math.abs(q.z-start.z)>range) continue;268
if(!q.equals(goal) && occupied.contains(q)) continue;269
if(!isRouteSpace(world.getBlockAt(q.x,q.y,q.z), q.equals(goal))) continue;270
int ng=n.g()+1;271
if(ng<g.getOrDefault(q,Integer.MAX_VALUE)) { g.put(q,ng); prev.put(q,n.pos()); open.add(new Node(q,ng,ng+q.manhattan(goal))); }272
}273
}274
return null;275
}276
private static List<BlockPos> reconstruct(Map<BlockPos,BlockPos> prev, BlockPos goal) { ArrayList<BlockPos> out=new ArrayList<>(); for(BlockPos p=goal;p!=null;p=prev.get(p))out.add(p); Collections.reverse(out); return out; }277
private boolean isRouteSpace(Block block, boolean endpointOutside) { return block.getType().isAir(); }278
private Set<BlockPos> occupiedPipeBlocks() { Set<BlockPos>s=new HashSet<>(); for(Connection c:connections.values())s.addAll(c.path); return s; }279
280
private void spawnDisplays(Connection c) {281
removeDisplays(c.id);282
World world=Bukkit.getWorld(c.source.world); if(world==null)return;283
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));284
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;285
final Material pipeMaterial = material;286
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));287
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;288
final Material filteredSourceMaterial=filteredMaterial;289
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));290
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));291
float sourceEndpointScale=endpointScale("source-endpoint-scale");292
float destinationEndpointScale=endpointScale("destination-endpoint-scale");293
List<UUID> ids=new ArrayList<>();294
List<DisplayPoint> points=polylinePoints(c, spacing);295
for(DisplayPoint point:points) {296
Location loc = point.location();297
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;298
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;299
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{300
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());301
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));302
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);303
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);304
});305
ids.add(d.getUniqueId());306
Interaction hit=world.spawn(loc, Interaction.class, interaction->{307
interaction.setInteractionWidth(Math.max(0.28f, pointScale));308
interaction.setInteractionHeight(Math.max(0.28f, pointScale));309
interaction.setResponsive(true);310
interaction.setPersistent(false);311
interaction.addScoreboardTag("containerpipes");312
interaction.addScoreboardTag("containerpipes-filter:"+c.id);313
});314
ids.add(hit.getUniqueId());315
}316
displayIds.put(c.id,ids);317
}318
319
private List<DisplayPoint> polylinePoints(Connection c,double spacing) {320
World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();321
float sourceEndpointScale=endpointScale("source-endpoint-scale");322
float destinationEndpointScale=endpointScale("destination-endpoint-scale");323
ArrayList<Location> centers=new ArrayList<>();324
Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);325
for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));326
centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));327
ArrayList<Location> raw=new ArrayList<>();328
for(int i=0;i<centers.size()-1;i++) {329
Location a=centers.get(i),b=centers.get(i+1); double dist=a.distance(b); int steps=Math.max(1,(int)Math.ceil(dist/spacing));330
for(int j=(i==0?0:1);j<=steps;j++) { double t=(double)j/steps; raw.add(new Location(w,a.getX()+(b.getX()-a.getX())*t,a.getY()+(b.getY()-a.getY())*t,a.getZ()+(b.getZ()-a.getZ())*t)); }331
}332
ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());333
for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));334
return out;335
}336
337
private void spawnSelectionParticles(Player p, Endpoint e) {338
World w=Bukkit.getWorld(e.world); if(w==null)return; Location l=e.faceCenter(w);339
int count=Math.max(1,getConfig().getInt("selection-particle-count",12));340
w.spawnParticle(Particle.HAPPY_VILLAGER,l,count,0.18,0.18,0.18,0);341
}342
private void refreshSelectionParticles() {343
for (Map.Entry<UUID, Selection> entry : selections.entrySet()) {344
Player player = Bukkit.getPlayer(entry.getKey());345
if (player != null && player.isOnline()) spawnSelectionParticles(player, entry.getValue().endpoint);346
}347
}348
349
private void animateTransfer(Connection c) {350
World world = Bukkit.getWorld(c.source.world);351
if (world == null) return;352
List<DisplayPoint> displayPoints = polylinePoints(c, Math.max(0.1, getConfig().getDouble("transfer-particle-spacing", 0.25)));353
if (displayPoints.isEmpty()) return;354
int stepTicks = Math.max(1, getConfig().getInt("transfer-particle-step-ticks", 1));355
int pointsPerStep = Math.max(1, getConfig().getInt("transfer-particle-points-per-step", 2));356
BukkitTask[] task = new BukkitTask[1];357
int[] index = {0};358
task[0] = Bukkit.getScheduler().runTaskTimer(this, () -> {359
if (index[0] >= displayPoints.size()) {360
task[0].cancel();361
return;362
}363
for (int i = 0; i < pointsPerStep && index[0] < displayPoints.size(); i++, index[0]++) {364
Location location = displayPoints.get(index[0]).location();365
if (world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {366
world.spawnParticle(Particle.END_ROD, location, 1, 0, 0, 0, 0);367
}368
}369
}, 0L, stepTicks);370
}371
private void expireSelections(){long max=Math.max(1,getConfig().getLong("selection-timeout-seconds",30))*1000; long now=System.currentTimeMillis(); selections.entrySet().removeIf(e->now-e.getValue().createdAt>max);}372
373
private void refreshLoadedDisplays(){for(Connection c:connections.values())spawnDisplays(c);}374
private void refreshChunk(Chunk chunk){for(Connection c:connections.values())if(c.touchesChunk(chunk))spawnMissingDisplaysInChunk(c, chunk);}375
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}376
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}377
private void removeDisplaysInChunk(Chunk chunk){378
Set<UUID> removed=new HashSet<>();379
for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}380
if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);381
}382
private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {383
World world=Bukkit.getWorld(c.source.world); if(world==null)return;384
Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));385
if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;386
final Material pipeMaterial=material;387
Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));388
if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;389
final Material filteredSourceMaterial=filteredMaterial;390
double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));391
float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));392
float sourceEndpointScale=endpointScale("source-endpoint-scale");393
float destinationEndpointScale=endpointScale("destination-endpoint-scale");394
List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());395
for(DisplayPoint point:polylinePoints(c,spacing)) {396
Location loc=point.location();397
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;398
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;399
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{400
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());401
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));402
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);403
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);404
});405
ids.add(d.getUniqueId());406
Interaction hit=world.spawn(loc,Interaction.class,interaction->{407
interaction.setInteractionWidth(Math.max(0.28f,pointScale));408
interaction.setInteractionHeight(Math.max(0.28f,pointScale));409
interaction.setResponsive(true);interaction.setPersistent(false);410
interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);411
});412
ids.add(hit.getUniqueId());413
}414
}415
private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}416
417
private void removeConnection(long id,boolean save){connections.remove(id);removeDisplays(id);if(save)saveConnections();}418
419
private void saveConnections(){420
try {getDataFolder().mkdirs(); StringBuilder s=new StringBuilder("# ContainerPipes 1.1.0\n"); for(Connection c:connections.values())s.append(c.serialize()).append('\n'); Files.writeString(dataFile.toPath(),s.toString(),StandardCharsets.UTF_8);} catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingen niet opslaan",e);}421
}422
private void loadConnections(){423
connections.clear();424
nextId.set(1);425
if(!dataFile.exists())return;426
int loaded=0;427
int skipped=0;428
try {429
List<String> lines=Files.readAllLines(dataFile.toPath(),StandardCharsets.UTF_8);430
for(int i=0;i<lines.size();i++) {431
String line=lines.get(i).trim();432
if(line.isEmpty()||line.startsWith("#"))continue;433
try {434
Connection c=Connection.parse(line);435
connections.put(c.id,c);436
nextId.set(Math.max(nextId.get(),c.id+1));437
loaded++;438
} catch(Exception entryError) {439
skipped++;440
getLogger().warning("Ongeldige verbinding overgeslagen op regel "+(i+1)+": "+entryError.getMessage());441
}442
}443
if(skipped>0)getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen.");444
} catch(Exception e) {445
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen",e);446
}447
}448
449
private float endpointScale(String key) {450
double legacy=getConfig().getDouble("endpoint-scale",0.40);451
return (float)Math.max(0.05,Math.min(1.0,getConfig().getDouble(key,legacy)));452
}453
454
private void send(Player p,String key){p.sendMessage(legacyMessage(getConfig().getString(key,"")));}455
private String legacyMessage(String input){456
if(input==null)return "";457
return input.replace("<green>","§a").replace("</green>","")458
.replace("<yellow>","§e").replace("</yellow>","")459
.replace("<red>","§c").replace("</red>","")460
.replace("<gray>","§7").replace("</gray>","")461
.replace("<white>","§f").replace("</white>","")462
.replace("<bold>","§l").replace("</bold>","§r")463
.replace("<reset>","§r");464
}465
466
467
private boolean isPipeRouteBlock(BlockPos pos){for(Connection c:connections.values())if(c.path.contains(pos))return true;return false;}468
private boolean matchesFilter(Connection c, ItemStack item){if(!c.hasFilter())return true;for(ItemStack f:c.filter)if(f!=null&&!f.getType().isAir()&&f.isSimilar(item))return true;return false;}469
470
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)471
public void onPipeInteract(PlayerInteractAtEntityEvent event){472
if(event.getHand()!=EquipmentSlot.HAND || !event.getPlayer().isSneaking())return;473
ItemStack held=event.getPlayer().getInventory().getItemInMainHand();474
if(held!=null&&!held.getType().isAir())return;475
long id=connectionIdFrom(event.getRightClicked().getScoreboardTags());476
if(id<0||!connections.containsKey(id))return;477
event.setCancelled(true);openFilter(event.getPlayer(),id);478
}479
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}480
private void openFilter(Player player,long id){481
Connection c=connections.get(id);if(c==null)return;482
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,"Buisfilter #"+id);holder.inventory=inv;483
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}484
openFilters.put(id,holder);player.openInventory(inv);485
}486
@EventHandler public void onFilterClick(InventoryClickEvent event){487
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;488
if(event.getRawSlot()<0)return;489
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}490
event.setCancelled(true);491
ItemStack cursor=event.getCursor();492
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);493
else{ItemStack copy=cursor.clone();copy.setAmount(1);event.getInventory().setItem(event.getRawSlot(),copy);}494
updateFilter(holder.connectionId,event.getInventory());495
}496
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}497
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}498
private void updateFilter(long id,Inventory inv){Connection old=connections.get(id);if(old==null)return;ArrayList<ItemStack> f=new ArrayList<>(5);for(int i=0;i<5;i++){ItemStack x=inv.getItem(i);if(x!=null){x=x.clone();x.setAmount(1);}f.add(x);}connections.put(id,new Connection(old.id,old.source,old.destination,old.path,Collections.unmodifiableList(f)));saveConnections();spawnDisplays(connections.get(id));}499
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}500
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}501
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}502
503
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {504
if(!sender.hasPermission("containerpipes.admin"))return true;505
String sub=args.length==0?"status":args[0].toLowerCase(Locale.ROOT);506
switch(sub){507
case "status"->sender.sendMessage("ContainerPipes: "+connections.size()+" verbinding(en), "+displayIds.values().stream().mapToInt(List::size).sum()+" displaysegmenten.");508
case "reload"->{reloadConfig();startTasks();refreshLoadedDisplays();sender.sendMessage("ContainerPipes herladen.");}509
case "refresh"->{cleanupTaggedDisplays();displayIds.clear();refreshLoadedDisplays();sender.sendMessage("Alle geladen buizen vernieuwd.");}510
default->sender.sendMessage("Gebruik: /containerpipes <status|reload|refresh>");511
} return true;512
}513
514
private record Selection(Endpoint endpoint,long createdAt){}515
private record DisplayPoint(Location location, int type){}516
private record BlockPos(int x,int y,int z){517
static BlockPos of(Block b){return new BlockPos(b.getX(),b.getY(),b.getZ());}518
List<BlockPos> neighbors(){return List.of(new BlockPos(x+1,y,z),new BlockPos(x-1,y,z),new BlockPos(x,y+1,z),new BlockPos(x,y-1,z),new BlockPos(x,y,z+1),new BlockPos(x,y,z-1));}519
int manhattan(BlockPos o){return Math.abs(x-o.x)+Math.abs(y-o.y)+Math.abs(z-o.z);}520
String encode(){return x+","+y+","+z;} static BlockPos decode(String s){String[]p=s.split(",");return new BlockPos(Integer.parseInt(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]));}521
}522
private record Endpoint(UUID world,int x,int y,int z,BlockFace face){523
BlockPos outside(){return new BlockPos(x+face.getModX(),y+face.getModY(),z+face.getModZ());}524
boolean isBlock(Block b){return b.getWorld().getUID().equals(world)&&b.getX()==x&&b.getY()==y&&b.getZ()==z;}525
double distanceSquared(Endpoint o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return dx*dx+dy*dy+dz*dz;}526
Location faceCenter(World w){return new Location(w,x+0.5+face.getModX()*0.51,y+0.5+face.getModY()*0.51,z+0.5+face.getModZ()*0.51);}527
Location attachmentCenter(World w,float scale){double offset=0.5+(scale/2.0);return new Location(w,x+0.5+face.getModX()*offset,y+0.5+face.getModY()*offset,z+0.5+face.getModZ()*offset);}528
String encode(){return world+","+x+","+y+","+z+","+face.name();}529
static Endpoint decode(String s){String[]p=s.split(",");return new Endpoint(UUID.fromString(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]),Integer.parseInt(p[3]),BlockFace.valueOf(p[4]));}530
}531
private record Connection(long id,Endpoint source,Endpoint destination,List<BlockPos> path,List<ItemStack> filter){532
boolean hasFilter(){return filter.stream().anyMatch(i->i!=null&&!i.getType().isAir());}533
String serialize(){return id+"\t"+source.encode()+"\t"+destination.encode()+"\t"+path.stream().map(BlockPos::encode).reduce((a,b)->a+";"+b).orElse("")+"\t"+encodeFilter(filter);}534
static Connection parse(String line){String[]p=line.split("\\t",5);List<BlockPos>path=p.length<4||p[3].isBlank()?List.of():Arrays.stream(p[3].split(";")).map(BlockPos::decode).toList();List<ItemStack> filter=p.length<5?List.of():decodeFilter(p[4]);return new Connection(Long.parseLong(p[0]),Endpoint.decode(p[1]),Endpoint.decode(p[2]),path,filter);}535
boolean touchesChunk(Chunk c){if(!c.getWorld().getUID().equals(source.world))return false;int cx=c.getX(),cz=c.getZ();if((source.x>>4)==cx&&(source.z>>4)==cz)return true;if((destination.x>>4)==cx&&(destination.z>>4)==cz)return true;for(BlockPos p:path)if((p.x>>4)==cx&&(p.z>>4)==cz)return true;return false;}536
}537
}@@ -0,0 +1,955 @@
1
package nl.timfalken.containerpipes;
2
3
import org.bukkit.Bukkit;
4
import org.bukkit.Location;
5
import org.bukkit.Material;
6
import org.bukkit.World;
7
import org.bukkit.block.Block;
8
import org.bukkit.block.BlockState;
9
import org.bukkit.block.Chest;
10
import org.bukkit.block.Container;
11
import org.bukkit.block.DoubleChest;
12
import org.bukkit.configuration.file.FileConfiguration;
13
import org.bukkit.inventory.FurnaceInventory;
14
import org.bukkit.inventory.Inventory;
15
import org.bukkit.inventory.InventoryHolder;
16
import org.bukkit.inventory.ItemStack;
17
18
import java.lang.reflect.*;
19
import java.util.*;
20
import java.util.concurrent.ConcurrentHashMap;
21
22
/**
23
* Direct Paper-API transfer planner.
24
*
25
* Reflection is used only to read ContainerPipes' private immutable Connection
26
* records and to call the optional visual animation. World/block/inventory/item
27
* operations in the transfer hot path are ordinary Java calls.
28
*/
29
public final class OptimizedTransferPlanner {
30
private OptimizedTransferPlanner() {}
31
32
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
33
private static final Map<MethodKey, Method> METHODS = new ConcurrentHashMap<>();
34
private static final Map<FieldKey, Field> FIELDS = new ConcurrentHashMap<>();
35
36
public static void tick(Object plugin) {
37
try {
38
State state = STATES.computeIfAbsent(plugin, State::new);
39
state.tick();
40
state.callPlugin("refreshSelectionParticles");
41
state.callPlugin("expireSelections");
42
} catch (Throwable t) {
43
log(plugin, "Direct transfer planner failed", t);
44
}
45
}
46
47
public static void probeSleeping(Object plugin) {
48
try { STATES.computeIfAbsent(plugin, State::new).probeSleepingBatch(); }
49
catch (Throwable t) { log(plugin, "Sleeping transfer probe failed", t); }
50
}
51
52
/**
53
* Called when a Connection object is replaced without changing the total
54
* connection count (most notably when a pipe filter is edited). A normal
55
* count-based topology check cannot see that immediately, so force a
56
* synchronous rebuild of the cached source groups/filter reservations.
57
* Filter edits are rare and happen on the server thread, making a full
58
* rebuild here preferable to allowing stale routing state for up to the
59
* periodic fingerprint interval.
60
*/
61
public static void connectionChanged(Object plugin) {
62
try { STATES.computeIfAbsent(plugin, State::new).rebuild(true); }
63
catch (Throwable t) { log(plugin, "Connection topology refresh failed", t); }
64
}
65
66
private static final class State {
67
final Object plugin;
68
final Map<ContainerKey, Group> groups = new LinkedHashMap<>();
69
final Map<ContainerKey, Set<Group>> wakeIndex = new HashMap<>();
70
final LinkedHashSet<Group> active = new LinkedHashSet<>();
71
final LinkedHashMap<Group, Long> sleeping = new LinkedHashMap<>();
72
final IdentityHashMap<Object, Long> lastParticleTick = new IdentityHashMap<>();
73
74
long logicalTick;
75
int schedulerInterval = 3;
76
int idleAfter = 3;
77
int sleepProbe = 200;
78
int sleepBatchSize = 10;
79
int visualInterval = 20;
80
long nextVisualTick;
81
long nextSleepingBatchTick;
82
int lastConnectionCount = -1;
83
int lastIdentityFingerprint;
84
long nextTopologyFingerprintTick;
85
long nextConfigReloadTick;
86
final Map<ContainerKey, DestinationState> cycleDestinations = new HashMap<>();
87
88
State(Object plugin) {
89
this.plugin = plugin;
90
reloadConfig();
91
rebuild(true);
92
registerListeners();
93
}
94
95
void reloadConfig() {
96
FileConfiguration cfg = config();
97
schedulerInterval = Math.max(1, cfg.getInt("transfer-interval-ticks", 3));
98
idleAfter = Math.max(1, cfg.getInt("performance.idle-after-failed-attempts", 3));
99
sleepProbe = Math.max(schedulerInterval, cfg.getInt("performance.sleeping-probe-interval-ticks", 200));
100
sleepBatchSize = Math.max(1, cfg.getInt("performance.sleeping-probe-batch-size", 10));
101
visualInterval = Math.max(5, cfg.getInt("visuals.refresh-interval-ticks", 20));
102
}
103
104
FileConfiguration config() {
105
try { return (FileConfiguration) call(plugin, "getConfig"); }
106
catch (Throwable t) { throw new IllegalStateException(t); }
107
}
108
109
@SuppressWarnings("unchecked")
110
Map<Long, Object> rawConnections() {
111
try { return (Map<Long, Object>) field(plugin, "connections"); }
112
catch (Throwable t) { throw new IllegalStateException(t); }
113
}
114
115
void tick() {
116
logicalTick += schedulerInterval;
117
reloadConfigIfNeeded();
118
rebuild(false);
119
cycleDestinations.clear();
120
121
List<Group> cycle = new ArrayList<>(active);
122
123
// Freeze only the number of items that was available at the start of
124
// this transfer cycle. Incoming pipes may still update sourceCache
125
// transactionally during the cycle, but those newly received items
126
// receive no budget until the next cycle. Existing items in a
127
// through-container can therefore keep flowing while it also receives.
128
for (Group group : cycle) {
129
if (!active.contains(group) || groups.get(group.key) != group) continue;
130
group.prepareCycleBudget();
131
}
132
133
for (Group group : cycle) {
134
if (!active.contains(group) || groups.get(group.key) != group) continue;
135
136
RunResult result = group.run();
137
if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
138
// STALE_CACHE already rebuilt from the real inventory. Keep the
139
// group active so the corrected contents are retried next cycle.
140
group.failed = 0;
141
} else if (++group.failed >= idleAfter) {
142
Inventory source = inventoryAt(group.connections.get(0).source);
143
if (source != null && group.refreshRealInventoryIfChanged(source)) {
144
// A direct, non-event mutation introduced/rearranged items.
145
// Do not sleep on stale knowledge; retry on the normal cadence.
146
group.failed = 0;
147
} else {
148
active.remove(group);
149
sleeping.put(group, logicalTick + sleepProbe);
150
}
151
}
152
}
153
154
int sleepingBatchInterval = Math.max(1, config().getInt("performance.sleeping-probe-batch-interval-ticks", 5));
155
if (logicalTick >= nextSleepingBatchTick) {
156
probeSleepingBatch();
157
nextSleepingBatchTick = logicalTick + sleepingBatchInterval;
158
}
159
160
if (logicalTick >= nextVisualTick) {
161
try {
162
Class<?> visual = Class.forName("nl.timfalken.containerpipes.VisualPerformanceManager", false,
163
plugin.getClass().getClassLoader());
164
invokeStatic(visual, "tick", new Class<?>[]{Object.class}, plugin);
165
} catch (Throwable ignored) {}
166
nextVisualTick = logicalTick + visualInterval;
167
}
168
}
169
170
void reloadConfigIfNeeded() {
171
if (logicalTick < nextConfigReloadTick) return;
172
reloadConfig();
173
nextConfigReloadTick = logicalTick + 200;
174
}
175
176
void probeSleepingBatch() {
177
rebuild(false);
178
if (sleeping.isEmpty()) return;
179
int processed = 0;
180
List<Group> activate = new ArrayList<>();
181
List<Group> requeue = new ArrayList<>();
182
Iterator<Map.Entry<Group, Long>> it = sleeping.entrySet().iterator();
183
while (it.hasNext() && processed < sleepBatchSize) {
184
Map.Entry<Group, Long> entry = it.next();
185
if (entry.getValue() > logicalTick) continue;
186
Group group = entry.getKey();
187
it.remove();
188
processed++;
189
if (groups.get(group.key) != group) continue;
190
// A sleeping probe is the final safety net for direct inventory
191
// mutations by other plugins that do not emit Bukkit events. Always
192
// read the real inventory here instead of trusting an old clean cache.
193
group.cacheDirty = true;
194
group.prepareCycleBudget();
195
RunResult result = group.run();
196
if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
197
group.failed = 0;
198
activate.add(group);
199
} else {
200
requeue.add(group);
201
}
202
}
203
active.addAll(activate);
204
for (Group group : requeue) sleeping.put(group, logicalTick + sleepProbe);
205
}
206
207
void rebuild(boolean force) {
208
Map<Long, Object> raw = rawConnections();
209
int count = raw.size();
210
boolean dueFingerprint = logicalTick >= nextTopologyFingerprintTick;
211
if (!force && count == lastConnectionCount && !dueFingerprint) return;
212
213
int fingerprint = count;
214
for (Object connection : raw.values()) fingerprint = 31 * fingerprint + System.identityHashCode(connection);
215
nextTopologyFingerprintTick = logicalTick + 400;
216
if (!force && count == lastConnectionCount && fingerprint == lastIdentityFingerprint) return;
217
218
lastConnectionCount = count;
219
lastIdentityFingerprint = fingerprint;
220
221
Map<ContainerKey, Boolean> previousAwake = new HashMap<>();
222
for (Group group : groups.values()) previousAwake.put(group.key, active.contains(group));
223
224
groups.clear();
225
wakeIndex.clear();
226
active.clear();
227
sleeping.clear();
228
229
for (Object rawConnection : raw.values()) {
230
try {
231
ConnectionView connection = ConnectionView.read(rawConnection);
232
ContainerKey sourceKey = endpointKey(connection.source);
233
groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);
234
} catch (Throwable t) {
235
log(plugin, "Could not index a pipe connection", t);
236
}
237
}
238
239
for (Group group : groups.values()) {
240
group.rebuildCache();
241
wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);
242
for (ContainerKey destination : group.destinationKeys) {
243
wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);
244
}
245
// Rebuilds are infrequent and should never make a usable pipe wait for
246
// the emergency probe. Start rebuilt groups active.
247
active.add(group);
248
}
249
}
250
251
void wakeInventory(Inventory inventory) {
252
ContainerKey key = inventoryKey(inventory);
253
if (key != null) invalidateAndWakeKey(key);
254
}
255
256
void invalidateAndWakeKey(ContainerKey key) {
257
Set<Group> affected = wakeIndex.get(key);
258
if (affected == null) return;
259
for (Group group : affected) {
260
if (group.key.equals(key)) group.cacheDirty = true;
261
group.failed = 0;
262
sleeping.remove(group);
263
active.add(group);
264
}
265
}
266
267
void wakeKeyInternal(ContainerKey key) {
268
Set<Group> affected = wakeIndex.get(key);
269
if (affected == null) return;
270
for (Group group : affected) {
271
group.failed = 0;
272
sleeping.remove(group);
273
active.add(group);
274
}
275
}
276
277
void registerListeners() {
278
// Event registration is deliberately reflective: it is not a hot path and
279
// keeps this replacement class compatible with the already-built plugin.
280
try {
281
ClassLoader cl = plugin.getClass().getClassLoader();
282
Class<?> listenerClass = Class.forName("org.bukkit.event.Listener", false, cl);
283
Class<?> executorClass = Class.forName("org.bukkit.plugin.EventExecutor", false, cl);
284
Class<?> priorityClass = Class.forName("org.bukkit.event.EventPriority", false, cl);
285
Object monitor = Enum.valueOf((Class<Enum>) priorityClass.asSubclass(Enum.class), "MONITOR");
286
Object listener = Proxy.newProxyInstance(cl, new Class<?>[]{listenerClass}, (p, m, a) -> null);
287
Object executor = Proxy.newProxyInstance(cl, new Class<?>[]{executorClass}, (p, m, a) -> {
288
if ("execute".equals(m.getName()) && a != null && a.length == 2) onEvent(a[1]);
289
return null;
290
});
291
Object pm = call(call(plugin, "getServer"), "getPluginManager");
292
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, cl);
293
Method register = findMethod(pm.getClass(), "registerEvent",
294
new Class<?>[]{Class.class, listenerClass, priorityClass, executorClass, pluginClass, boolean.class});
295
String[] names = {
296
"org.bukkit.event.inventory.InventoryOpenEvent",
297
"org.bukkit.event.inventory.InventoryClickEvent",
298
"org.bukkit.event.inventory.InventoryDragEvent",
299
"org.bukkit.event.inventory.InventoryCloseEvent",
300
"org.bukkit.event.inventory.InventoryMoveItemEvent",
301
"org.bukkit.event.inventory.InventoryPickupItemEvent",
302
"org.bukkit.event.inventory.FurnaceSmeltEvent",
303
"org.bukkit.event.inventory.FurnaceExtractEvent",
304
"org.bukkit.event.inventory.FurnaceBurnEvent",
305
"org.bukkit.event.block.BlockCookEvent",
306
"org.bukkit.event.world.ChunkLoadEvent",
307
"org.bukkit.event.world.ChunkUnloadEvent"
308
};
309
for (String name : names) {
310
try { register.invoke(pm, Class.forName(name, false, cl), listener, monitor, executor, plugin, true); }
311
catch (Throwable ignored) {}
312
}
313
} catch (Throwable t) {
314
log(plugin, "Could not register transfer wake listeners", t);
315
}
316
}
317
318
void onEvent(Object event) {
319
try {
320
String name = event.getClass().getName();
321
if (name.endsWith("InventoryOpenEvent")) {
322
Inventory opened = (Inventory) call(event, "getInventory");
323
// Other plugins commonly sort/rewrite a container from the open
324
// event without producing a Bukkit inventory mutation event.
325
// Invalidate one tick later so their changes are already applied.
326
schedule(() -> wakeInventory(opened), 1L);
327
} else if (name.endsWith("InventoryClickEvent")) {
328
Object view = call(event, "getView");
329
Inventory top = (Inventory) call(view, "getTopInventory");
330
Inventory clicked = (Inventory) call(event, "getClickedInventory");
331
schedule(() -> {
332
wakeInventory(top);
333
if (clicked != null && clicked != top) wakeInventory(clicked);
334
}, 1L);
335
} else if (name.endsWith("InventoryDragEvent")) {
336
Object view = call(event, "getView");
337
Inventory top = (Inventory) call(view, "getTopInventory");
338
schedule(() -> wakeInventory(top), 1L);
339
} else if (name.endsWith("InventoryCloseEvent")) {
340
wakeInventory((Inventory) call(event, "getInventory"));
341
} else if (name.endsWith("InventoryMoveItemEvent")) {
342
Inventory source = (Inventory) call(event, "getSource");
343
Inventory destination = (Inventory) call(event, "getDestination");
344
schedule(() -> { wakeInventory(source); wakeInventory(destination); }, 1L);
345
} else if (name.endsWith("InventoryPickupItemEvent")) {
346
Inventory inventory = (Inventory) call(event, "getInventory");
347
schedule(() -> wakeInventory(inventory), 1L);
348
} else if (name.endsWith("FurnaceSmeltEvent") || name.endsWith("FurnaceExtractEvent")
349
|| name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")) {
350
Block block = (Block) call(event, "getBlock");
351
schedule(() -> {
352
Inventory inventory = inventoryOf(block);
353
if (inventory != null) wakeInventory(inventory);
354
}, 1L);
355
} else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {
356
// Double-chest canonical identities can change as either half loads.
357
lastConnectionCount = -1;
358
for (Group group : groups.values()) active.add(group);
359
}
360
} catch (Throwable t) {
361
// A missed event must never stall the network permanently; emergency
362
// sleeping probes remain as a fallback.
363
}
364
}
365
366
void schedule(Runnable runnable, long delay) throws Exception {
367
Object scheduler = call(call(plugin, "getServer"), "getScheduler");
368
Class<?> pluginInterface = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
369
call(scheduler, "runTaskLater", new Class<?>[]{pluginInterface, Runnable.class, long.class}, plugin, runnable, delay);
370
}
371
372
void callPlugin(String name) {
373
try { call(plugin, name); } catch (Throwable ignored) {}
374
}
375
376
final class Group {
377
final ContainerKey key;
378
final List<ConnectionView> connections = new ArrayList<>();
379
final List<ConnectionView> filtered = new ArrayList<>();
380
final List<ConnectionView> unfiltered = new ArrayList<>();
381
final EnumSet<Material> reserved = EnumSet.noneOf(Material.class);
382
final Set<ContainerKey> destinationKeys = new HashSet<>();
383
ItemStack[] sourceCache;
384
int[] cycleBudget;
385
final IdentityHashMap<Object, Boolean> usedConnections = new IdentityHashMap<>();
386
boolean cacheDirty = true;
387
int failed;
388
389
Group(ContainerKey key) { this.key = key; }
390
391
void rebuildCache() {
392
for (ConnectionView connection : connections) {
393
if (connection.filters.isEmpty()) unfiltered.add(connection);
394
else {
395
filtered.add(connection);
396
reserved.addAll(connection.filters);
397
}
398
destinationKeys.add(endpointKey(connection.destination));
399
}
400
cacheDirty = true;
401
}
402
403
void prepareCycleBudget() {
404
Inventory source = inventoryAt(connections.get(0).source);
405
if (source == null || source instanceof FurnaceInventory) {
406
cycleBudget = null;
407
return;
408
}
409
if (cacheDirty || sourceCache == null) {
410
ItemStack[] storage = source.getStorageContents();
411
sourceCache = cloneContents(storage);
412
cacheDirty = false;
413
}
414
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {
415
cycleBudget = new int[sourceCache.length];
416
}
417
for (int slot = 0; slot < sourceCache.length; slot++) {
418
ItemStack stack = sourceCache[slot];
419
cycleBudget[slot] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();
420
}
421
}
422
423
boolean slotMatchesRealInventory(Inventory source, int slot, ItemStack expected) {
424
ItemStack actual = source.getItem(slot);
425
if (expected == null || expected.getType().isAir()) {
426
return actual == null || actual.getType().isAir();
427
}
428
if (actual == null || actual.getType().isAir()) return false;
429
return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
430
}
431
432
void rebuildSourceCacheNow(Inventory source) {
433
ItemStack[] storage = source.getStorageContents();
434
sourceCache = cloneContents(storage);
435
cacheDirty = false;
436
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {
437
cycleBudget = new int[sourceCache.length];
438
}
439
for (int slot = 0; slot < sourceCache.length; slot++) {
440
ItemStack stack = sourceCache[slot];
441
cycleBudget[slot] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();
442
}
443
}
444
445
boolean refreshRealInventoryIfChanged(Inventory source) {
446
if (source instanceof FurnaceInventory) return false;
447
ItemStack[] actual = source.getStorageContents();
448
if (sourceCache == null || actual.length != sourceCache.length) {
449
sourceCache = cloneContents(actual);
450
cacheDirty = false;
451
prepareCycleBudget();
452
return true;
453
}
454
for (int slot = 0; slot < actual.length; slot++) {
455
ItemStack expected = sourceCache[slot];
456
ItemStack real = actual[slot];
457
boolean same;
458
if (expected == null || expected.getType().isAir()) {
459
same = real == null || real.getType().isAir();
460
} else {
461
same = real != null && !real.getType().isAir()
462
&& expected.getAmount() == real.getAmount()
463
&& expected.isSimilar(real);
464
}
465
if (!same) {
466
sourceCache = cloneContents(actual);
467
cacheDirty = false;
468
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {
469
cycleBudget = new int[sourceCache.length];
470
}
471
for (int i = 0; i < sourceCache.length; i++) {
472
ItemStack stack = sourceCache[i];
473
cycleBudget[i] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();
474
}
475
return true;
476
}
477
}
478
return false;
479
}
480
481
RunResult run() {
482
Inventory source = inventoryAt(connections.get(0).source);
483
if (source == null) return RunResult.NO_MOVE;
484
485
// Furnaces are special: only the output slot is a legal source.
486
if (source instanceof FurnaceInventory furnace) {
487
boolean moved = false;
488
Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());
489
for (ConnectionView connection : filtered) {
490
ItemStack output = furnace.getResult();
491
if (used.contains(connection.raw) || !allowed(connection, output, true, reserved)) continue;
492
TransferResult result = transferFurnaceOutput(connection, furnace, key);
493
if (result.moved) { used.add(connection.raw); moved = true; }
494
}
495
for (ConnectionView connection : unfiltered) {
496
ItemStack output = furnace.getResult();
497
if (used.contains(connection.raw) || !allowed(connection, output, false, reserved)) continue;
498
TransferResult result = transferFurnaceOutput(connection, furnace, key);
499
if (result.moved) { used.add(connection.raw); moved = true; }
500
}
501
cacheDirty = true;
502
return moved ? RunResult.MOVED : RunResult.NO_MOVE;
503
}
504
505
if (cycleBudget == null || cacheDirty || sourceCache == null) {
506
prepareCycleBudget();
507
}
508
if (cycleBudget == null || sourceCache == null) return RunResult.NO_MOVE;
509
510
usedConnections.clear();
511
boolean moved = false;
512
513
// Preserve vanilla-like first-slot preference: one ascending pass over
514
// the source inventory services every outgoing connection at most once.
515
for (int slot = 0; slot < sourceCache.length; slot++) {
516
int availableAtCycleStart = cycleBudget[slot];
517
if (availableAtCycleStart <= 0) continue;
518
ItemStack stack = sourceCache[slot];
519
if (stack == null || stack.getType().isAir() || stack.getAmount() <= 0) continue;
520
521
// The cache is an optimisation, never an authority. A plugin may
522
// have sorted/replaced this slot without emitting a Bukkit event.
523
// Verify only the slot we are about to use; on mismatch rebuild
524
// once from the real inventory and restart this group next cycle.
525
if (!slotMatchesRealInventory(source, slot, stack)) {
526
rebuildSourceCacheNow(source);
527
failed = 0;
528
return RunResult.STALE_CACHE;
529
}
530
531
Material type = stack.getType();
532
533
for (ConnectionView connection : filtered) {
534
if (stack == null || stack.getAmount() <= 0 || cycleBudget[slot] <= 0) break;
535
if (usedConnections.containsKey(connection.raw) || !connection.filters.contains(type)) continue;
536
TransferResult result = transferCached(connection, stack, cycleDestinations, key);
537
if (!result.moved) continue;
538
usedConnections.put(connection.raw, Boolean.TRUE);
539
stack = decrementCachedSource(source, slot, stack);
540
sourceCache[slot] = stack;
541
cycleBudget[slot]--;
542
moved = true;
543
}
544
545
if (!reserved.contains(type)) {
546
for (ConnectionView connection : unfiltered) {
547
if (stack == null || stack.getAmount() <= 0 || cycleBudget[slot] <= 0) break;
548
if (usedConnections.containsKey(connection.raw)) continue;
549
TransferResult result = transferCached(connection, stack, cycleDestinations, key);
550
if (!result.moved) continue;
551
usedConnections.put(connection.raw, Boolean.TRUE);
552
stack = decrementCachedSource(source, slot, stack);
553
sourceCache[slot] = stack;
554
cycleBudget[slot]--;
555
moved = true;
556
}
557
}
558
}
559
return moved ? RunResult.MOVED : RunResult.NO_MOVE;
560
}
561
}
562
563
ItemStack[] cloneContents(ItemStack[] input) {
564
ItemStack[] copy = new ItemStack[input.length];
565
for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
566
return copy;
567
}
568
569
ItemStack decrementCachedSource(Inventory source, int slot, ItemStack cached) {
570
if (cached.getAmount() <= 1) {
571
source.setItem(slot, null);
572
return null;
573
}
574
ItemStack reduced = cached.clone();
575
reduced.setAmount(cached.getAmount() - 1);
576
source.setItem(slot, reduced);
577
return reduced;
578
}
579
580
TransferResult transferFurnaceOutput(ConnectionView connection, FurnaceInventory source, ContainerKey sourceKey) {
581
ItemStack output = source.getResult();
582
Inventory destination = inventoryAt(connection.destination);
583
if (destination == null || output == null || output.getType().isAir()) return TransferResult.NO_MOVE;
584
585
// Furnace output used to bypass cycleDestinations and write directly to
586
// the Bukkit inventory. That left a destination source-group with a
587
// stale slot cache, so freshly produced items could remain invisible to
588
// its outgoing pipes until an unrelated event or topology refresh.
589
// Route every internal insertion through the same DestinationState so
590
// multiple incoming normal/furnace pipes share one authoritative
591
// cycle-local view and downstream caches are updated transactionally.
592
ContainerKey destinationKey = inventoryKey(destination);
593
if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
594
DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,
595
ignored -> new DestinationState(destination));
596
if (!state.insertOne(output)) return TransferResult.NO_MOVE;
597
598
decrementFurnace(source);
599
syncIncomingCache(destinationKey, state);
600
afterTransfer(connection, source, destination);
601
return new TransferResult(true, destinationKey);
602
}
603
604
TransferResult transferCached(ConnectionView connection, ItemStack source,
605
Map<ContainerKey, DestinationState> destinations, ContainerKey sourceKey) {
606
Inventory destination = inventoryAt(connection.destination);
607
if (destination == null) return TransferResult.NO_MOVE;
608
ContainerKey destinationKey = inventoryKey(destination);
609
if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;
610
DestinationState state = destinations.computeIfAbsent(destinationKey,
611
ignored -> new DestinationState(destination));
612
if (!state.insertOne(source)) return TransferResult.NO_MOVE;
613
syncIncomingCache(destinationKey, state);
614
afterTransfer(connection, null, destination);
615
return new TransferResult(true, destinationKey);
616
}
617
618
void syncIncomingCache(ContainerKey destinationKey, DestinationState state) {
619
Group destinationGroup = groups.get(destinationKey);
620
if (destinationGroup != null && !(state.inventory instanceof FurnaceInventory)) {
621
// DestinationState owns this cycle-local array. Reusing it avoids
622
// cloning the entire destination after every inserted item.
623
destinationGroup.sourceCache = state.storage;
624
destinationGroup.cacheDirty = false;
625
}
626
wakeKeyInternal(destinationKey);
627
}
628
629
final class DestinationState {
630
final Inventory inventory;
631
ItemStack[] storage;
632
633
DestinationState(Inventory inventory) {
634
this.inventory = inventory;
635
this.storage = inventory instanceof FurnaceInventory ? null : cloneContents(inventory.getStorageContents());
636
}
637
638
/**
639
* Insert one item using the cached destination view, but validate the exact
640
* real slot immediately before every write. If another plugin silently
641
* changed/sorted the inventory, rebuild the full destination snapshot and
642
* restart the search from slot 0 so first-slot/merge preference stays correct.
643
*/
644
boolean insertOne(ItemStack source) {
645
// Crafters are destination-only and deliberately bypass the normal
646
// destination slot cache. Query their live disabled-slot state and
647
// use vanilla-equivalent hopper insertion ordering instead.
648
if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {
649
return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
650
}
651
ItemStack one = source.clone();
652
one.setAmount(1);
653
654
// Furnace slots are never cached: read the real input/fuel slot for
655
// every attempt, so external furnace mutations cannot be overwritten.
656
if (inventory instanceof FurnaceInventory furnace) {
657
ItemStack smelting = furnace.getSmelting();
658
if (furnace.canSmelt(one) && canMerge(smelting, one, inventory.getMaxStackSize())) {
659
// Re-read just before write. This is cheap and keeps the same
660
// optimistic validation rule as normal container slots.
661
ItemStack actual = furnace.getSmelting();
662
if (!sameStackExact(smelting, actual)) return false;
663
furnace.setSmelting(merge(actual, one));
664
return true;
665
}
666
ItemStack fuel = furnace.getFuel();
667
if (furnace.isFuel(one) && canMerge(fuel, one, inventory.getMaxStackSize())) {
668
ItemStack actual = furnace.getFuel();
669
if (!sameStackExact(fuel, actual)) return false;
670
furnace.setFuel(merge(actual, one));
671
return true;
672
}
673
return false;
674
}
675
676
// Normally attempt 0 succeeds with one getItem() validation. A second
677
// pass is only needed after a detected stale destination cache.
678
for (int attempt = 0; attempt < 2; attempt++) {
679
boolean restart = false;
680
681
// Minecraft-like preference: merge into the first compatible stack.
682
for (int slot = 0; slot < storage.length; slot++) {
683
ItemStack expected = storage[slot];
684
if (expected == null || expected.getType().isAir() || !expected.isSimilar(one)
685
|| expected.getAmount() >= Math.min(expected.getMaxStackSize(), inventory.getMaxStackSize())) {
686
continue;
687
}
688
689
ItemStack actual = inventory.getItem(slot);
690
if (!sameStackExact(expected, actual)) {
691
refreshFromReal();
692
restart = true;
693
break;
694
}
695
696
ItemStack merged = actual.clone();
697
merged.setAmount(actual.getAmount() + 1);
698
inventory.setItem(slot, merged);
699
storage[slot] = merged;
700
return true;
701
}
702
if (restart) continue;
703
704
// Otherwise use the first empty slot, validating that it is still
705
// empty in the real inventory before writing to it.
706
for (int slot = 0; slot < storage.length; slot++) {
707
ItemStack expected = storage[slot];
708
if (expected != null && !expected.getType().isAir()) continue;
709
710
ItemStack actual = inventory.getItem(slot);
711
if (!sameStackExact(expected, actual)) {
712
refreshFromReal();
713
restart = true;
714
break;
715
}
716
717
ItemStack inserted = one.clone();
718
inventory.setItem(slot, inserted);
719
storage[slot] = inserted;
720
return true;
721
}
722
if (!restart) return false;
723
}
724
725
// A destination that changes twice during one synchronous transfer
726
// attempt is treated conservatively: do not overwrite anything.
727
return false;
728
}
729
730
void refreshFromReal() {
731
storage = cloneContents(inventory.getStorageContents());
732
}
733
}
734
735
boolean allowed(ConnectionView connection, ItemStack item, boolean filtered, Set<Material> reserved) {
736
if (item == null || item.getType().isAir() || item.getAmount() <= 0) return false;
737
return filtered ? connection.filters.contains(item.getType()) : !reserved.contains(item.getType());
738
}
739
740
void afterTransfer(ConnectionView connection, Inventory source, Inventory destination) {
741
ContainerKey sourceKey = source == null ? null : inventoryKey(source);
742
ContainerKey destinationKey = inventoryKey(destination);
743
if (sourceKey != null) wakeKeyInternal(sourceKey);
744
if (destinationKey != null) wakeKeyInternal(destinationKey);
745
746
int cooldown = Math.max(0, config().getInt("particles.transfer-animation-cooldown-ticks", 100));
747
Long previous = lastParticleTick.get(connection.raw);
748
if (previous == null || logicalTick - previous >= cooldown) {
749
lastParticleTick.put(connection.raw, logicalTick);
750
try { call(plugin, "animateTransfer", new Class<?>[]{connection.raw.getClass()}, connection.raw); }
751
catch (Throwable ignored) {}
752
}
753
}
754
755
Inventory inventoryAt(EndpointView endpoint) {
756
World world = Bukkit.getWorld(endpoint.world);
757
if (world == null || !world.isChunkLoaded(endpoint.x >> 4, endpoint.z >> 4)) return null;
758
return inventoryOf(world.getBlockAt(endpoint.x, endpoint.y, endpoint.z));
759
}
760
761
Inventory inventoryOf(Block block) {
762
BlockState state = block.getState();
763
if (state instanceof Chest chest) return chest.getInventory();
764
if (state instanceof Container container) return container.getInventory();
765
return null;
766
}
767
768
ContainerKey endpointKey(EndpointView endpoint) {
769
Inventory inventory = inventoryAt(endpoint);
770
ContainerKey key = inventoryKey(inventory);
771
return key != null ? key : new ContainerKey(endpoint.world, pack(endpoint.x, endpoint.y, endpoint.z));
772
}
773
774
ContainerKey inventoryKey(Inventory inventory) {
775
if (inventory == null) return null;
776
InventoryHolder holder = inventory.getHolder();
777
if (holder instanceof DoubleChest doubleChest) {
778
ContainerKey left = holderKey(doubleChest.getLeftSide());
779
ContainerKey right = holderKey(doubleChest.getRightSide());
780
if (left == null) return right;
781
if (right == null) return left;
782
int wc = left.world.compareTo(right.world);
783
return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;
784
}
785
Location location = inventory.getLocation();
786
if (location != null && location.getWorld() != null) {
787
return new ContainerKey(location.getWorld().getUID(),
788
pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
789
}
790
return holderKey(holder);
791
}
792
793
ContainerKey holderKey(InventoryHolder holder) {
794
if (holder instanceof BlockState state) {
795
Block block = state.getBlock();
796
return new ContainerKey(block.getWorld().getUID(), pack(block.getX(), block.getY(), block.getZ()));
797
}
798
return null;
799
}
800
}
801
802
private enum RunResult { MOVED, NO_MOVE, STALE_CACHE }
803
private record TransferResult(boolean moved, ContainerKey destinationKey) {
804
static final TransferResult NO_MOVE = new TransferResult(false, null);
805
}
806
private record ContainerKey(UUID world, long packed) {}
807
private record EndpointView(UUID world, int x, int y, int z) {}
808
809
private static final class ConnectionView {
810
final Object raw;
811
final EndpointView source;
812
final EndpointView destination;
813
final EnumSet<Material> filters;
814
815
ConnectionView(Object raw, EndpointView source, EndpointView destination, EnumSet<Material> filters) {
816
this.raw = raw;
817
this.source = source;
818
this.destination = destination;
819
this.filters = filters;
820
}
821
822
static ConnectionView read(Object raw) throws Exception {
823
Object source = call(raw, "source");
824
Object destination = call(raw, "destination");
825
EndpointView sourceView = endpoint(source);
826
EndpointView destinationView = endpoint(destination);
827
EnumSet<Material> filters = EnumSet.noneOf(Material.class);
828
for (Object value : (List<?>) call(raw, "filter")) {
829
if (value instanceof ItemStack item && !item.getType().isAir()) filters.add(item.getType());
830
}
831
return new ConnectionView(raw, sourceView, destinationView, filters);
832
}
833
834
static EndpointView endpoint(Object endpoint) throws Exception {
835
return new EndpointView((UUID) call(endpoint, "world"), (int) call(endpoint, "x"),
836
(int) call(endpoint, "y"), (int) call(endpoint, "z"));
837
}
838
}
839
840
private static boolean sameStackExact(ItemStack expected, ItemStack actual) {
841
boolean expectedEmpty = expected == null || expected.getType().isAir();
842
boolean actualEmpty = actual == null || actual.getType().isAir();
843
if (expectedEmpty || actualEmpty) return expectedEmpty == actualEmpty;
844
return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
845
}
846
847
private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {
848
return existing == null || existing.getType().isAir()
849
|| (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));
850
}
851
852
private static ItemStack merge(ItemStack existing, ItemStack add) {
853
if (existing == null || existing.getType().isAir()) return add.clone();
854
ItemStack result = existing.clone();
855
result.setAmount(existing.getAmount() + add.getAmount());
856
return result;
857
}
858
859
private static void decrementFurnace(FurnaceInventory inventory) {
860
ItemStack result = inventory.getResult();
861
if (result == null) return;
862
if (result.getAmount() <= 1) inventory.setResult(null);
863
else {
864
ItemStack reduced = result.clone();
865
reduced.setAmount(result.getAmount() - 1);
866
inventory.setResult(reduced);
867
}
868
}
869
870
private static long pack(int x, int y, int z) {
871
return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFFL);
872
}
873
874
private static Object field(Object target, String name) throws Exception {
875
FieldKey key = new FieldKey(target.getClass(), name);
876
Field field = FIELDS.get(key);
877
if (field == null) {
878
for (Class<?> type = target.getClass(); type != null; type = type.getSuperclass()) {
879
try {
880
field = type.getDeclaredField(name);
881
field.setAccessible(true);
882
FIELDS.put(key, field);
883
break;
884
} catch (NoSuchFieldException ignored) {}
885
}
886
}
887
if (field == null) throw new NoSuchFieldException(name);
888
return field.get(target);
889
}
890
891
private static Object call(Object target, String name, Object... arguments) throws Exception {
892
return call(target, name, new Class<?>[0], arguments);
893
}
894
895
private static Object call(Object target, String name, Class<?>[] parameterTypes, Object... arguments) throws Exception {
896
Method method = cachedMethod(target.getClass(), name, parameterTypes);
897
return method.invoke(target, arguments);
898
}
899
900
private static Object invokeStatic(Class<?> owner, String name, Class<?>[] parameterTypes, Object... arguments) throws Exception {
901
Method method = cachedMethod(owner, name, parameterTypes);
902
return method.invoke(null, arguments);
903
}
904
905
private static Method cachedMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {
906
MethodKey key = new MethodKey(owner, name, List.of(parameterTypes));
907
Method method = METHODS.get(key);
908
if (method != null) return method;
909
method = findMethod(owner, name, parameterTypes);
910
method.setAccessible(true);
911
METHODS.put(key, method);
912
return method;
913
}
914
915
private static Method findMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {
916
for (Class<?> type = owner; type != null; type = type.getSuperclass()) {
917
for (Method method : type.getDeclaredMethods()) {
918
if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
919
}
920
}
921
for (Method method : owner.getMethods()) {
922
if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
923
}
924
throw new NoSuchMethodException(owner.getName() + "." + name);
925
}
926
927
private static boolean compatible(Class<?>[] actual, Class<?>[] requested) {
928
if (actual.length != requested.length) return false;
929
for (int index = 0; index < actual.length; index++) {
930
if (!wrap(actual[index]).isAssignableFrom(wrap(requested[index]))) return false;
931
}
932
return true;
933
}
934
935
private static Class<?> wrap(Class<?> type) {
936
if (!type.isPrimitive()) return type;
937
if (type == int.class) return Integer.class;
938
if (type == long.class) return Long.class;
939
if (type == boolean.class) return Boolean.class;
940
if (type == double.class) return Double.class;
941
if (type == float.class) return Float.class;
942
return type;
943
}
944
945
private static void log(Object plugin, String message, Throwable throwable) {
946
try {
947
Object logger = call(plugin, "getLogger");
948
call(logger, "log", new Class<?>[]{java.util.logging.Level.class, String.class, Throwable.class},
949
java.util.logging.Level.WARNING, message, throwable);
950
} catch (Throwable ignored) {}
951
}
952
953
private record MethodKey(Class<?> owner, String name, List<Class<?>> parameters) {}
954
private record FieldKey(Class<?> owner, String name) {}
955
}
@@ -0,0 +1,955 @@1
package nl.timfalken.containerpipes;2
3
import org.bukkit.Bukkit;4
import org.bukkit.Location;5
import org.bukkit.Material;6
import org.bukkit.World;7
import org.bukkit.block.Block;8
import org.bukkit.block.BlockState;9
import org.bukkit.block.Chest;10
import org.bukkit.block.Container;11
import org.bukkit.block.DoubleChest;12
import org.bukkit.configuration.file.FileConfiguration;13
import org.bukkit.inventory.FurnaceInventory;14
import org.bukkit.inventory.Inventory;15
import org.bukkit.inventory.InventoryHolder;16
import org.bukkit.inventory.ItemStack;17
18
import java.lang.reflect.*;19
import java.util.*;20
import java.util.concurrent.ConcurrentHashMap;21
22
/**23
* Direct Paper-API transfer planner.24
*25
* Reflection is used only to read ContainerPipes' private immutable Connection26
* records and to call the optional visual animation. World/block/inventory/item27
* operations in the transfer hot path are ordinary Java calls.28
*/29
public final class OptimizedTransferPlanner {30
private OptimizedTransferPlanner() {}31
32
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());33
private static final Map<MethodKey, Method> METHODS = new ConcurrentHashMap<>();34
private static final Map<FieldKey, Field> FIELDS = new ConcurrentHashMap<>();35
36
public static void tick(Object plugin) {37
try {38
State state = STATES.computeIfAbsent(plugin, State::new);39
state.tick();40
state.callPlugin("refreshSelectionParticles");41
state.callPlugin("expireSelections");42
} catch (Throwable t) {43
log(plugin, "Direct transfer planner failed", t);44
}45
}46
47
public static void probeSleeping(Object plugin) {48
try { STATES.computeIfAbsent(plugin, State::new).probeSleepingBatch(); }49
catch (Throwable t) { log(plugin, "Sleeping transfer probe failed", t); }50
}51
52
/**53
* Called when a Connection object is replaced without changing the total54
* connection count (most notably when a pipe filter is edited). A normal55
* count-based topology check cannot see that immediately, so force a56
* synchronous rebuild of the cached source groups/filter reservations.57
* Filter edits are rare and happen on the server thread, making a full58
* rebuild here preferable to allowing stale routing state for up to the59
* periodic fingerprint interval.60
*/61
public static void connectionChanged(Object plugin) {62
try { STATES.computeIfAbsent(plugin, State::new).rebuild(true); }63
catch (Throwable t) { log(plugin, "Connection topology refresh failed", t); }64
}65
66
private static final class State {67
final Object plugin;68
final Map<ContainerKey, Group> groups = new LinkedHashMap<>();69
final Map<ContainerKey, Set<Group>> wakeIndex = new HashMap<>();70
final LinkedHashSet<Group> active = new LinkedHashSet<>();71
final LinkedHashMap<Group, Long> sleeping = new LinkedHashMap<>();72
final IdentityHashMap<Object, Long> lastParticleTick = new IdentityHashMap<>();73
74
long logicalTick;75
int schedulerInterval = 3;76
int idleAfter = 3;77
int sleepProbe = 200;78
int sleepBatchSize = 10;79
int visualInterval = 20;80
long nextVisualTick;81
long nextSleepingBatchTick;82
int lastConnectionCount = -1;83
int lastIdentityFingerprint;84
long nextTopologyFingerprintTick;85
long nextConfigReloadTick;86
final Map<ContainerKey, DestinationState> cycleDestinations = new HashMap<>();87
88
State(Object plugin) {89
this.plugin = plugin;90
reloadConfig();91
rebuild(true);92
registerListeners();93
}94
95
void reloadConfig() {96
FileConfiguration cfg = config();97
schedulerInterval = Math.max(1, cfg.getInt("transfer-interval-ticks", 3));98
idleAfter = Math.max(1, cfg.getInt("performance.idle-after-failed-attempts", 3));99
sleepProbe = Math.max(schedulerInterval, cfg.getInt("performance.sleeping-probe-interval-ticks", 200));100
sleepBatchSize = Math.max(1, cfg.getInt("performance.sleeping-probe-batch-size", 10));101
visualInterval = Math.max(5, cfg.getInt("visuals.refresh-interval-ticks", 20));102
}103
104
FileConfiguration config() {105
try { return (FileConfiguration) call(plugin, "getConfig"); }106
catch (Throwable t) { throw new IllegalStateException(t); }107
}108
109
@SuppressWarnings("unchecked")110
Map<Long, Object> rawConnections() {111
try { return (Map<Long, Object>) field(plugin, "connections"); }112
catch (Throwable t) { throw new IllegalStateException(t); }113
}114
115
void tick() {116
logicalTick += schedulerInterval;117
reloadConfigIfNeeded();118
rebuild(false);119
cycleDestinations.clear();120
121
List<Group> cycle = new ArrayList<>(active);122
123
// Freeze only the number of items that was available at the start of124
// this transfer cycle. Incoming pipes may still update sourceCache125
// transactionally during the cycle, but those newly received items126
// receive no budget until the next cycle. Existing items in a127
// through-container can therefore keep flowing while it also receives.128
for (Group group : cycle) {129
if (!active.contains(group) || groups.get(group.key) != group) continue;130
group.prepareCycleBudget();131
}132
133
for (Group group : cycle) {134
if (!active.contains(group) || groups.get(group.key) != group) continue;135
136
RunResult result = group.run();137
if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {138
// STALE_CACHE already rebuilt from the real inventory. Keep the139
// group active so the corrected contents are retried next cycle.140
group.failed = 0;141
} else if (++group.failed >= idleAfter) {142
Inventory source = inventoryAt(group.connections.get(0).source);143
if (source != null && group.refreshRealInventoryIfChanged(source)) {144
// A direct, non-event mutation introduced/rearranged items.145
// Do not sleep on stale knowledge; retry on the normal cadence.146
group.failed = 0;147
} else {148
active.remove(group);149
sleeping.put(group, logicalTick + sleepProbe);150
}151
}152
}153
154
int sleepingBatchInterval = Math.max(1, config().getInt("performance.sleeping-probe-batch-interval-ticks", 5));155
if (logicalTick >= nextSleepingBatchTick) {156
probeSleepingBatch();157
nextSleepingBatchTick = logicalTick + sleepingBatchInterval;158
}159
160
if (logicalTick >= nextVisualTick) {161
try {162
Class<?> visual = Class.forName("nl.timfalken.containerpipes.VisualPerformanceManager", false,163
plugin.getClass().getClassLoader());164
invokeStatic(visual, "tick", new Class<?>[]{Object.class}, plugin);165
} catch (Throwable ignored) {}166
nextVisualTick = logicalTick + visualInterval;167
}168
}169
170
void reloadConfigIfNeeded() {171
if (logicalTick < nextConfigReloadTick) return;172
reloadConfig();173
nextConfigReloadTick = logicalTick + 200;174
}175
176
void probeSleepingBatch() {177
rebuild(false);178
if (sleeping.isEmpty()) return;179
int processed = 0;180
List<Group> activate = new ArrayList<>();181
List<Group> requeue = new ArrayList<>();182
Iterator<Map.Entry<Group, Long>> it = sleeping.entrySet().iterator();183
while (it.hasNext() && processed < sleepBatchSize) {184
Map.Entry<Group, Long> entry = it.next();185
if (entry.getValue() > logicalTick) continue;186
Group group = entry.getKey();187
it.remove();188
processed++;189
if (groups.get(group.key) != group) continue;190
// A sleeping probe is the final safety net for direct inventory191
// mutations by other plugins that do not emit Bukkit events. Always192
// read the real inventory here instead of trusting an old clean cache.193
group.cacheDirty = true;194
group.prepareCycleBudget();195
RunResult result = group.run();196
if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {197
group.failed = 0;198
activate.add(group);199
} else {200
requeue.add(group);201
}202
}203
active.addAll(activate);204
for (Group group : requeue) sleeping.put(group, logicalTick + sleepProbe);205
}206
207
void rebuild(boolean force) {208
Map<Long, Object> raw = rawConnections();209
int count = raw.size();210
boolean dueFingerprint = logicalTick >= nextTopologyFingerprintTick;211
if (!force && count == lastConnectionCount && !dueFingerprint) return;212
213
int fingerprint = count;214
for (Object connection : raw.values()) fingerprint = 31 * fingerprint + System.identityHashCode(connection);215
nextTopologyFingerprintTick = logicalTick + 400;216
if (!force && count == lastConnectionCount && fingerprint == lastIdentityFingerprint) return;217
218
lastConnectionCount = count;219
lastIdentityFingerprint = fingerprint;220
221
Map<ContainerKey, Boolean> previousAwake = new HashMap<>();222
for (Group group : groups.values()) previousAwake.put(group.key, active.contains(group));223
224
groups.clear();225
wakeIndex.clear();226
active.clear();227
sleeping.clear();228
229
for (Object rawConnection : raw.values()) {230
try {231
ConnectionView connection = ConnectionView.read(rawConnection);232
ContainerKey sourceKey = endpointKey(connection.source);233
groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);234
} catch (Throwable t) {235
log(plugin, "Could not index a pipe connection", t);236
}237
}238
239
for (Group group : groups.values()) {240
group.rebuildCache();241
wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);242
for (ContainerKey destination : group.destinationKeys) {243
wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);244
}245
// Rebuilds are infrequent and should never make a usable pipe wait for246
// the emergency probe. Start rebuilt groups active.247
active.add(group);248
}249
}250
251
void wakeInventory(Inventory inventory) {252
ContainerKey key = inventoryKey(inventory);253
if (key != null) invalidateAndWakeKey(key);254
}255
256
void invalidateAndWakeKey(ContainerKey key) {257
Set<Group> affected = wakeIndex.get(key);258
if (affected == null) return;259
for (Group group : affected) {260
if (group.key.equals(key)) group.cacheDirty = true;261
group.failed = 0;262
sleeping.remove(group);263
active.add(group);264
}265
}266
267
void wakeKeyInternal(ContainerKey key) {268
Set<Group> affected = wakeIndex.get(key);269
if (affected == null) return;270
for (Group group : affected) {271
group.failed = 0;272
sleeping.remove(group);273
active.add(group);274
}275
}276
277
void registerListeners() {278
// Event registration is deliberately reflective: it is not a hot path and279
// keeps this replacement class compatible with the already-built plugin.280
try {281
ClassLoader cl = plugin.getClass().getClassLoader();282
Class<?> listenerClass = Class.forName("org.bukkit.event.Listener", false, cl);283
Class<?> executorClass = Class.forName("org.bukkit.plugin.EventExecutor", false, cl);284
Class<?> priorityClass = Class.forName("org.bukkit.event.EventPriority", false, cl);285
Object monitor = Enum.valueOf((Class<Enum>) priorityClass.asSubclass(Enum.class), "MONITOR");286
Object listener = Proxy.newProxyInstance(cl, new Class<?>[]{listenerClass}, (p, m, a) -> null);287
Object executor = Proxy.newProxyInstance(cl, new Class<?>[]{executorClass}, (p, m, a) -> {288
if ("execute".equals(m.getName()) && a != null && a.length == 2) onEvent(a[1]);289
return null;290
});291
Object pm = call(call(plugin, "getServer"), "getPluginManager");292
Class<?> pluginClass = Class.forName("org.bukkit.plugin.Plugin", false, cl);293
Method register = findMethod(pm.getClass(), "registerEvent",294
new Class<?>[]{Class.class, listenerClass, priorityClass, executorClass, pluginClass, boolean.class});295
String[] names = {296
"org.bukkit.event.inventory.InventoryOpenEvent",297
"org.bukkit.event.inventory.InventoryClickEvent",298
"org.bukkit.event.inventory.InventoryDragEvent",299
"org.bukkit.event.inventory.InventoryCloseEvent",300
"org.bukkit.event.inventory.InventoryMoveItemEvent",301
"org.bukkit.event.inventory.InventoryPickupItemEvent",302
"org.bukkit.event.inventory.FurnaceSmeltEvent",303
"org.bukkit.event.inventory.FurnaceExtractEvent",304
"org.bukkit.event.inventory.FurnaceBurnEvent",305
"org.bukkit.event.block.BlockCookEvent",306
"org.bukkit.event.world.ChunkLoadEvent",307
"org.bukkit.event.world.ChunkUnloadEvent"308
};309
for (String name : names) {310
try { register.invoke(pm, Class.forName(name, false, cl), listener, monitor, executor, plugin, true); }311
catch (Throwable ignored) {}312
}313
} catch (Throwable t) {314
log(plugin, "Could not register transfer wake listeners", t);315
}316
}317
318
void onEvent(Object event) {319
try {320
String name = event.getClass().getName();321
if (name.endsWith("InventoryOpenEvent")) {322
Inventory opened = (Inventory) call(event, "getInventory");323
// Other plugins commonly sort/rewrite a container from the open324
// event without producing a Bukkit inventory mutation event.325
// Invalidate one tick later so their changes are already applied.326
schedule(() -> wakeInventory(opened), 1L);327
} else if (name.endsWith("InventoryClickEvent")) {328
Object view = call(event, "getView");329
Inventory top = (Inventory) call(view, "getTopInventory");330
Inventory clicked = (Inventory) call(event, "getClickedInventory");331
schedule(() -> {332
wakeInventory(top);333
if (clicked != null && clicked != top) wakeInventory(clicked);334
}, 1L);335
} else if (name.endsWith("InventoryDragEvent")) {336
Object view = call(event, "getView");337
Inventory top = (Inventory) call(view, "getTopInventory");338
schedule(() -> wakeInventory(top), 1L);339
} else if (name.endsWith("InventoryCloseEvent")) {340
wakeInventory((Inventory) call(event, "getInventory"));341
} else if (name.endsWith("InventoryMoveItemEvent")) {342
Inventory source = (Inventory) call(event, "getSource");343
Inventory destination = (Inventory) call(event, "getDestination");344
schedule(() -> { wakeInventory(source); wakeInventory(destination); }, 1L);345
} else if (name.endsWith("InventoryPickupItemEvent")) {346
Inventory inventory = (Inventory) call(event, "getInventory");347
schedule(() -> wakeInventory(inventory), 1L);348
} else if (name.endsWith("FurnaceSmeltEvent") || name.endsWith("FurnaceExtractEvent")349
|| name.endsWith("FurnaceBurnEvent") || name.endsWith("BlockCookEvent")) {350
Block block = (Block) call(event, "getBlock");351
schedule(() -> {352
Inventory inventory = inventoryOf(block);353
if (inventory != null) wakeInventory(inventory);354
}, 1L);355
} else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {356
// Double-chest canonical identities can change as either half loads.357
lastConnectionCount = -1;358
for (Group group : groups.values()) active.add(group);359
}360
} catch (Throwable t) {361
// A missed event must never stall the network permanently; emergency362
// sleeping probes remain as a fallback.363
}364
}365
366
void schedule(Runnable runnable, long delay) throws Exception {367
Object scheduler = call(call(plugin, "getServer"), "getScheduler");368
Class<?> pluginInterface = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());369
call(scheduler, "runTaskLater", new Class<?>[]{pluginInterface, Runnable.class, long.class}, plugin, runnable, delay);370
}371
372
void callPlugin(String name) {373
try { call(plugin, name); } catch (Throwable ignored) {}374
}375
376
final class Group {377
final ContainerKey key;378
final List<ConnectionView> connections = new ArrayList<>();379
final List<ConnectionView> filtered = new ArrayList<>();380
final List<ConnectionView> unfiltered = new ArrayList<>();381
final EnumSet<Material> reserved = EnumSet.noneOf(Material.class);382
final Set<ContainerKey> destinationKeys = new HashSet<>();383
ItemStack[] sourceCache;384
int[] cycleBudget;385
final IdentityHashMap<Object, Boolean> usedConnections = new IdentityHashMap<>();386
boolean cacheDirty = true;387
int failed;388
389
Group(ContainerKey key) { this.key = key; }390
391
void rebuildCache() {392
for (ConnectionView connection : connections) {393
if (connection.filters.isEmpty()) unfiltered.add(connection);394
else {395
filtered.add(connection);396
reserved.addAll(connection.filters);397
}398
destinationKeys.add(endpointKey(connection.destination));399
}400
cacheDirty = true;401
}402
403
void prepareCycleBudget() {404
Inventory source = inventoryAt(connections.get(0).source);405
if (source == null || source instanceof FurnaceInventory) {406
cycleBudget = null;407
return;408
}409
if (cacheDirty || sourceCache == null) {410
ItemStack[] storage = source.getStorageContents();411
sourceCache = cloneContents(storage);412
cacheDirty = false;413
}414
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {415
cycleBudget = new int[sourceCache.length];416
}417
for (int slot = 0; slot < sourceCache.length; slot++) {418
ItemStack stack = sourceCache[slot];419
cycleBudget[slot] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();420
}421
}422
423
boolean slotMatchesRealInventory(Inventory source, int slot, ItemStack expected) {424
ItemStack actual = source.getItem(slot);425
if (expected == null || expected.getType().isAir()) {426
return actual == null || actual.getType().isAir();427
}428
if (actual == null || actual.getType().isAir()) return false;429
return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);430
}431
432
void rebuildSourceCacheNow(Inventory source) {433
ItemStack[] storage = source.getStorageContents();434
sourceCache = cloneContents(storage);435
cacheDirty = false;436
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {437
cycleBudget = new int[sourceCache.length];438
}439
for (int slot = 0; slot < sourceCache.length; slot++) {440
ItemStack stack = sourceCache[slot];441
cycleBudget[slot] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();442
}443
}444
445
boolean refreshRealInventoryIfChanged(Inventory source) {446
if (source instanceof FurnaceInventory) return false;447
ItemStack[] actual = source.getStorageContents();448
if (sourceCache == null || actual.length != sourceCache.length) {449
sourceCache = cloneContents(actual);450
cacheDirty = false;451
prepareCycleBudget();452
return true;453
}454
for (int slot = 0; slot < actual.length; slot++) {455
ItemStack expected = sourceCache[slot];456
ItemStack real = actual[slot];457
boolean same;458
if (expected == null || expected.getType().isAir()) {459
same = real == null || real.getType().isAir();460
} else {461
same = real != null && !real.getType().isAir()462
&& expected.getAmount() == real.getAmount()463
&& expected.isSimilar(real);464
}465
if (!same) {466
sourceCache = cloneContents(actual);467
cacheDirty = false;468
if (cycleBudget == null || cycleBudget.length != sourceCache.length) {469
cycleBudget = new int[sourceCache.length];470
}471
for (int i = 0; i < sourceCache.length; i++) {472
ItemStack stack = sourceCache[i];473
cycleBudget[i] = stack == null || stack.getType().isAir() ? 0 : stack.getAmount();474
}475
return true;476
}477
}478
return false;479
}480
481
RunResult run() {482
Inventory source = inventoryAt(connections.get(0).source);483
if (source == null) return RunResult.NO_MOVE;484
485
// Furnaces are special: only the output slot is a legal source.486
if (source instanceof FurnaceInventory furnace) {487
boolean moved = false;488
Set<Object> used = Collections.newSetFromMap(new IdentityHashMap<>());489
for (ConnectionView connection : filtered) {490
ItemStack output = furnace.getResult();491
if (used.contains(connection.raw) || !allowed(connection, output, true, reserved)) continue;492
TransferResult result = transferFurnaceOutput(connection, furnace, key);493
if (result.moved) { used.add(connection.raw); moved = true; }494
}495
for (ConnectionView connection : unfiltered) {496
ItemStack output = furnace.getResult();497
if (used.contains(connection.raw) || !allowed(connection, output, false, reserved)) continue;498
TransferResult result = transferFurnaceOutput(connection, furnace, key);499
if (result.moved) { used.add(connection.raw); moved = true; }500
}501
cacheDirty = true;502
return moved ? RunResult.MOVED : RunResult.NO_MOVE;503
}504
505
if (cycleBudget == null || cacheDirty || sourceCache == null) {506
prepareCycleBudget();507
}508
if (cycleBudget == null || sourceCache == null) return RunResult.NO_MOVE;509
510
usedConnections.clear();511
boolean moved = false;512
513
// Preserve vanilla-like first-slot preference: one ascending pass over514
// the source inventory services every outgoing connection at most once.515
for (int slot = 0; slot < sourceCache.length; slot++) {516
int availableAtCycleStart = cycleBudget[slot];517
if (availableAtCycleStart <= 0) continue;518
ItemStack stack = sourceCache[slot];519
if (stack == null || stack.getType().isAir() || stack.getAmount() <= 0) continue;520
521
// The cache is an optimisation, never an authority. A plugin may522
// have sorted/replaced this slot without emitting a Bukkit event.523
// Verify only the slot we are about to use; on mismatch rebuild524
// once from the real inventory and restart this group next cycle.525
if (!slotMatchesRealInventory(source, slot, stack)) {526
rebuildSourceCacheNow(source);527
failed = 0;528
return RunResult.STALE_CACHE;529
}530
531
Material type = stack.getType();532
533
for (ConnectionView connection : filtered) {534
if (stack == null || stack.getAmount() <= 0 || cycleBudget[slot] <= 0) break;535
if (usedConnections.containsKey(connection.raw) || !connection.filters.contains(type)) continue;536
TransferResult result = transferCached(connection, stack, cycleDestinations, key);537
if (!result.moved) continue;538
usedConnections.put(connection.raw, Boolean.TRUE);539
stack = decrementCachedSource(source, slot, stack);540
sourceCache[slot] = stack;541
cycleBudget[slot]--;542
moved = true;543
}544
545
if (!reserved.contains(type)) {546
for (ConnectionView connection : unfiltered) {547
if (stack == null || stack.getAmount() <= 0 || cycleBudget[slot] <= 0) break;548
if (usedConnections.containsKey(connection.raw)) continue;549
TransferResult result = transferCached(connection, stack, cycleDestinations, key);550
if (!result.moved) continue;551
usedConnections.put(connection.raw, Boolean.TRUE);552
stack = decrementCachedSource(source, slot, stack);553
sourceCache[slot] = stack;554
cycleBudget[slot]--;555
moved = true;556
}557
}558
}559
return moved ? RunResult.MOVED : RunResult.NO_MOVE;560
}561
}562
563
ItemStack[] cloneContents(ItemStack[] input) {564
ItemStack[] copy = new ItemStack[input.length];565
for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();566
return copy;567
}568
569
ItemStack decrementCachedSource(Inventory source, int slot, ItemStack cached) {570
if (cached.getAmount() <= 1) {571
source.setItem(slot, null);572
return null;573
}574
ItemStack reduced = cached.clone();575
reduced.setAmount(cached.getAmount() - 1);576
source.setItem(slot, reduced);577
return reduced;578
}579
580
TransferResult transferFurnaceOutput(ConnectionView connection, FurnaceInventory source, ContainerKey sourceKey) {581
ItemStack output = source.getResult();582
Inventory destination = inventoryAt(connection.destination);583
if (destination == null || output == null || output.getType().isAir()) return TransferResult.NO_MOVE;584
585
// Furnace output used to bypass cycleDestinations and write directly to586
// the Bukkit inventory. That left a destination source-group with a587
// stale slot cache, so freshly produced items could remain invisible to588
// its outgoing pipes until an unrelated event or topology refresh.589
// Route every internal insertion through the same DestinationState so590
// multiple incoming normal/furnace pipes share one authoritative591
// cycle-local view and downstream caches are updated transactionally.592
ContainerKey destinationKey = inventoryKey(destination);593
if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;594
DestinationState state = cycleDestinations.computeIfAbsent(destinationKey,595
ignored -> new DestinationState(destination));596
if (!state.insertOne(output)) return TransferResult.NO_MOVE;597
598
decrementFurnace(source);599
syncIncomingCache(destinationKey, state);600
afterTransfer(connection, source, destination);601
return new TransferResult(true, destinationKey);602
}603
604
TransferResult transferCached(ConnectionView connection, ItemStack source,605
Map<ContainerKey, DestinationState> destinations, ContainerKey sourceKey) {606
Inventory destination = inventoryAt(connection.destination);607
if (destination == null) return TransferResult.NO_MOVE;608
ContainerKey destinationKey = inventoryKey(destination);609
if (destinationKey == null || destinationKey.equals(sourceKey)) return TransferResult.NO_MOVE;610
DestinationState state = destinations.computeIfAbsent(destinationKey,611
ignored -> new DestinationState(destination));612
if (!state.insertOne(source)) return TransferResult.NO_MOVE;613
syncIncomingCache(destinationKey, state);614
afterTransfer(connection, null, destination);615
return new TransferResult(true, destinationKey);616
}617
618
void syncIncomingCache(ContainerKey destinationKey, DestinationState state) {619
Group destinationGroup = groups.get(destinationKey);620
if (destinationGroup != null && !(state.inventory instanceof FurnaceInventory)) {621
// DestinationState owns this cycle-local array. Reusing it avoids622
// cloning the entire destination after every inserted item.623
destinationGroup.sourceCache = state.storage;624
destinationGroup.cacheDirty = false;625
}626
wakeKeyInternal(destinationKey);627
}628
629
final class DestinationState {630
final Inventory inventory;631
ItemStack[] storage;632
633
DestinationState(Inventory inventory) {634
this.inventory = inventory;635
this.storage = inventory instanceof FurnaceInventory ? null : cloneContents(inventory.getStorageContents());636
}637
638
/**639
* Insert one item using the cached destination view, but validate the exact640
* real slot immediately before every write. If another plugin silently641
* changed/sorted the inventory, rebuild the full destination snapshot and642
* restart the search from slot 0 so first-slot/merge preference stays correct.643
*/644
boolean insertOne(ItemStack source) {645
// Crafters are destination-only and deliberately bypass the normal646
// destination slot cache. Query their live disabled-slot state and647
// use vanilla-equivalent hopper insertion ordering instead.648
if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {649
return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);650
}651
ItemStack one = source.clone();652
one.setAmount(1);653
654
// Furnace slots are never cached: read the real input/fuel slot for655
// every attempt, so external furnace mutations cannot be overwritten.656
if (inventory instanceof FurnaceInventory furnace) {657
ItemStack smelting = furnace.getSmelting();658
if (furnace.canSmelt(one) && canMerge(smelting, one, inventory.getMaxStackSize())) {659
// Re-read just before write. This is cheap and keeps the same660
// optimistic validation rule as normal container slots.661
ItemStack actual = furnace.getSmelting();662
if (!sameStackExact(smelting, actual)) return false;663
furnace.setSmelting(merge(actual, one));664
return true;665
}666
ItemStack fuel = furnace.getFuel();667
if (furnace.isFuel(one) && canMerge(fuel, one, inventory.getMaxStackSize())) {668
ItemStack actual = furnace.getFuel();669
if (!sameStackExact(fuel, actual)) return false;670
furnace.setFuel(merge(actual, one));671
return true;672
}673
return false;674
}675
676
// Normally attempt 0 succeeds with one getItem() validation. A second677
// pass is only needed after a detected stale destination cache.678
for (int attempt = 0; attempt < 2; attempt++) {679
boolean restart = false;680
681
// Minecraft-like preference: merge into the first compatible stack.682
for (int slot = 0; slot < storage.length; slot++) {683
ItemStack expected = storage[slot];684
if (expected == null || expected.getType().isAir() || !expected.isSimilar(one)685
|| expected.getAmount() >= Math.min(expected.getMaxStackSize(), inventory.getMaxStackSize())) {686
continue;687
}688
689
ItemStack actual = inventory.getItem(slot);690
if (!sameStackExact(expected, actual)) {691
refreshFromReal();692
restart = true;693
break;694
}695
696
ItemStack merged = actual.clone();697
merged.setAmount(actual.getAmount() + 1);698
inventory.setItem(slot, merged);699
storage[slot] = merged;700
return true;701
}702
if (restart) continue;703
704
// Otherwise use the first empty slot, validating that it is still705
// empty in the real inventory before writing to it.706
for (int slot = 0; slot < storage.length; slot++) {707
ItemStack expected = storage[slot];708
if (expected != null && !expected.getType().isAir()) continue;709
710
ItemStack actual = inventory.getItem(slot);711
if (!sameStackExact(expected, actual)) {712
refreshFromReal();713
restart = true;714
break;715
}716
717
ItemStack inserted = one.clone();718
inventory.setItem(slot, inserted);719
storage[slot] = inserted;720
return true;721
}722
if (!restart) return false;723
}724
725
// A destination that changes twice during one synchronous transfer726
// attempt is treated conservatively: do not overwrite anything.727
return false;728
}729
730
void refreshFromReal() {731
storage = cloneContents(inventory.getStorageContents());732
}733
}734
735
boolean allowed(ConnectionView connection, ItemStack item, boolean filtered, Set<Material> reserved) {736
if (item == null || item.getType().isAir() || item.getAmount() <= 0) return false;737
return filtered ? connection.filters.contains(item.getType()) : !reserved.contains(item.getType());738
}739
740
void afterTransfer(ConnectionView connection, Inventory source, Inventory destination) {741
ContainerKey sourceKey = source == null ? null : inventoryKey(source);742
ContainerKey destinationKey = inventoryKey(destination);743
if (sourceKey != null) wakeKeyInternal(sourceKey);744
if (destinationKey != null) wakeKeyInternal(destinationKey);745
746
int cooldown = Math.max(0, config().getInt("particles.transfer-animation-cooldown-ticks", 100));747
Long previous = lastParticleTick.get(connection.raw);748
if (previous == null || logicalTick - previous >= cooldown) {749
lastParticleTick.put(connection.raw, logicalTick);750
try { call(plugin, "animateTransfer", new Class<?>[]{connection.raw.getClass()}, connection.raw); }751
catch (Throwable ignored) {}752
}753
}754
755
Inventory inventoryAt(EndpointView endpoint) {756
World world = Bukkit.getWorld(endpoint.world);757
if (world == null || !world.isChunkLoaded(endpoint.x >> 4, endpoint.z >> 4)) return null;758
return inventoryOf(world.getBlockAt(endpoint.x, endpoint.y, endpoint.z));759
}760
761
Inventory inventoryOf(Block block) {762
BlockState state = block.getState();763
if (state instanceof Chest chest) return chest.getInventory();764
if (state instanceof Container container) return container.getInventory();765
return null;766
}767
768
ContainerKey endpointKey(EndpointView endpoint) {769
Inventory inventory = inventoryAt(endpoint);770
ContainerKey key = inventoryKey(inventory);771
return key != null ? key : new ContainerKey(endpoint.world, pack(endpoint.x, endpoint.y, endpoint.z));772
}773
774
ContainerKey inventoryKey(Inventory inventory) {775
if (inventory == null) return null;776
InventoryHolder holder = inventory.getHolder();777
if (holder instanceof DoubleChest doubleChest) {778
ContainerKey left = holderKey(doubleChest.getLeftSide());779
ContainerKey right = holderKey(doubleChest.getRightSide());780
if (left == null) return right;781
if (right == null) return left;782
int wc = left.world.compareTo(right.world);783
return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;784
}785
Location location = inventory.getLocation();786
if (location != null && location.getWorld() != null) {787
return new ContainerKey(location.getWorld().getUID(),788
pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));789
}790
return holderKey(holder);791
}792
793
ContainerKey holderKey(InventoryHolder holder) {794
if (holder instanceof BlockState state) {795
Block block = state.getBlock();796
return new ContainerKey(block.getWorld().getUID(), pack(block.getX(), block.getY(), block.getZ()));797
}798
return null;799
}800
}801
802
private enum RunResult { MOVED, NO_MOVE, STALE_CACHE }803
private record TransferResult(boolean moved, ContainerKey destinationKey) {804
static final TransferResult NO_MOVE = new TransferResult(false, null);805
}806
private record ContainerKey(UUID world, long packed) {}807
private record EndpointView(UUID world, int x, int y, int z) {}808
809
private static final class ConnectionView {810
final Object raw;811
final EndpointView source;812
final EndpointView destination;813
final EnumSet<Material> filters;814
815
ConnectionView(Object raw, EndpointView source, EndpointView destination, EnumSet<Material> filters) {816
this.raw = raw;817
this.source = source;818
this.destination = destination;819
this.filters = filters;820
}821
822
static ConnectionView read(Object raw) throws Exception {823
Object source = call(raw, "source");824
Object destination = call(raw, "destination");825
EndpointView sourceView = endpoint(source);826
EndpointView destinationView = endpoint(destination);827
EnumSet<Material> filters = EnumSet.noneOf(Material.class);828
for (Object value : (List<?>) call(raw, "filter")) {829
if (value instanceof ItemStack item && !item.getType().isAir()) filters.add(item.getType());830
}831
return new ConnectionView(raw, sourceView, destinationView, filters);832
}833
834
static EndpointView endpoint(Object endpoint) throws Exception {835
return new EndpointView((UUID) call(endpoint, "world"), (int) call(endpoint, "x"),836
(int) call(endpoint, "y"), (int) call(endpoint, "z"));837
}838
}839
840
private static boolean sameStackExact(ItemStack expected, ItemStack actual) {841
boolean expectedEmpty = expected == null || expected.getType().isAir();842
boolean actualEmpty = actual == null || actual.getType().isAir();843
if (expectedEmpty || actualEmpty) return expectedEmpty == actualEmpty;844
return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);845
}846
847
private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) {848
return existing == null || existing.getType().isAir()849
|| (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax));850
}851
852
private static ItemStack merge(ItemStack existing, ItemStack add) {853
if (existing == null || existing.getType().isAir()) return add.clone();854
ItemStack result = existing.clone();855
result.setAmount(existing.getAmount() + add.getAmount());856
return result;857
}858
859
private static void decrementFurnace(FurnaceInventory inventory) {860
ItemStack result = inventory.getResult();861
if (result == null) return;862
if (result.getAmount() <= 1) inventory.setResult(null);863
else {864
ItemStack reduced = result.clone();865
reduced.setAmount(result.getAmount() - 1);866
inventory.setResult(reduced);867
}868
}869
870
private static long pack(int x, int y, int z) {871
return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFFL);872
}873
874
private static Object field(Object target, String name) throws Exception {875
FieldKey key = new FieldKey(target.getClass(), name);876
Field field = FIELDS.get(key);877
if (field == null) {878
for (Class<?> type = target.getClass(); type != null; type = type.getSuperclass()) {879
try {880
field = type.getDeclaredField(name);881
field.setAccessible(true);882
FIELDS.put(key, field);883
break;884
} catch (NoSuchFieldException ignored) {}885
}886
}887
if (field == null) throw new NoSuchFieldException(name);888
return field.get(target);889
}890
891
private static Object call(Object target, String name, Object... arguments) throws Exception {892
return call(target, name, new Class<?>[0], arguments);893
}894
895
private static Object call(Object target, String name, Class<?>[] parameterTypes, Object... arguments) throws Exception {896
Method method = cachedMethod(target.getClass(), name, parameterTypes);897
return method.invoke(target, arguments);898
}899
900
private static Object invokeStatic(Class<?> owner, String name, Class<?>[] parameterTypes, Object... arguments) throws Exception {901
Method method = cachedMethod(owner, name, parameterTypes);902
return method.invoke(null, arguments);903
}904
905
private static Method cachedMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {906
MethodKey key = new MethodKey(owner, name, List.of(parameterTypes));907
Method method = METHODS.get(key);908
if (method != null) return method;909
method = findMethod(owner, name, parameterTypes);910
method.setAccessible(true);911
METHODS.put(key, method);912
return method;913
}914
915
private static Method findMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {916
for (Class<?> type = owner; type != null; type = type.getSuperclass()) {917
for (Method method : type.getDeclaredMethods()) {918
if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;919
}920
}921
for (Method method : owner.getMethods()) {922
if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;923
}924
throw new NoSuchMethodException(owner.getName() + "." + name);925
}926
927
private static boolean compatible(Class<?>[] actual, Class<?>[] requested) {928
if (actual.length != requested.length) return false;929
for (int index = 0; index < actual.length; index++) {930
if (!wrap(actual[index]).isAssignableFrom(wrap(requested[index]))) return false;931
}932
return true;933
}934
935
private static Class<?> wrap(Class<?> type) {936
if (!type.isPrimitive()) return type;937
if (type == int.class) return Integer.class;938
if (type == long.class) return Long.class;939
if (type == boolean.class) return Boolean.class;940
if (type == double.class) return Double.class;941
if (type == float.class) return Float.class;942
return type;943
}944
945
private static void log(Object plugin, String message, Throwable throwable) {946
try {947
Object logger = call(plugin, "getLogger");948
call(logger, "log", new Class<?>[]{java.util.logging.Level.class, String.class, Throwable.class},949
java.util.logging.Level.WARNING, message, throwable);950
} catch (Throwable ignored) {}951
}952
953
private record MethodKey(Class<?> owner, String name, List<Class<?>> parameters) {}954
private record FieldKey(Class<?> owner, String name) {}955
}@@ -0,0 +1,46 @@
1
package nl.timfalken.containerpipes;
2
3
import java.lang.reflect.*;
4
import java.util.*;
5
6
/** Coalesces frequent TSV writes while preserving a synchronous shutdown flush. */
7
public final class PersistenceDebouncer {
8
private PersistenceDebouncer() {}
9
private static final Map<Object, Object> PENDING = Collections.synchronizedMap(new WeakHashMap<>());
10
11
public static void request(Object plugin) {
12
try {
13
synchronized (PENDING) {
14
if (PENDING.containsKey(plugin)) return;
15
Object cfg = call(plugin, "getConfig");
16
long delay = Math.max(1L, ((Number) call(cfg, "getLong", new Class<?>[]{String.class,long.class}, "persistence.save-debounce-ticks", 20L)).longValue());
17
Runnable run = () -> {
18
synchronized (PENDING) { PENDING.remove(plugin); }
19
try { invoke(plugin, "saveConnectionsNow"); } catch (Throwable ignored) {}
20
};
21
Object scheduler = call(call(plugin, "getServer"), "getScheduler");
22
Class<?> pluginType = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());
23
Object task = call(scheduler, "runTaskLater", new Class<?>[]{pluginType,Runnable.class,long.class}, plugin, run, delay);
24
PENDING.put(plugin, task);
25
}
26
} catch (Throwable t) {
27
try { invoke(plugin, "saveConnectionsNow"); } catch (Throwable ignored) {}
28
}
29
}
30
31
public static void flush(Object plugin) {
32
try {
33
Object task;
34
synchronized (PENDING) { task = PENDING.remove(plugin); }
35
if (task != null) try { call(task, "cancel"); } catch (Throwable ignored) {}
36
invoke(plugin, "saveConnectionsNow");
37
} catch (Throwable ignored) {}
38
}
39
40
private static Object invoke(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}
41
private static Object call(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}
42
private static Object call(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}
43
private static Method find(Class<?> c,String n,Class<?>[]t)throws Exception{for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t))return m;for(Method m:c.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t))return m;throw new NoSuchMethodException(n);}
44
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}
45
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==long.class)return Long.class;if(c==int.class)return Integer.class;if(c==boolean.class)return Boolean.class;return c;}
46
}
@@ -0,0 +1,46 @@1
package nl.timfalken.containerpipes;2
3
import java.lang.reflect.*;4
import java.util.*;5
6
/** Coalesces frequent TSV writes while preserving a synchronous shutdown flush. */7
public final class PersistenceDebouncer {8
private PersistenceDebouncer() {}9
private static final Map<Object, Object> PENDING = Collections.synchronizedMap(new WeakHashMap<>());10
11
public static void request(Object plugin) {12
try {13
synchronized (PENDING) {14
if (PENDING.containsKey(plugin)) return;15
Object cfg = call(plugin, "getConfig");16
long delay = Math.max(1L, ((Number) call(cfg, "getLong", new Class<?>[]{String.class,long.class}, "persistence.save-debounce-ticks", 20L)).longValue());17
Runnable run = () -> {18
synchronized (PENDING) { PENDING.remove(plugin); }19
try { invoke(plugin, "saveConnectionsNow"); } catch (Throwable ignored) {}20
};21
Object scheduler = call(call(plugin, "getServer"), "getScheduler");22
Class<?> pluginType = Class.forName("org.bukkit.plugin.Plugin", false, plugin.getClass().getClassLoader());23
Object task = call(scheduler, "runTaskLater", new Class<?>[]{pluginType,Runnable.class,long.class}, plugin, run, delay);24
PENDING.put(plugin, task);25
}26
} catch (Throwable t) {27
try { invoke(plugin, "saveConnectionsNow"); } catch (Throwable ignored) {}28
}29
}30
31
public static void flush(Object plugin) {32
try {33
Object task;34
synchronized (PENDING) { task = PENDING.remove(plugin); }35
if (task != null) try { call(task, "cancel"); } catch (Throwable ignored) {}36
invoke(plugin, "saveConnectionsNow");37
} catch (Throwable ignored) {}38
}39
40
private static Object invoke(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}41
private static Object call(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}42
private static Object call(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}43
private static Method find(Class<?> c,String n,Class<?>[]t)throws Exception{for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t))return m;for(Method m:c.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t))return m;throw new NoSuchMethodException(n);}44
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}45
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==long.class)return Long.class;if(c==int.class)return Integer.class;if(c==boolean.class)return Boolean.class;return c;}46
}@@ -0,0 +1,155 @@
1
package nl.timfalken.containerpipes;
2
3
import java.lang.reflect.*;
4
import java.util.*;
5
6
/** Runtime compatibility helper: deliberately uses reflection so it does not bind to unstable API descriptors. */
7
public final class TransferPolicyPatch {
8
private TransferPolicyPatch() {}
9
10
public static void transferOne(Object plugin, Object connection) {
11
try {
12
Object sourceEp = call(connection, "source");
13
Object destEp = call(connection, "destination");
14
UUID worldId = (UUID) call(sourceEp, "world");
15
Object world = callStatic("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);
16
if (world == null) return;
17
int sx=(int)call(sourceEp,"x"), sy=(int)call(sourceEp,"y"), sz=(int)call(sourceEp,"z");
18
int dx=(int)call(destEp,"x"), dy=(int)call(destEp,"y"), dz=(int)call(destEp,"z");
19
if (!(boolean)call(world,"isChunkLoaded", new Class<?>[]{int.class,int.class}, sx>>4,sz>>4)) return;
20
if (!(boolean)call(world,"isChunkLoaded", new Class<?>[]{int.class,int.class}, dx>>4,dz>>4)) return;
21
Object sourceBlock=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},sx,sy,sz);
22
Object destBlock=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},dx,dy,dz);
23
Object source=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},sourceBlock);
24
Object dest=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},destBlock);
25
if(source==null||dest==null)return;
26
27
boolean filtered=(boolean)call(connection,"hasFilter");
28
List<Object> reserved=filtered?List.of():reservedItems(plugin,sourceEp,source);
29
30
if(isA(source,"org.bukkit.inventory.FurnaceInventory")){
31
Object out=call(source,"getResult");
32
if(validItem(out) && allowed(plugin,connection,out,filtered,reserved)){
33
Object single=one(out);
34
if((boolean)invokePrivate(plugin,"tryInsert",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),classFor("org.bukkit.inventory.ItemStack")},dest,single)){
35
invokePrivateStatic(plugin.getClass(),"decrementFurnaceResult",new Class<?>[]{classFor("org.bukkit.inventory.FurnaceInventory")},source);
36
invokePrivate(plugin,"animateTransfer",new Class<?>[]{connection.getClass()},connection);
37
}
38
}
39
return;
40
}
41
42
Object[] contents=(Object[])call(source,"getStorageContents");
43
for(int slot=0;slot<contents.length;slot++){
44
Object stack=contents[slot];
45
if(!validItem(stack))continue;
46
if(!allowed(plugin,connection,stack,filtered,reserved))continue;
47
Object single=one(stack);
48
if((boolean)invokePrivate(plugin,"tryInsert",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),classFor("org.bukkit.inventory.ItemStack")},dest,single)){
49
invokePrivateStatic(plugin.getClass(),"decrement",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),int.class,classFor("org.bukkit.inventory.ItemStack")},source,slot,stack);
50
invokePrivate(plugin,"animateTransfer",new Class<?>[]{connection.getClass()},connection);
51
return;
52
}
53
}
54
} catch (Throwable t) {
55
log(plugin,"Transfer planner failed",t);
56
}
57
}
58
59
public static void sanitizeFilterAndUpdate(Object plugin,long id,Object inventory){
60
try{
61
Object connections=getField(plugin,"connections");
62
Object old=call(connections,"get",new Class<?>[]{Object.class},id);
63
if(old==null)return;
64
Object destEp=call(old,"destination");
65
UUID worldId=(UUID)call(destEp,"world");
66
Object world=callStatic("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);
67
Object destInv=null;
68
if(world!=null){
69
int x=(int)call(destEp,"x"),y=(int)call(destEp,"y"),z=(int)call(destEp,"z");
70
if((boolean)call(world,"isChunkLoaded",new Class<?>[]{int.class,int.class},x>>4,z>>4)){
71
Object block=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},x,y,z);
72
destInv=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},block);
73
}
74
}
75
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory")){
76
for(int i=0;i<5;i++){
77
Object item=call(inventory,"getItem",new Class<?>[]{int.class},i);
78
if(!validItem(item))continue;
79
Object single=one(item);
80
boolean smelt=(boolean)call(destInv,"canSmelt",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},single);
81
boolean fuel=(boolean)call(destInv,"isFuel",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},single);
82
if(!smelt&&!fuel)call(inventory,"setItem",new Class<?>[]{int.class,classFor("org.bukkit.inventory.ItemStack")},i,null);
83
}
84
}
85
invokePrivate(plugin,"updateFilterOriginal",new Class<?>[]{long.class,classFor("org.bukkit.inventory.Inventory")},id,inventory);
86
// Updating a filter replaces the immutable Connection object while the
87
// connection count stays unchanged. Force the optimized planner to
88
// rebuild its cached filtered/unfiltered routing immediately.
89
OptimizedTransferPlanner.connectionChanged(plugin);
90
}catch(Throwable t){log(plugin,"Filter validation failed",t);}
91
}
92
93
private static boolean allowed(Object plugin,Object connection,Object item,boolean filtered,List<Object> reserved)throws Exception{
94
if(filtered)return (boolean)invokePrivate(plugin,"matchesFilter",new Class<?>[]{connection.getClass(),classFor("org.bukkit.inventory.ItemStack")},connection,one(item));
95
for(Object filter:reserved)if((boolean)call(filter,"isSimilar",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},item))return false;
96
return true;
97
}
98
99
private static List<Object> reservedItems(Object plugin,Object sourceEp,Object sourceInventory)throws Exception{
100
Object map=getField(plugin,"connections");
101
Collection<?> all=(Collection<?>)call(map,"values");
102
ArrayList<Object> result=new ArrayList<>();
103
for(Object c:all){
104
if(!(boolean)call(c,"hasFilter"))continue;
105
Object src=call(c,"source");
106
if(!samePhysicalContainer(plugin,sourceEp,sourceInventory,src))continue;
107
@SuppressWarnings("unchecked") List<Object> filters=(List<Object>)call(c,"filter");
108
for(Object f:filters)if(validItem(f))result.add(f);
109
}
110
return result;
111
}
112
113
/**
114
* Exact coordinates cover normal containers. For double chests, both block
115
* halves expose one logical inventory location; comparing that location
116
* groups pipes attached to either half without grouping adjacent barrels or
117
* unrelated single containers.
118
*/
119
private static boolean samePhysicalContainer(Object plugin,Object a,Object inventoryA,Object b)throws Exception{
120
if(!Objects.equals(call(a,"world"),call(b,"world")))return false;
121
if((int)call(a,"x")== (int)call(b,"x") && (int)call(a,"y")== (int)call(b,"y") && (int)call(a,"z")== (int)call(b,"z"))return true;
122
UUID worldId=(UUID)call(b,"world");
123
Object world=callStatic("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);
124
if(world==null)return false;
125
int bx=(int)call(b,"x"),by=(int)call(b,"y"),bz=(int)call(b,"z");
126
if(!(boolean)call(world,"isChunkLoaded",new Class<?>[]{int.class,int.class},bx>>4,bz>>4))return false;
127
Object blockB=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},bx,by,bz);
128
Object inventoryB=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},blockB);
129
if(inventoryB==null)return false;
130
Object locA=safeCall(inventoryA,"getLocation");
131
Object locB=safeCall(inventoryB,"getLocation");
132
return locA!=null && locA.equals(locB);
133
}
134
135
private static Object safeCall(Object o,String n){try{return call(o,n);}catch(Throwable ignored){return null;}}
136
private static boolean validItem(Object item)throws Exception{
137
if(item==null)return false; Object type=call(item,"getType"); return !(boolean)call(type,"isAir") && (int)call(item,"getAmount")>0;
138
}
139
private static Object one(Object item)throws Exception{Object c=call(item,"clone");call(c,"setAmount",new Class<?>[]{int.class},1);return c;}
140
private static boolean isA(Object o,String name)throws Exception{return classFor(name).isInstance(o);}
141
private static Class<?> classFor(String n)throws ClassNotFoundException{return Class.forName(n,false,TransferPolicyPatch.class.getClassLoader());}
142
private static Object getField(Object o,String n)throws Exception{Field f=o.getClass().getDeclaredField(n);f.setAccessible(true);return f.get(o);}
143
private static Object call(Object o,String n,Object...args)throws Exception{return call(o,n,new Class<?>[0],args);}
144
private static Object call(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
145
private static Object callStatic(String cn,String n,Class<?>[]types,Object...args)throws Exception{Class<?> c=classFor(cn);Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}
146
private static Object invokePrivate(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}
147
private static Object invokePrivateStatic(Class<?> c,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}
148
private static Method findMethod(Class<?> c,String n,Class<?>[]types)throws NoSuchMethodException{
149
for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;
150
throw new NoSuchMethodException(c.getName()+"."+n+Arrays.toString(types));
151
}
152
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}
153
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;return c;}
154
private static void log(Object plugin,String msg,Throwable t){try{Object l=call(plugin,"getLogger");call(l,"log",new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},java.util.logging.Level.WARNING,msg,t);}catch(Throwable ignored){}}
155
}
@@ -0,0 +1,155 @@1
package nl.timfalken.containerpipes;2
3
import java.lang.reflect.*;4
import java.util.*;5
6
/** Runtime compatibility helper: deliberately uses reflection so it does not bind to unstable API descriptors. */7
public final class TransferPolicyPatch {8
private TransferPolicyPatch() {}9
10
public static void transferOne(Object plugin, Object connection) {11
try {12
Object sourceEp = call(connection, "source");13
Object destEp = call(connection, "destination");14
UUID worldId = (UUID) call(sourceEp, "world");15
Object world = callStatic("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);16
if (world == null) return;17
int sx=(int)call(sourceEp,"x"), sy=(int)call(sourceEp,"y"), sz=(int)call(sourceEp,"z");18
int dx=(int)call(destEp,"x"), dy=(int)call(destEp,"y"), dz=(int)call(destEp,"z");19
if (!(boolean)call(world,"isChunkLoaded", new Class<?>[]{int.class,int.class}, sx>>4,sz>>4)) return;20
if (!(boolean)call(world,"isChunkLoaded", new Class<?>[]{int.class,int.class}, dx>>4,dz>>4)) return;21
Object sourceBlock=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},sx,sy,sz);22
Object destBlock=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},dx,dy,dz);23
Object source=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},sourceBlock);24
Object dest=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},destBlock);25
if(source==null||dest==null)return;26
27
boolean filtered=(boolean)call(connection,"hasFilter");28
List<Object> reserved=filtered?List.of():reservedItems(plugin,sourceEp,source);29
30
if(isA(source,"org.bukkit.inventory.FurnaceInventory")){31
Object out=call(source,"getResult");32
if(validItem(out) && allowed(plugin,connection,out,filtered,reserved)){33
Object single=one(out);34
if((boolean)invokePrivate(plugin,"tryInsert",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),classFor("org.bukkit.inventory.ItemStack")},dest,single)){35
invokePrivateStatic(plugin.getClass(),"decrementFurnaceResult",new Class<?>[]{classFor("org.bukkit.inventory.FurnaceInventory")},source);36
invokePrivate(plugin,"animateTransfer",new Class<?>[]{connection.getClass()},connection);37
}38
}39
return;40
}41
42
Object[] contents=(Object[])call(source,"getStorageContents");43
for(int slot=0;slot<contents.length;slot++){44
Object stack=contents[slot];45
if(!validItem(stack))continue;46
if(!allowed(plugin,connection,stack,filtered,reserved))continue;47
Object single=one(stack);48
if((boolean)invokePrivate(plugin,"tryInsert",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),classFor("org.bukkit.inventory.ItemStack")},dest,single)){49
invokePrivateStatic(plugin.getClass(),"decrement",new Class<?>[]{classFor("org.bukkit.inventory.Inventory"),int.class,classFor("org.bukkit.inventory.ItemStack")},source,slot,stack);50
invokePrivate(plugin,"animateTransfer",new Class<?>[]{connection.getClass()},connection);51
return;52
}53
}54
} catch (Throwable t) {55
log(plugin,"Transfer planner failed",t);56
}57
}58
59
public static void sanitizeFilterAndUpdate(Object plugin,long id,Object inventory){60
try{61
Object connections=getField(plugin,"connections");62
Object old=call(connections,"get",new Class<?>[]{Object.class},id);63
if(old==null)return;64
Object destEp=call(old,"destination");65
UUID worldId=(UUID)call(destEp,"world");66
Object world=callStatic("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);67
Object destInv=null;68
if(world!=null){69
int x=(int)call(destEp,"x"),y=(int)call(destEp,"y"),z=(int)call(destEp,"z");70
if((boolean)call(world,"isChunkLoaded",new Class<?>[]{int.class,int.class},x>>4,z>>4)){71
Object block=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},x,y,z);72
destInv=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},block);73
}74
}75
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory")){76
for(int i=0;i<5;i++){77
Object item=call(inventory,"getItem",new Class<?>[]{int.class},i);78
if(!validItem(item))continue;79
Object single=one(item);80
boolean smelt=(boolean)call(destInv,"canSmelt",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},single);81
boolean fuel=(boolean)call(destInv,"isFuel",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},single);82
if(!smelt&&!fuel)call(inventory,"setItem",new Class<?>[]{int.class,classFor("org.bukkit.inventory.ItemStack")},i,null);83
}84
}85
invokePrivate(plugin,"updateFilterOriginal",new Class<?>[]{long.class,classFor("org.bukkit.inventory.Inventory")},id,inventory);86
// Updating a filter replaces the immutable Connection object while the87
// connection count stays unchanged. Force the optimized planner to88
// rebuild its cached filtered/unfiltered routing immediately.89
OptimizedTransferPlanner.connectionChanged(plugin);90
}catch(Throwable t){log(plugin,"Filter validation failed",t);}91
}92
93
private static boolean allowed(Object plugin,Object connection,Object item,boolean filtered,List<Object> reserved)throws Exception{94
if(filtered)return (boolean)invokePrivate(plugin,"matchesFilter",new Class<?>[]{connection.getClass(),classFor("org.bukkit.inventory.ItemStack")},connection,one(item));95
for(Object filter:reserved)if((boolean)call(filter,"isSimilar",new Class<?>[]{classFor("org.bukkit.inventory.ItemStack")},item))return false;96
return true;97
}98
99
private static List<Object> reservedItems(Object plugin,Object sourceEp,Object sourceInventory)throws Exception{100
Object map=getField(plugin,"connections");101
Collection<?> all=(Collection<?>)call(map,"values");102
ArrayList<Object> result=new ArrayList<>();103
for(Object c:all){104
if(!(boolean)call(c,"hasFilter"))continue;105
Object src=call(c,"source");106
if(!samePhysicalContainer(plugin,sourceEp,sourceInventory,src))continue;107
@SuppressWarnings("unchecked") List<Object> filters=(List<Object>)call(c,"filter");108
for(Object f:filters)if(validItem(f))result.add(f);109
}110
return result;111
}112
113
/**114
* Exact coordinates cover normal containers. For double chests, both block115
* halves expose one logical inventory location; comparing that location116
* groups pipes attached to either half without grouping adjacent barrels or117
* unrelated single containers.118
*/119
private static boolean samePhysicalContainer(Object plugin,Object a,Object inventoryA,Object b)throws Exception{120
if(!Objects.equals(call(a,"world"),call(b,"world")))return false;121
if((int)call(a,"x")== (int)call(b,"x") && (int)call(a,"y")== (int)call(b,"y") && (int)call(a,"z")== (int)call(b,"z"))return true;122
UUID worldId=(UUID)call(b,"world");123
Object world=callStatic("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);124
if(world==null)return false;125
int bx=(int)call(b,"x"),by=(int)call(b,"y"),bz=(int)call(b,"z");126
if(!(boolean)call(world,"isChunkLoaded",new Class<?>[]{int.class,int.class},bx>>4,bz>>4))return false;127
Object blockB=call(world,"getBlockAt",new Class<?>[]{int.class,int.class,int.class},bx,by,bz);128
Object inventoryB=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},blockB);129
if(inventoryB==null)return false;130
Object locA=safeCall(inventoryA,"getLocation");131
Object locB=safeCall(inventoryB,"getLocation");132
return locA!=null && locA.equals(locB);133
}134
135
private static Object safeCall(Object o,String n){try{return call(o,n);}catch(Throwable ignored){return null;}}136
private static boolean validItem(Object item)throws Exception{137
if(item==null)return false; Object type=call(item,"getType"); return !(boolean)call(type,"isAir") && (int)call(item,"getAmount")>0;138
}139
private static Object one(Object item)throws Exception{Object c=call(item,"clone");call(c,"setAmount",new Class<?>[]{int.class},1);return c;}140
private static boolean isA(Object o,String name)throws Exception{return classFor(name).isInstance(o);}141
private static Class<?> classFor(String n)throws ClassNotFoundException{return Class.forName(n,false,TransferPolicyPatch.class.getClassLoader());}142
private static Object getField(Object o,String n)throws Exception{Field f=o.getClass().getDeclaredField(n);f.setAccessible(true);return f.get(o);}143
private static Object call(Object o,String n,Object...args)throws Exception{return call(o,n,new Class<?>[0],args);}144
private static Object call(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}145
private static Object callStatic(String cn,String n,Class<?>[]types,Object...args)throws Exception{Class<?> c=classFor(cn);Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}146
private static Object invokePrivate(Object o,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(o.getClass(),n,types);m.setAccessible(true);return m.invoke(o,args);}147
private static Object invokePrivateStatic(Class<?> c,String n,Class<?>[]types,Object...args)throws Exception{Method m=findMethod(c,n,types);m.setAccessible(true);return m.invoke(null,args);}148
private static Method findMethod(Class<?> c,String n,Class<?>[]types)throws NoSuchMethodException{149
for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),types))return m;150
throw new NoSuchMethodException(c.getName()+"."+n+Arrays.toString(types));151
}152
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}153
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;return c;}154
private static void log(Object plugin,String msg,Throwable t){try{Object l=call(plugin,"getLogger");call(l,"log",new Class<?>[]{java.util.logging.Level.class,String.class,Throwable.class},java.util.logging.Level.WARNING,msg,t);}catch(Throwable ignored){}}155
}@@ -0,0 +1,110 @@
1
package nl.timfalken.containerpipes;
2
3
import java.lang.reflect.*;
4
import java.util.*;
5
import java.util.concurrent.ConcurrentHashMap;
6
7
/** Manages display radius and interaction hitbox density without retaining Bukkit objects. */
8
public final class VisualPerformanceManager {
9
private VisualPerformanceManager() {}
10
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
11
private static final Map<String, Method> METHODS = new ConcurrentHashMap<>();
12
13
public static void markDirty(Object plugin) { STATES.computeIfAbsent(plugin, p -> new State()).dirty = true; }
14
15
public static void tick(Object plugin) {
16
try {
17
State state=STATES.computeIfAbsent(plugin,p->new State());
18
if(!state.dirty && ++state.counter < state.refreshEvery) return;
19
state.counter=0; state.dirty=false;
20
Object cfg=call(plugin,"getConfig");
21
state.refreshEvery=Math.max(1,intCfg(cfg,"visuals.refresh-cycles",5));
22
int radiusChunks=Math.max(0,intCfg(cfg,"visuals.player-tracking-radius-chunks",5));
23
int hitEvery=Math.max(1,intCfg(cfg,"interaction.hitbox-every-segments",3));
24
boolean unloadFar=boolCfg(cfg,"visuals.unload-when-no-player-nearby",true);
25
manage(plugin,radiusChunks,hitEvery,unloadFar);
26
} catch(Throwable ignored){}
27
}
28
29
public static boolean hasPlayerNearConnection(Object plugin,Object connection,int radius) {
30
try {
31
Object source=call(connection,"source"); UUID worldId=(UUID)call(source,"world");
32
Object world=staticCall("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);
33
if(world==null)return false;
34
double x=(int)call(source,"x")+0.5,y=(int)call(source,"y")+0.5,z=(int)call(source,"z")+0.5;
35
double max=(double)radius*radius;
36
for(Object player:(Collection<?>)call(world,"getPlayers")){
37
Object loc=call(player,"getLocation");double dx=(double)call(loc,"getX")-x,dy=(double)call(loc,"getY")-y,dz=(double)call(loc,"getZ")-z;
38
if(dx*dx+dy*dy+dz*dz<=max)return true;
39
}
40
}catch(Throwable ignored){}
41
return false;
42
}
43
44
private static void manage(Object plugin,int radiusChunks,int hitEvery,boolean unloadFar)throws Exception{
45
Map<?,?> connections=(Map<?,?>)field(plugin,"connections");
46
Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");
47
Set<Long> near=new HashSet<>();
48
for(Object connection:connections.values())if(isNearPlayer(connection,radiusChunks))near.add(((Number)call(connection,"id")).longValue());
49
if(unloadFar){
50
for(Object idObj:new ArrayList<>(displayIds.keySet())){
51
long id=((Number)idObj).longValue();
52
if(!near.contains(id))invoke(plugin,"removeDisplays",new Class<?>[]{long.class},id);
53
}
54
}
55
for(Object connection:connections.values()){
56
long id=((Number)call(connection,"id")).longValue();
57
if(near.contains(id)&&!displayIds.containsKey(id))invoke(plugin,"spawnDisplays",new Class<?>[]{connection.getClass()},connection);
58
}
59
thinInteractions(plugin,hitEvery);
60
}
61
62
private static boolean isNearPlayer(Object connection,int radiusChunks)throws Exception{
63
Object source=call(connection,"source");UUID worldId=(UUID)call(source,"world");Object world=staticCall("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);if(world==null)return false;
64
int sx=(int)call(source,"x")>>4,sz=(int)call(source,"z")>>4;
65
Object destination=call(connection,"destination");int dx=(int)call(destination,"x")>>4,dz=(int)call(destination,"z")>>4;
66
for(Object player:(Collection<?>)call(world,"getPlayers")){
67
Object loc=call(player,"getLocation");int px=(int)call(loc,"getBlockX")>>4,pz=(int)call(loc,"getBlockZ")>>4;
68
if(Math.max(Math.abs(px-sx),Math.abs(pz-sz))<=radiusChunks||Math.max(Math.abs(px-dx),Math.abs(pz-dz))<=radiusChunks)return true;
69
}
70
return false;
71
}
72
73
private static void thinInteractions(Object plugin,int every)throws Exception{
74
// Only inspect entities owned by ContainerPipes. The previous implementation
75
// scanned and sorted every entity in every world, which caused periodic MSPT
76
// spikes in mob-heavy worlds.
77
Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");
78
for(Object entryObj:displayIds.entrySet()){
79
Map.Entry<?,?> entry=(Map.Entry<?,?>)entryObj;
80
Object idObj=entry.getKey();
81
long connectionId=((Number)idObj).longValue();
82
List<?> uuids=(List<?>)entry.getValue();
83
ArrayList<Object> interactions=new ArrayList<>();
84
for(Object uuidObj:uuids){
85
if(!(uuidObj instanceof UUID uuid))continue;
86
Object entity=staticCall("org.bukkit.Bukkit","getEntity",new Class<?>[]{UUID.class},uuid);
87
if(entity==null)continue;
88
Set<?> tags=(Set<?>)call(entity,"getScoreboardTags");
89
if(tags.contains("containerpipes-filter:"+connectionId))interactions.add(entity);
90
}
91
interactions.sort(Comparator.comparingDouble(VisualPerformanceManager::entitySortKey));
92
for(int i=0;i<interactions.size();i++){
93
if(i!=0&&i!=interactions.size()-1&&i%every!=0)call(interactions.get(i),"remove");
94
}
95
}
96
}
97
98
private static double entitySortKey(Object e){try{Object l=call(e,"getLocation");return (double)call(l,"getX")*31+(double)call(l,"getY")*17+(double)call(l,"getZ");}catch(Throwable t){return 0;}}
99
private static final class State{boolean dirty=true;int counter;int refreshEvery=5;}
100
private static boolean boolCfg(Object cfg,String p,boolean d){try{return (boolean)call(cfg,"getBoolean",new Class<?>[]{String.class,boolean.class},p,d);}catch(Throwable t){return d;}}
101
private static int intCfg(Object cfg,String p,int d){try{return (int)call(cfg,"getInt",new Class<?>[]{String.class,int.class},p,d);}catch(Throwable t){return d;}}
102
private static Object field(Object o,String n)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);return f.get(o);}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}
103
private static Object invoke(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}
104
private static Object call(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}
105
private static Object call(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}
106
private static Object staticCall(String c,String n,Class<?>[]t,Object...a)throws Exception{Class<?> k=Class.forName(c,false,VisualPerformanceManager.class.getClassLoader());Method m=find(k,n,t);m.setAccessible(true);return m.invoke(null,a);}
107
private static Method find(Class<?> c,String n,Class<?>[]t)throws Exception{String key=c.getName()+"#"+n+Arrays.toString(t);Method cached=METHODS.get(key);if(cached!=null)return cached;for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t)){METHODS.put(key,m);return m;}for(Method m:c.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t)){METHODS.put(key,m);return m;}throw new NoSuchMethodException(key);}
108
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}
109
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;if(c==double.class)return Double.class;if(c==float.class)return Float.class;return c;}
110
}
@@ -0,0 +1,110 @@1
package nl.timfalken.containerpipes;2
3
import java.lang.reflect.*;4
import java.util.*;5
import java.util.concurrent.ConcurrentHashMap;6
7
/** Manages display radius and interaction hitbox density without retaining Bukkit objects. */8
public final class VisualPerformanceManager {9
private VisualPerformanceManager() {}10
private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());11
private static final Map<String, Method> METHODS = new ConcurrentHashMap<>();12
13
public static void markDirty(Object plugin) { STATES.computeIfAbsent(plugin, p -> new State()).dirty = true; }14
15
public static void tick(Object plugin) {16
try {17
State state=STATES.computeIfAbsent(plugin,p->new State());18
if(!state.dirty && ++state.counter < state.refreshEvery) return;19
state.counter=0; state.dirty=false;20
Object cfg=call(plugin,"getConfig");21
state.refreshEvery=Math.max(1,intCfg(cfg,"visuals.refresh-cycles",5));22
int radiusChunks=Math.max(0,intCfg(cfg,"visuals.player-tracking-radius-chunks",5));23
int hitEvery=Math.max(1,intCfg(cfg,"interaction.hitbox-every-segments",3));24
boolean unloadFar=boolCfg(cfg,"visuals.unload-when-no-player-nearby",true);25
manage(plugin,radiusChunks,hitEvery,unloadFar);26
} catch(Throwable ignored){}27
}28
29
public static boolean hasPlayerNearConnection(Object plugin,Object connection,int radius) {30
try {31
Object source=call(connection,"source"); UUID worldId=(UUID)call(source,"world");32
Object world=staticCall("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);33
if(world==null)return false;34
double x=(int)call(source,"x")+0.5,y=(int)call(source,"y")+0.5,z=(int)call(source,"z")+0.5;35
double max=(double)radius*radius;36
for(Object player:(Collection<?>)call(world,"getPlayers")){37
Object loc=call(player,"getLocation");double dx=(double)call(loc,"getX")-x,dy=(double)call(loc,"getY")-y,dz=(double)call(loc,"getZ")-z;38
if(dx*dx+dy*dy+dz*dz<=max)return true;39
}40
}catch(Throwable ignored){}41
return false;42
}43
44
private static void manage(Object plugin,int radiusChunks,int hitEvery,boolean unloadFar)throws Exception{45
Map<?,?> connections=(Map<?,?>)field(plugin,"connections");46
Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");47
Set<Long> near=new HashSet<>();48
for(Object connection:connections.values())if(isNearPlayer(connection,radiusChunks))near.add(((Number)call(connection,"id")).longValue());49
if(unloadFar){50
for(Object idObj:new ArrayList<>(displayIds.keySet())){51
long id=((Number)idObj).longValue();52
if(!near.contains(id))invoke(plugin,"removeDisplays",new Class<?>[]{long.class},id);53
}54
}55
for(Object connection:connections.values()){56
long id=((Number)call(connection,"id")).longValue();57
if(near.contains(id)&&!displayIds.containsKey(id))invoke(plugin,"spawnDisplays",new Class<?>[]{connection.getClass()},connection);58
}59
thinInteractions(plugin,hitEvery);60
}61
62
private static boolean isNearPlayer(Object connection,int radiusChunks)throws Exception{63
Object source=call(connection,"source");UUID worldId=(UUID)call(source,"world");Object world=staticCall("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);if(world==null)return false;64
int sx=(int)call(source,"x")>>4,sz=(int)call(source,"z")>>4;65
Object destination=call(connection,"destination");int dx=(int)call(destination,"x")>>4,dz=(int)call(destination,"z")>>4;66
for(Object player:(Collection<?>)call(world,"getPlayers")){67
Object loc=call(player,"getLocation");int px=(int)call(loc,"getBlockX")>>4,pz=(int)call(loc,"getBlockZ")>>4;68
if(Math.max(Math.abs(px-sx),Math.abs(pz-sz))<=radiusChunks||Math.max(Math.abs(px-dx),Math.abs(pz-dz))<=radiusChunks)return true;69
}70
return false;71
}72
73
private static void thinInteractions(Object plugin,int every)throws Exception{74
// Only inspect entities owned by ContainerPipes. The previous implementation75
// scanned and sorted every entity in every world, which caused periodic MSPT76
// spikes in mob-heavy worlds.77
Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");78
for(Object entryObj:displayIds.entrySet()){79
Map.Entry<?,?> entry=(Map.Entry<?,?>)entryObj;80
Object idObj=entry.getKey();81
long connectionId=((Number)idObj).longValue();82
List<?> uuids=(List<?>)entry.getValue();83
ArrayList<Object> interactions=new ArrayList<>();84
for(Object uuidObj:uuids){85
if(!(uuidObj instanceof UUID uuid))continue;86
Object entity=staticCall("org.bukkit.Bukkit","getEntity",new Class<?>[]{UUID.class},uuid);87
if(entity==null)continue;88
Set<?> tags=(Set<?>)call(entity,"getScoreboardTags");89
if(tags.contains("containerpipes-filter:"+connectionId))interactions.add(entity);90
}91
interactions.sort(Comparator.comparingDouble(VisualPerformanceManager::entitySortKey));92
for(int i=0;i<interactions.size();i++){93
if(i!=0&&i!=interactions.size()-1&&i%every!=0)call(interactions.get(i),"remove");94
}95
}96
}97
98
private static double entitySortKey(Object e){try{Object l=call(e,"getLocation");return (double)call(l,"getX")*31+(double)call(l,"getY")*17+(double)call(l,"getZ");}catch(Throwable t){return 0;}}99
private static final class State{boolean dirty=true;int counter;int refreshEvery=5;}100
private static boolean boolCfg(Object cfg,String p,boolean d){try{return (boolean)call(cfg,"getBoolean",new Class<?>[]{String.class,boolean.class},p,d);}catch(Throwable t){return d;}}101
private static int intCfg(Object cfg,String p,int d){try{return (int)call(cfg,"getInt",new Class<?>[]{String.class,int.class},p,d);}catch(Throwable t){return d;}}102
private static Object field(Object o,String n)throws Exception{for(Class<?> c=o.getClass();c!=null;c=c.getSuperclass())try{Field f=c.getDeclaredField(n);f.setAccessible(true);return f.get(o);}catch(NoSuchFieldException ignored){}throw new NoSuchFieldException(n);}103
private static Object invoke(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}104
private static Object call(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}105
private static Object call(Object o,String n,Class<?>[]t,Object...a)throws Exception{Method m=find(o.getClass(),n,t);m.setAccessible(true);return m.invoke(o,a);}106
private static Object staticCall(String c,String n,Class<?>[]t,Object...a)throws Exception{Class<?> k=Class.forName(c,false,VisualPerformanceManager.class.getClassLoader());Method m=find(k,n,t);m.setAccessible(true);return m.invoke(null,a);}107
private static Method find(Class<?> c,String n,Class<?>[]t)throws Exception{String key=c.getName()+"#"+n+Arrays.toString(t);Method cached=METHODS.get(key);if(cached!=null)return cached;for(Class<?> k=c;k!=null;k=k.getSuperclass())for(Method m:k.getDeclaredMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t)){METHODS.put(key,m);return m;}for(Method m:c.getMethods())if(m.getName().equals(n)&&compatible(m.getParameterTypes(),t)){METHODS.put(key,m);return m;}throw new NoSuchMethodException(key);}108
private static boolean compatible(Class<?>[]a,Class<?>[]b){if(a.length!=b.length)return false;for(int i=0;i<a.length;i++)if(!wrap(a[i]).isAssignableFrom(wrap(b[i])))return false;return true;}109
private static Class<?> wrap(Class<?> c){if(!c.isPrimitive())return c;if(c==int.class)return Integer.class;if(c==long.class)return Long.class;if(c==boolean.class)return Boolean.class;if(c==double.class)return Double.class;if(c==float.class)return Float.class;return c;}110
}@@ -0,0 +1,115 @@
1
# One item per connection per interval.
2
transfer-interval-ticks: 3
3
4
# Maximum distance between the two clicked containers.
5
maximum-connection-range: 32
6
7
# Only main-hand container interactions are processed. This debounce catches
8
# duplicate interactions within the same client tick.
9
interaction-debounce-millis: 100
10
11
# Material used for visual pipe segments.
12
pipe-material: minecraft:iron_block
13
14
# Diameter of normal visual pipe segments, as a fraction of one block.
15
pipe-scale: 0.25
16
17
# Separate scale for source and destination connectors.
18
source-endpoint-scale: 0.45
19
destination-endpoint-scale: 0.40
20
21
# Distance between the centres of consecutive visual segments.
22
segment-spacing: 0.333333
23
24
# Periodic endpoint validation interval.
25
validation-interval-ticks: 400
26
27
# Source connector material while a filter is active.
28
filtered-source-material: minecraft:copper_block
29
30
# Green feedback while a player is choosing the destination.
31
selection-particle-count: 12
32
selection-timeout-seconds: 30
33
34
# Moving particle shown after a successful transfer.
35
transfer-particle-spacing: 0.25
36
transfer-particle-step-ticks: 3
37
transfer-particle-points-per-step: 2
38
39
filter-title:
40
nl: 'Buisfilter #{id}'
41
en: 'Pipe filter #{id}'
42
43
messages:
44
nl:
45
selected-source: '<green>Bronzijde gekozen. Shift-klik met lege hand op de bestemmingscontainer.</green>'
46
selection-cancelled: '<yellow>Selectie geannuleerd.</yellow>'
47
connected: '<green>Containers verbonden.</green>'
48
disconnected: '<yellow>Verbinding verwijderd.</yellow>'
49
side-in-use: '<red>Deze containerzijde heeft al een verbinding.</red>'
50
too-far: '<red>De bestemming ligt buiten het toegestane bereik.</red>'
51
no-route: '<red>Er is geen vrije buisroute gevonden.</red>'
52
invalid-container: '<red>Dit containertype wordt niet ondersteund.</red>'
53
different-world: '<red>Beide containers moeten in dezelfde wereld staan.</red>'
54
en:
55
selected-source: '<green>Source side selected. Shift-click the destination container with an empty hand.</green>'
56
selection-cancelled: '<yellow>Selection cancelled.</yellow>'
57
connected: '<green>Containers connected.</green>'
58
disconnected: '<yellow>Connection removed.</yellow>'
59
side-in-use: '<red>This container side already has a connection.</red>'
60
too-far: '<red>The destination is outside the allowed range.</red>'
61
no-route: '<red>No unobstructed pipe route could be found.</red>'
62
invalid-container: '<red>This container type is not supported.</red>'
63
different-world: '<red>Both containers must be in the same world.</red>'
64
65
commands:
66
nl:
67
status: 'ContainerPipes: {connections} verbinding(en), {segments} displaysegmenten.'
68
reloaded: 'ContainerPipes herladen.'
69
refreshed: 'Alle geladen buizen vernieuwd.'
70
usage: 'Gebruik: /containerpipes <status|reload|refresh>'
71
en:
72
status: 'ContainerPipes: {connections} connection(s), {segments} display segment(s).'
73
reloaded: 'ContainerPipes reloaded.'
74
refreshed: 'All loaded pipes refreshed.'
75
usage: 'Usage: /containerpipes <status|reload|refresh>'
76
77
# Transfer performance. Active source groups run at the normal interval;
78
# idle groups sleep and are woken immediately by inventory/chunk events.
79
performance:
80
active-interval-ticks: 3
81
idle-after-failed-attempts: 3
82
sleeping-probe-interval-ticks: 200
83
84
# Retry temporarily full/blocked destinations sooner than fully idle sources.
85
blocked-retry-interval-ticks: 20
86
87
# Sleeping groups are probed in small batches to avoid a single spike.
88
sleeping-probe-batch-size: 10
89
sleeping-probe-batch-interval-ticks: 5
90
91
92
# Verdere performance-optimalisaties.
93
interaction:
94
# Slechts ieder N-de buissegment krijgt een klikbare Interaction-hitbox.
95
# Bron- en eindsegment blijven altijd klikbaar.
96
hitbox-every-segments: 3
97
98
visuals:
99
# Visuele BlockDisplays en hitboxes bestaan alleen binnen deze afstand van spelers.
100
player-tracking-radius-chunks: 5
101
unload-when-no-player-nearby: true
102
refresh-interval-ticks: 20
103
refresh-cycles: 5
104
105
particles:
106
# Per connection, show at most one transfer animation within this interval.
107
transfer-animation-cooldown-ticks: 100
108
109
maximum-active-animations: 20
110
only-show-within-blocks: 48
111
animation-budget-release-ticks: 40
112
113
persistence:
114
# Bundel snelle opeenvolgende wijzigingen tot één veilige TSV-write.
115
save-debounce-ticks: 20
@@ -0,0 +1,115 @@1
# One item per connection per interval.2
transfer-interval-ticks: 33
4
# Maximum distance between the two clicked containers.5
maximum-connection-range: 326
7
# Only main-hand container interactions are processed. This debounce catches8
# duplicate interactions within the same client tick.9
interaction-debounce-millis: 10010
11
# Material used for visual pipe segments.12
pipe-material: minecraft:iron_block13
14
# Diameter of normal visual pipe segments, as a fraction of one block.15
pipe-scale: 0.2516
17
# Separate scale for source and destination connectors.18
source-endpoint-scale: 0.4519
destination-endpoint-scale: 0.4020
21
# Distance between the centres of consecutive visual segments.22
segment-spacing: 0.33333323
24
# Periodic endpoint validation interval.25
validation-interval-ticks: 40026
27
# Source connector material while a filter is active.28
filtered-source-material: minecraft:copper_block29
30
# Green feedback while a player is choosing the destination.31
selection-particle-count: 1232
selection-timeout-seconds: 3033
34
# Moving particle shown after a successful transfer.35
transfer-particle-spacing: 0.2536
transfer-particle-step-ticks: 337
transfer-particle-points-per-step: 238
39
filter-title:40
nl: 'Buisfilter #{id}'41
en: 'Pipe filter #{id}'42
43
messages:44
nl:45
selected-source: '<green>Bronzijde gekozen. Shift-klik met lege hand op de bestemmingscontainer.</green>'46
selection-cancelled: '<yellow>Selectie geannuleerd.</yellow>'47
connected: '<green>Containers verbonden.</green>'48
disconnected: '<yellow>Verbinding verwijderd.</yellow>'49
side-in-use: '<red>Deze containerzijde heeft al een verbinding.</red>'50
too-far: '<red>De bestemming ligt buiten het toegestane bereik.</red>'51
no-route: '<red>Er is geen vrije buisroute gevonden.</red>'52
invalid-container: '<red>Dit containertype wordt niet ondersteund.</red>'53
different-world: '<red>Beide containers moeten in dezelfde wereld staan.</red>'54
en:55
selected-source: '<green>Source side selected. Shift-click the destination container with an empty hand.</green>'56
selection-cancelled: '<yellow>Selection cancelled.</yellow>'57
connected: '<green>Containers connected.</green>'58
disconnected: '<yellow>Connection removed.</yellow>'59
side-in-use: '<red>This container side already has a connection.</red>'60
too-far: '<red>The destination is outside the allowed range.</red>'61
no-route: '<red>No unobstructed pipe route could be found.</red>'62
invalid-container: '<red>This container type is not supported.</red>'63
different-world: '<red>Both containers must be in the same world.</red>'64
65
commands:66
nl:67
status: 'ContainerPipes: {connections} verbinding(en), {segments} displaysegmenten.'68
reloaded: 'ContainerPipes herladen.'69
refreshed: 'Alle geladen buizen vernieuwd.'70
usage: 'Gebruik: /containerpipes <status|reload|refresh>'71
en:72
status: 'ContainerPipes: {connections} connection(s), {segments} display segment(s).'73
reloaded: 'ContainerPipes reloaded.'74
refreshed: 'All loaded pipes refreshed.'75
usage: 'Usage: /containerpipes <status|reload|refresh>'76
77
# Transfer performance. Active source groups run at the normal interval;78
# idle groups sleep and are woken immediately by inventory/chunk events.79
performance:80
active-interval-ticks: 381
idle-after-failed-attempts: 382
sleeping-probe-interval-ticks: 20083
84
# Retry temporarily full/blocked destinations sooner than fully idle sources.85
blocked-retry-interval-ticks: 2086
87
# Sleeping groups are probed in small batches to avoid a single spike.88
sleeping-probe-batch-size: 1089
sleeping-probe-batch-interval-ticks: 590
91
92
# Verdere performance-optimalisaties.93
interaction:94
# Slechts ieder N-de buissegment krijgt een klikbare Interaction-hitbox.95
# Bron- en eindsegment blijven altijd klikbaar.96
hitbox-every-segments: 397
98
visuals:99
# Visuele BlockDisplays en hitboxes bestaan alleen binnen deze afstand van spelers.100
player-tracking-radius-chunks: 5101
unload-when-no-player-nearby: true102
refresh-interval-ticks: 20103
refresh-cycles: 5104
105
particles:106
# Per connection, show at most one transfer animation within this interval.107
transfer-animation-cooldown-ticks: 100108
109
maximum-active-animations: 20110
only-show-within-blocks: 48111
animation-budget-release-ticks: 40112
113
persistence:114
# Bundel snelle opeenvolgende wijzigingen tot één veilige TSV-write.115
save-debounce-ticks: 20@@ -0,0 +1,15 @@
1
name: ContainerPipes
2
version: '1.7.0'
3
main: nl.timfalken.containerpipes.ContainerPipesPlugin
4
api-version: '26.2'
5
author: Tim Falken
6
commands:
7
containerpipes:
8
description: Manage ContainerPipes
9
usage: /containerpipes <status|reload|refresh>
10
permission: containerpipes.admin
11
permissions:
12
containerpipes.use:
13
default: true
14
containerpipes.admin:
15
default: op
@@ -0,0 +1,15 @@1
name: ContainerPipes2
version: '1.7.0'3
main: nl.timfalken.containerpipes.ContainerPipesPlugin4
api-version: '26.2'5
author: Tim Falken6
commands:7
containerpipes:8
description: Manage ContainerPipes9
usage: /containerpipes <status|reload|refresh>10
permission: containerpipes.admin11
permissions:12
containerpipes.use:13
default: true14
containerpipes.admin:15
default: op