BlueGit

timfa containerpipes

Render pipes as packet-only BlockDisplays and release 1.8.4.

Keep real Interaction hitboxes only on chest endpoints so datapack selectors no longer scan visual segments.

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

timfa Tim Falken · pushed by timfa

Authored 2026-08-20 · 2 months ago

Hash
76409c2f902404e1ddf9d20447718d20a2812b1d
Parent
25391a63
9 files changed +585 −207
.gitlab-ci.yml +1 −1
@@ -78,7 +78,7 @@ build:jar:
78 78 - find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
79 79 script:
80 80 - test -n "${VERSION}"
81 - gradle --no-daemon clean jar
81 - gradle --no-daemon clean shadowJar
82 82 - test -f "build/libs/ContainerPipes-${VERSION}.jar"
83 83 - ls -la "build/libs/ContainerPipes-${VERSION}.jar"
84 84 - ./scripts/release.sh upload
@@ -78,7 +78,7 @@ build:jar:
78 - find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
78 - find src -maxdepth 1 -name 'README-*.md' ! -name "README-${VERSION}.md" -delete
79 script:
79 script:
80 - test -n "${VERSION}"
80 - test -n "${VERSION}"
81 - gradle --no-daemon clean jar
81 - gradle --no-daemon clean shadowJar
82 - test -f "build/libs/ContainerPipes-${VERSION}.jar"
82 - test -f "build/libs/ContainerPipes-${VERSION}.jar"
83 - ls -la "build/libs/ContainerPipes-${VERSION}.jar"
83 - ls -la "build/libs/ContainerPipes-${VERSION}.jar"
84 - ./scripts/release.sh upload
84 - ./scripts/release.sh upload
README.md +1 −1
@@ -1,4 +1,4 @@
1 # ContainerPipes 1.8.3
1 # ContainerPipes 1.8.4
2 2
3 3 Paper plugin that connects containers with visible pipes and moves items (or cauldron liquids) between them automatically.
4 4
@@ -1,4 +1,4 @@
1# ContainerPipes 1.8.3
1# ContainerPipes 1.8.4
2
2
3Paper plugin that connects containers with visible pipes and moves items (or cauldron liquids) between them automatically.
3Paper plugin that connects containers with visible pipes and moves items (or cauldron liquids) between them automatically.
4
4
build.gradle.kts +31 −3
@@ -1,19 +1,47 @@
1 plugins { java }
1 plugins {
2 java
3 id("com.gradleup.shadow") version "9.0.2"
4 }
5
2 6 group = "nl.timfalken"
3 version = "1.8.3"
7 version = "1.8.4"
8
4 9 repositories {
5 10 maven {
6 11 name = "papermc"
7 12 url = uri("https://repo.papermc.io/repository/maven-public/")
8 13 }
14 maven {
15 name = "codemc-releases"
16 url = uri("https://repo.codemc.io/repository/maven-releases/")
17 }
9 18 }
19
10 20 dependencies {
11 21 compileOnly("io.papermc.paper:paper-api:26.2.build.+")
22 implementation("com.github.retrooper:packetevents-spigot:2.13.0") {
23 exclude(group = "net.kyori")
24 }
12 25 }
26
13 27 java {
14 28 toolchain.languageVersion.set(JavaLanguageVersion.of(25))
15 29 }
16 tasks.jar {
30
31 tasks.shadowJar {
17 32 archiveBaseName.set("ContainerPipes")
18 33 archiveVersion.set(project.version.toString())
34 archiveClassifier.set("")
35 mergeServiceFiles()
36 relocate("com.github.retrooper.packetevents", "nl.timfalken.containerpipes.libs.pe.api")
37 relocate("io.github.retrooper.packetevents", "nl.timfalken.containerpipes.libs.pe.impl")
38 }
39
40 tasks.named<Jar>("jar") {
41 enabled = false
42 dependsOn(tasks.shadowJar)
43 }
44
45 tasks.named("build") {
46 dependsOn(tasks.shadowJar)
19 47 }
@@ -1,19 +1,47 @@
1plugins { java }
1plugins {
2 java
3 id("com.gradleup.shadow") version "9.0.2"
4}
5
2group = "nl.timfalken"
6group = "nl.timfalken"
3version = "1.8.3"
7version = "1.8.4"
8
4repositories {
9repositories {
5 maven {
10 maven {
6 name = "papermc"
11 name = "papermc"
7 url = uri("https://repo.papermc.io/repository/maven-public/")
12 url = uri("https://repo.papermc.io/repository/maven-public/")
8 }
13 }
14 maven {
15 name = "codemc-releases"
16 url = uri("https://repo.codemc.io/repository/maven-releases/")
17 }
9}
18}
19
10dependencies {
20dependencies {
11 compileOnly("io.papermc.paper:paper-api:26.2.build.+")
21 compileOnly("io.papermc.paper:paper-api:26.2.build.+")
22 implementation("com.github.retrooper:packetevents-spigot:2.13.0") {
23 exclude(group = "net.kyori")
24 }
12}
25}
26
13java {
27java {
14 toolchain.languageVersion.set(JavaLanguageVersion.of(25))
28 toolchain.languageVersion.set(JavaLanguageVersion.of(25))
15}
29}
16tasks.jar {
30
31tasks.shadowJar {
17 archiveBaseName.set("ContainerPipes")
32 archiveBaseName.set("ContainerPipes")
18 archiveVersion.set(project.version.toString())
33 archiveVersion.set(project.version.toString())
34 archiveClassifier.set("")
35 mergeServiceFiles()
36 relocate("com.github.retrooper.packetevents", "nl.timfalken.containerpipes.libs.pe.api")
37 relocate("io.github.retrooper.packetevents", "nl.timfalken.containerpipes.libs.pe.impl")
38}
39
40tasks.named<Jar>("jar") {
41 enabled = false
42 dependsOn(tasks.shadowJar)
43}
44
45tasks.named("build") {
46 dependsOn(tasks.shadowJar)
19}
47}
src/README-1.8.3.md src/README-1.8.4.md renamed +1 −1
@@ -1,4 +1,4 @@
1 # ContainerPipes 1.8.3
1 # ContainerPipes 1.8.4
2 2
3 3 Builds on 1.7.4 (dispenser bucket wake + sleeping-probe CME fix).
4 4
@@ -1,4 +1,4 @@
1# ContainerPipes 1.8.3
1# ContainerPipes 1.8.4
2
2
3Builds on 1.7.4 (dispenser bucket wake + sleeping-probe CME fix).
3Builds on 1.7.4 (dispenser bucket wake + sleeping-probe CME fix).
4
4
src/main/java/nl/timfalken/containerpipes/ContainerPipesPlugin.java +108 −121
@@ -4,8 +4,8 @@ import org.bukkit.*;
4 4 import org.bukkit.block.*;
5 5 import org.bukkit.command.*;
6 6 import org.bukkit.configuration.file.FileConfiguration;
7 import org.bukkit.block.data.BlockData;
7 8 import org.bukkit.block.data.Lightable;
8 import org.bukkit.entity.BlockDisplay;
9 9 import org.bukkit.entity.Entity;
10 10 import org.bukkit.entity.HumanEntity;
11 11 import org.bukkit.entity.Interaction;
@@ -24,9 +24,6 @@ import org.bukkit.event.inventory.InventoryType;
24 24 import org.bukkit.inventory.EquipmentSlot;
25 25 import org.bukkit.plugin.java.JavaPlugin;
26 26 import org.bukkit.scheduler.BukkitTask;
27 import org.bukkit.util.Transformation;
28 import org.joml.AxisAngle4f;
29 import org.joml.Vector3f;
30 27 import net.kyori.adventure.text.Component;
31 28 import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
32 29 import net.kyori.adventure.translation.GlobalTranslator;
@@ -56,16 +53,21 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
56 53 private BukkitTask transferTask;
57 54 private BukkitTask validationTask;
58 55
56 @Override public void onLoad() {
57 PipeVisualManager.load(this);
58 }
59
59 60 @Override public void onEnable() {
60 61 saveDefaultConfig();
61 62 dataFile = new File(getDataFolder(), "connections.tsv");
62 63 getServer().getPluginManager().registerEvents(this, this);
63 64 Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);
65 PipeVisualManager.enable(this);
64 66 cleanupTaggedDisplays();
65 67 loadConnections();
66 68 startTasks();
67 69 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
68 getLogger().info("ContainerPipes 1.8.3 enabled with " + connections.size() + " connection(s).");
70 getLogger().info("ContainerPipes 1.8.4 enabled with " + connections.size() + " connection(s).");
69 71 AdvancedEndpointsPatch.enable(this);
70 72 CrafterPipeManager.enable(this);
71 73 }
@@ -75,6 +77,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
75 77 if (validationTask != null) validationTask.cancel();
76 78 saveConnectionsNow();
77 79 removeAllDisplays();
80 PipeVisualManager.disable();
78 81 selections.clear();
79 82 CrafterPipeManager.disable();
80 83 AdvancedEndpointsPatch.disable(this);
@@ -343,59 +346,71 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
343 346
344 347 private void spawnDisplays(Connection c) {
345 348 removeDisplays(c.id);
346 World world=Bukkit.getWorld(c.source.world); if(world==null)return;
347 Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
348 if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
349 final Material pipeMaterial = material;
350 Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
351 if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
352 final Material filteredSourceMaterial=filteredMaterial;
353 double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
354 float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
355 float sourceEndpointScale=endpointScale("source-endpoint-scale");
356 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
357 List<UUID> ids=new ArrayList<>();
358 List<DisplayPoint> points=polylinePoints(c, spacing);
359 for(DisplayPoint point:points) {
349 World world = Bukkit.getWorld(c.source.world);
350 if (world == null) return;
351 Material material = Material.matchMaterial(getConfig().getString("pipe-material", "minecraft:iron_block"));
352 if (material == null || !material.isBlock()) material = Material.IRON_BLOCK;
353 Material filteredMaterial = Material.matchMaterial(getConfig().getString("filtered-source-material", "minecraft:copper_block"));
354 if (filteredMaterial == null || !filteredMaterial.isBlock()) filteredMaterial = Material.COPPER_BLOCK;
355 double spacing = Math.max(0.1, getConfig().getDouble("segment-spacing", 1.0 / 3.0));
356 float scale = (float) Math.max(0.05, Math.min(1.0, getConfig().getDouble("pipe-scale", 1.0 / 3.0)));
357 float sourceEndpointScale = endpointScale("source-endpoint-scale");
358 float destinationEndpointScale = endpointScale("destination-endpoint-scale");
359 int radiusChunks = Math.max(0, getConfig().getInt("visuals.player-tracking-radius-chunks", 5));
360
361 List<PipeVisualManager.Segment> segments = new ArrayList<>();
362 List<UUID> hitboxIds = new ArrayList<>(2);
363 for (DisplayPoint point : polylinePoints(c, spacing)) {
360 364 Location loc = point.location();
361 float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
362 if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;
363 BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{
364 bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
365 bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
366 bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);
367 if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
368 bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);
369 });
370 ids.add(d.getUniqueId());
371 Interaction hit=world.spawn(loc, Interaction.class, interaction->{
372 interaction.setInteractionWidth(Math.max(0.28f, pointScale));
373 interaction.setInteractionHeight(Math.max(0.28f, pointScale));
374 interaction.setResponsive(true);
375 interaction.setPersistent(false);
376 interaction.addScoreboardTag("containerpipes");
377 interaction.addScoreboardTag("containerpipes-filter:"+c.id);
378 });
379 ids.add(hit.getUniqueId());
365 if (!world.isChunkLoaded(loc.getBlockX() >> 4, loc.getBlockZ() >> 4)) continue;
366 float pointScale = point.type() == 1 ? sourceEndpointScale : point.type() == 2 ? destinationEndpointScale : scale;
367 BlockData block = sourceSegmentData(c, point.type() == 1, material, filteredMaterial);
368 segments.add(PipeVisualManager.allocateSegment(world, loc, pointScale, block, point.type()));
369 // Clickable hitboxes only on the larger chest connectors.
370 if (point.type() == 1 || point.type() == 2) {
371 Interaction hit = world.spawn(loc, Interaction.class, interaction -> {
372 interaction.setInteractionWidth(Math.max(0.28f, pointScale));
373 interaction.setInteractionHeight(Math.max(0.28f, pointScale));
374 interaction.setResponsive(true);
375 interaction.setPersistent(false);
376 interaction.addScoreboardTag("containerpipes");
377 interaction.addScoreboardTag("containerpipes-filter:" + c.id);
378 });
379 hitboxIds.add(hit.getUniqueId());
380 }
380 381 }
381 displayIds.put(c.id,ids);
382 }
383
384 private List<DisplayPoint> polylinePoints(Connection c,double spacing) {
385 World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();
386 float sourceEndpointScale=endpointScale("source-endpoint-scale");
387 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
388 ArrayList<Location> centers=new ArrayList<>();
389 Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);
390 for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));
382 if (!segments.isEmpty()) PipeVisualManager.show(c.id, segments, radiusChunks);
383 if (!hitboxIds.isEmpty()) displayIds.put(c.id, hitboxIds);
384 else if (!segments.isEmpty()) displayIds.put(c.id, List.of());
385 }
386
387 private List<DisplayPoint> polylinePoints(Connection c, double spacing) {
388 World w = Bukkit.getWorld(c.source.world);
389 if (w == null) return List.of();
390 float sourceEndpointScale = endpointScale("source-endpoint-scale");
391 float destinationEndpointScale = endpointScale("destination-endpoint-scale");
392 ArrayList<Location> centers = new ArrayList<>();
393 Location sourceFace = c.source.attachmentCenter(w, sourceEndpointScale);
394 centers.add(sourceFace);
395 for (BlockPos p : c.path) centers.add(new Location(w, p.x + 0.5, p.y + 0.5, p.z + 0.5));
391 396 centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));
392 ArrayList<Location> raw=new ArrayList<>();
393 for(int i=0;i<centers.size()-1;i++) {
394 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));
395 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)); }
397 ArrayList<Location> raw = new ArrayList<>();
398 for (int i = 0; i < centers.size() - 1; i++) {
399 Location a = centers.get(i), b = centers.get(i + 1);
400 double dist = a.distance(b);
401 int steps = Math.max(1, (int) Math.ceil(dist / spacing));
402 for (int j = (i == 0 ? 0 : 1); j <= steps; j++) {
403 double t = (double) j / steps;
404 raw.add(new Location(w,
405 a.getX() + (b.getX() - a.getX()) * t,
406 a.getY() + (b.getY() - a.getY()) * t,
407 a.getZ() + (b.getZ() - a.getZ()) * t));
408 }
409 }
410 ArrayList<DisplayPoint> out = new ArrayList<>(raw.size());
411 for (int i = 0; i < raw.size(); i++) {
412 out.add(new DisplayPoint(raw.get(i), i == 0 ? 1 : i == raw.size() - 1 ? 2 : 0));
396 413 }
397 ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());
398 for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));
399 414 return out;
400 415 }
401 416
@@ -487,88 +502,59 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
487 502 void flashCrafterOutputLamp(long id) {
488 503 BukkitTask previous = crafterLampFlashes.remove(id);
489 504 if (previous != null) previous.cancel();
490 BlockDisplay sourceDisplay = findSourceDisplay(id);
491 if (sourceDisplay == null) return;
505 if (!PipeVisualManager.isShown(id)) return;
492 506 Lightable lit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
493 507 lit.setLit(true);
494 sourceDisplay.setBlock(lit);
508 PipeVisualManager.updateSourceBlock(id, lit);
495 509 crafterLampFlashes.put(id, Bukkit.getScheduler().runTaskLater(this, () -> {
496 510 crafterLampFlashes.remove(id);
497 if (!sourceDisplay.isValid()) return;
511 if (!PipeVisualManager.isShown(id)) return;
498 512 Lightable unlit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
499 513 unlit.setLit(false);
500 sourceDisplay.setBlock(unlit);
514 PipeVisualManager.updateSourceBlock(id, unlit);
501 515 }, 8L));
502 516 }
503 517
504 private BlockDisplay findSourceDisplay(long id) {
505 String sourceTag = "containerpipes-source:" + id;
506 List<UUID> ids = displayIds.get(id);
507 if (ids != null) {
508 for (UUID uuid : ids) {
509 Entity entity = Bukkit.getEntity(uuid);
510 if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) {
511 return display;
512 }
513 }
514 for (UUID uuid : ids) {
515 Entity entity = Bukkit.getEntity(uuid);
516 if (entity instanceof BlockDisplay display) return display;
517 }
518 private void removeDisplays(long id) {
519 PipeVisualManager.hide(id);
520 BukkitTask flash = crafterLampFlashes.remove(id);
521 if (flash != null) flash.cancel();
522 for (UUID uuid : displayIds.getOrDefault(id, List.of())) {
523 Entity entity = Bukkit.getEntity(uuid);
524 if (entity != null) entity.remove();
518 525 }
519 Connection connection = connections.get(id);
520 if (connection == null) return null;
521 World world = Bukkit.getWorld(connection.source.world);
522 if (world == null) return null;
523 Location at = connection.source.attachmentCenter(world, endpointScale("source-endpoint-scale"));
524 for (Entity entity : world.getNearbyEntities(at, 0.75, 0.75, 0.75)) {
525 if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) return display;
526 }
527 return null;
526 displayIds.remove(id);
527 }
528
529 private void removeAllDisplays() {
530 for (long id : List.copyOf(displayIds.keySet())) removeDisplays(id);
531 PipeVisualManager.hideAll();
528 532 }
529 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);}
530 private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}
531 private void removeDisplaysInChunk(Chunk chunk){
532 Set<UUID> removed=new HashSet<>();
533 for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}
534 if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);
533
534 private void removeDisplaysInChunk(Chunk chunk) {
535 for (long id : connectionIdsInChunk(chunk)) removeDisplays(id);
536 // Migration: remove leftover real BlockDisplays from older versions.
537 for (Entity entity : chunk.getEntities()) {
538 if (entity.getScoreboardTags().contains("containerpipes")) entity.remove();
539 }
535 540 }
541
536 542 private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {
537 World world=Bukkit.getWorld(c.source.world); if(world==null)return;
538 Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
539 if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
540 final Material pipeMaterial=material;
541 Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
542 if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
543 final Material filteredSourceMaterial=filteredMaterial;
544 double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
545 float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
546 float sourceEndpointScale=endpointScale("source-endpoint-scale");
547 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
548 List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());
549 for(DisplayPoint point:polylinePoints(c,spacing)) {
550 Location loc=point.location();
551 if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;
552 float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
553 BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{
554 bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
555 bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
556 bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);
557 if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
558 bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);
559 });
560 ids.add(d.getUniqueId());
561 Interaction hit=world.spawn(loc,Interaction.class,interaction->{
562 interaction.setInteractionWidth(Math.max(0.28f,pointScale));
563 interaction.setInteractionHeight(Math.max(0.28f,pointScale));
564 interaction.setResponsive(true);interaction.setPersistent(false);
565 interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);
566 });
567 ids.add(hit.getUniqueId());
543 // Packet segments + endpoint hitboxes are rebuilt as a unit.
544 if (!displayIds.containsKey(c.id) && !PipeVisualManager.isShown(c.id)) {
545 spawnDisplays(c);
546 return;
568 547 }
548 spawnDisplays(c);
569 549 }
570 private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}
571 550
551 private void cleanupTaggedDisplays() {
552 for (World w : Bukkit.getWorlds()) {
553 for (Entity e : w.getEntities()) {
554 if (e.getScoreboardTags().contains("containerpipes")) e.remove();
555 }
556 }
557 }
572 558 private void removeConnection(long id, boolean save) {
573 559 Connection removed = connections.get(id);
574 560 if (removed != null) {
@@ -1012,7 +998,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
1012 998 switch(sub){
1013 999 case "status" -> sender.sendMessage(commandText(sender, "status")
1014 1000 .replace("{connections}", Integer.toString(connections.size()))
1015 .replace("{segments}", Integer.toString(displayIds.values().stream().mapToInt(List::size).sum())));
1001 .replace("{segments}", Integer.toString(PipeVisualManager.segmentCount())));
1016 1002 case "reload" -> {
1017 1003 reloadConfig();
1018 1004 startTasks();
@@ -1023,6 +1009,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
1023 1009 case "refresh" -> {
1024 1010 cleanupTaggedDisplays();
1025 1011 displayIds.clear();
1012 PipeVisualManager.hideAll();
1026 1013 refreshLoadedDisplays();
1027 1014 sender.sendMessage(commandText(sender, "refreshed"));
1028 1015 }
@@ -4,8 +4,8 @@ import org.bukkit.*;
4import org.bukkit.block.*;
4import org.bukkit.block.*;
5import org.bukkit.command.*;
5import org.bukkit.command.*;
6import org.bukkit.configuration.file.FileConfiguration;
6import org.bukkit.configuration.file.FileConfiguration;
7import org.bukkit.block.data.BlockData;
7import org.bukkit.block.data.Lightable;
8import org.bukkit.block.data.Lightable;
8import org.bukkit.entity.BlockDisplay;
9import org.bukkit.entity.Entity;
9import org.bukkit.entity.Entity;
10import org.bukkit.entity.HumanEntity;
10import org.bukkit.entity.HumanEntity;
11import org.bukkit.entity.Interaction;
11import org.bukkit.entity.Interaction;
@@ -24,9 +24,6 @@ import org.bukkit.event.inventory.InventoryType;
24import org.bukkit.inventory.EquipmentSlot;
24import org.bukkit.inventory.EquipmentSlot;
25import org.bukkit.plugin.java.JavaPlugin;
25import org.bukkit.plugin.java.JavaPlugin;
26import org.bukkit.scheduler.BukkitTask;
26import org.bukkit.scheduler.BukkitTask;
27import org.bukkit.util.Transformation;
28import org.joml.AxisAngle4f;
29import org.joml.Vector3f;
30import net.kyori.adventure.text.Component;
27import net.kyori.adventure.text.Component;
31import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
28import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
32import net.kyori.adventure.translation.GlobalTranslator;
29import net.kyori.adventure.translation.GlobalTranslator;
@@ -56,16 +53,21 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
56 private BukkitTask transferTask;
53 private BukkitTask transferTask;
57 private BukkitTask validationTask;
54 private BukkitTask validationTask;
58
55
56 @Override public void onLoad() {
57 PipeVisualManager.load(this);
58 }
59
59 @Override public void onEnable() {
60 @Override public void onEnable() {
60 saveDefaultConfig();
61 saveDefaultConfig();
61 dataFile = new File(getDataFolder(), "connections.tsv");
62 dataFile = new File(getDataFolder(), "connections.tsv");
62 getServer().getPluginManager().registerEvents(this, this);
63 getServer().getPluginManager().registerEvents(this, this);
63 Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);
64 Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this);
65 PipeVisualManager.enable(this);
64 cleanupTaggedDisplays();
66 cleanupTaggedDisplays();
65 loadConnections();
67 loadConnections();
66 startTasks();
68 startTasks();
67 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
69 Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
68 getLogger().info("ContainerPipes 1.8.3 enabled with " + connections.size() + " connection(s).");
70 getLogger().info("ContainerPipes 1.8.4 enabled with " + connections.size() + " connection(s).");
69 AdvancedEndpointsPatch.enable(this);
71 AdvancedEndpointsPatch.enable(this);
70 CrafterPipeManager.enable(this);
72 CrafterPipeManager.enable(this);
71 }
73 }
@@ -75,6 +77,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
75 if (validationTask != null) validationTask.cancel();
77 if (validationTask != null) validationTask.cancel();
76 saveConnectionsNow();
78 saveConnectionsNow();
77 removeAllDisplays();
79 removeAllDisplays();
80 PipeVisualManager.disable();
78 selections.clear();
81 selections.clear();
79 CrafterPipeManager.disable();
82 CrafterPipeManager.disable();
80 AdvancedEndpointsPatch.disable(this);
83 AdvancedEndpointsPatch.disable(this);
@@ -343,59 +346,71 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
343
346
344 private void spawnDisplays(Connection c) {
347 private void spawnDisplays(Connection c) {
345 removeDisplays(c.id);
348 removeDisplays(c.id);
346 World world=Bukkit.getWorld(c.source.world); if(world==null)return;
349 World world = Bukkit.getWorld(c.source.world);
347 Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
350 if (world == null) return;
348 if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
351 Material material = Material.matchMaterial(getConfig().getString("pipe-material", "minecraft:iron_block"));
349 final Material pipeMaterial = material;
352 if (material == null || !material.isBlock()) material = Material.IRON_BLOCK;
350 Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
353 Material filteredMaterial = Material.matchMaterial(getConfig().getString("filtered-source-material", "minecraft:copper_block"));
351 if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
354 if (filteredMaterial == null || !filteredMaterial.isBlock()) filteredMaterial = Material.COPPER_BLOCK;
352 final Material filteredSourceMaterial=filteredMaterial;
355 double spacing = Math.max(0.1, getConfig().getDouble("segment-spacing", 1.0 / 3.0));
353 double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
356 float scale = (float) Math.max(0.05, Math.min(1.0, getConfig().getDouble("pipe-scale", 1.0 / 3.0)));
354 float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
357 float sourceEndpointScale = endpointScale("source-endpoint-scale");
355 float sourceEndpointScale=endpointScale("source-endpoint-scale");
358 float destinationEndpointScale = endpointScale("destination-endpoint-scale");
356 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
359 int radiusChunks = Math.max(0, getConfig().getInt("visuals.player-tracking-radius-chunks", 5));
357 List<UUID> ids=new ArrayList<>();
360
358 List<DisplayPoint> points=polylinePoints(c, spacing);
361 List<PipeVisualManager.Segment> segments = new ArrayList<>();
359 for(DisplayPoint point:points) {
362 List<UUID> hitboxIds = new ArrayList<>(2);
363 for (DisplayPoint point : polylinePoints(c, spacing)) {
360 Location loc = point.location();
364 Location loc = point.location();
361 float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
365 if (!world.isChunkLoaded(loc.getBlockX() >> 4, loc.getBlockZ() >> 4)) continue;
362 if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;
366 float pointScale = point.type() == 1 ? sourceEndpointScale : point.type() == 2 ? destinationEndpointScale : scale;
363 BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{
367 BlockData block = sourceSegmentData(c, point.type() == 1, material, filteredMaterial);
364 bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
368 segments.add(PipeVisualManager.allocateSegment(world, loc, pointScale, block, point.type()));
365 bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
369 // Clickable hitboxes only on the larger chest connectors.
366 bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);
370 if (point.type() == 1 || point.type() == 2) {
367 if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
371 Interaction hit = world.spawn(loc, Interaction.class, interaction -> {
368 bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);
372 interaction.setInteractionWidth(Math.max(0.28f, pointScale));
369 });
373 interaction.setInteractionHeight(Math.max(0.28f, pointScale));
370 ids.add(d.getUniqueId());
374 interaction.setResponsive(true);
371 Interaction hit=world.spawn(loc, Interaction.class, interaction->{
375 interaction.setPersistent(false);
372 interaction.setInteractionWidth(Math.max(0.28f, pointScale));
376 interaction.addScoreboardTag("containerpipes");
373 interaction.setInteractionHeight(Math.max(0.28f, pointScale));
377 interaction.addScoreboardTag("containerpipes-filter:" + c.id);
374 interaction.setResponsive(true);
378 });
375 interaction.setPersistent(false);
379 hitboxIds.add(hit.getUniqueId());
376 interaction.addScoreboardTag("containerpipes");
380 }
377 interaction.addScoreboardTag("containerpipes-filter:"+c.id);
378 });
379 ids.add(hit.getUniqueId());
380 }
381 }
381 displayIds.put(c.id,ids);
382 if (!segments.isEmpty()) PipeVisualManager.show(c.id, segments, radiusChunks);
382 }
383 if (!hitboxIds.isEmpty()) displayIds.put(c.id, hitboxIds);
383
384 else if (!segments.isEmpty()) displayIds.put(c.id, List.of());
384 private List<DisplayPoint> polylinePoints(Connection c,double spacing) {
385 }
385 World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of();
386
386 float sourceEndpointScale=endpointScale("source-endpoint-scale");
387 private List<DisplayPoint> polylinePoints(Connection c, double spacing) {
387 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
388 World w = Bukkit.getWorld(c.source.world);
388 ArrayList<Location> centers=new ArrayList<>();
389 if (w == null) return List.of();
389 Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace);
390 float sourceEndpointScale = endpointScale("source-endpoint-scale");
390 for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5));
391 float destinationEndpointScale = endpointScale("destination-endpoint-scale");
392 ArrayList<Location> centers = new ArrayList<>();
393 Location sourceFace = c.source.attachmentCenter(w, sourceEndpointScale);
394 centers.add(sourceFace);
395 for (BlockPos p : c.path) centers.add(new Location(w, p.x + 0.5, p.y + 0.5, p.z + 0.5));
391 centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));
396 centers.add(c.destination.attachmentCenter(w, destinationEndpointScale));
392 ArrayList<Location> raw=new ArrayList<>();
397 ArrayList<Location> raw = new ArrayList<>();
393 for(int i=0;i<centers.size()-1;i++) {
398 for (int i = 0; i < centers.size() - 1; i++) {
394 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));
399 Location a = centers.get(i), b = centers.get(i + 1);
395 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)); }
400 double dist = a.distance(b);
401 int steps = Math.max(1, (int) Math.ceil(dist / spacing));
402 for (int j = (i == 0 ? 0 : 1); j <= steps; j++) {
403 double t = (double) j / steps;
404 raw.add(new Location(w,
405 a.getX() + (b.getX() - a.getX()) * t,
406 a.getY() + (b.getY() - a.getY()) * t,
407 a.getZ() + (b.getZ() - a.getZ()) * t));
408 }
409 }
410 ArrayList<DisplayPoint> out = new ArrayList<>(raw.size());
411 for (int i = 0; i < raw.size(); i++) {
412 out.add(new DisplayPoint(raw.get(i), i == 0 ? 1 : i == raw.size() - 1 ? 2 : 0));
396 }
413 }
397 ArrayList<DisplayPoint> out=new ArrayList<>(raw.size());
398 for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0));
399 return out;
414 return out;
400 }
415 }
401
416
@@ -487,88 +502,59 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
487 void flashCrafterOutputLamp(long id) {
502 void flashCrafterOutputLamp(long id) {
488 BukkitTask previous = crafterLampFlashes.remove(id);
503 BukkitTask previous = crafterLampFlashes.remove(id);
489 if (previous != null) previous.cancel();
504 if (previous != null) previous.cancel();
490 BlockDisplay sourceDisplay = findSourceDisplay(id);
505 if (!PipeVisualManager.isShown(id)) return;
491 if (sourceDisplay == null) return;
492 Lightable lit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
506 Lightable lit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
493 lit.setLit(true);
507 lit.setLit(true);
494 sourceDisplay.setBlock(lit);
508 PipeVisualManager.updateSourceBlock(id, lit);
495 crafterLampFlashes.put(id, Bukkit.getScheduler().runTaskLater(this, () -> {
509 crafterLampFlashes.put(id, Bukkit.getScheduler().runTaskLater(this, () -> {
496 crafterLampFlashes.remove(id);
510 crafterLampFlashes.remove(id);
497 if (!sourceDisplay.isValid()) return;
511 if (!PipeVisualManager.isShown(id)) return;
498 Lightable unlit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
512 Lightable unlit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
499 unlit.setLit(false);
513 unlit.setLit(false);
500 sourceDisplay.setBlock(unlit);
514 PipeVisualManager.updateSourceBlock(id, unlit);
501 }, 8L));
515 }, 8L));
502 }
516 }
503
517
504 private BlockDisplay findSourceDisplay(long id) {
518 private void removeDisplays(long id) {
505 String sourceTag = "containerpipes-source:" + id;
519 PipeVisualManager.hide(id);
506 List<UUID> ids = displayIds.get(id);
520 BukkitTask flash = crafterLampFlashes.remove(id);
507 if (ids != null) {
521 if (flash != null) flash.cancel();
508 for (UUID uuid : ids) {
522 for (UUID uuid : displayIds.getOrDefault(id, List.of())) {
509 Entity entity = Bukkit.getEntity(uuid);
523 Entity entity = Bukkit.getEntity(uuid);
510 if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) {
524 if (entity != null) entity.remove();
511 return display;
512 }
513 }
514 for (UUID uuid : ids) {
515 Entity entity = Bukkit.getEntity(uuid);
516 if (entity instanceof BlockDisplay display) return display;
517 }
518 }
525 }
519 Connection connection = connections.get(id);
526 displayIds.remove(id);
520 if (connection == null) return null;
527 }
521 World world = Bukkit.getWorld(connection.source.world);
528
522 if (world == null) return null;
529 private void removeAllDisplays() {
523 Location at = connection.source.attachmentCenter(world, endpointScale("source-endpoint-scale"));
530 for (long id : List.copyOf(displayIds.keySet())) removeDisplays(id);
524 for (Entity entity : world.getNearbyEntities(at, 0.75, 0.75, 0.75)) {
531 PipeVisualManager.hideAll();
525 if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) return display;
526 }
527 return null;
528 }
532 }
529 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);}
533
530 private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}
534 private void removeDisplaysInChunk(Chunk chunk) {
531 private void removeDisplaysInChunk(Chunk chunk){
535 for (long id : connectionIdsInChunk(chunk)) removeDisplays(id);
532 Set<UUID> removed=new HashSet<>();
536 // Migration: remove leftover real BlockDisplays from older versions.
533 for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();}
537 for (Entity entity : chunk.getEntities()) {
534 if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains);
538 if (entity.getScoreboardTags().contains("containerpipes")) entity.remove();
539 }
535 }
540 }
541
536 private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {
542 private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) {
537 World world=Bukkit.getWorld(c.source.world); if(world==null)return;
543 // Packet segments + endpoint hitboxes are rebuilt as a unit.
538 Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block"));
544 if (!displayIds.containsKey(c.id) && !PipeVisualManager.isShown(c.id)) {
539 if(material==null || !material.isBlock()) material=Material.IRON_BLOCK;
545 spawnDisplays(c);
540 final Material pipeMaterial=material;
546 return;
541 Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block"));
542 if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK;
543 final Material filteredSourceMaterial=filteredMaterial;
544 double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0));
545 float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0)));
546 float sourceEndpointScale=endpointScale("source-endpoint-scale");
547 float destinationEndpointScale=endpointScale("destination-endpoint-scale");
548 List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>());
549 for(DisplayPoint point:polylinePoints(c,spacing)) {
550 Location loc=point.location();
551 if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;
552 float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
553 BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{
554 bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
555 bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
556 bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);
557 if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
558 bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);
559 });
560 ids.add(d.getUniqueId());
561 Interaction hit=world.spawn(loc,Interaction.class,interaction->{
562 interaction.setInteractionWidth(Math.max(0.28f,pointScale));
563 interaction.setInteractionHeight(Math.max(0.28f,pointScale));
564 interaction.setResponsive(true);interaction.setPersistent(false);
565 interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id);
566 });
567 ids.add(hit.getUniqueId());
568 }
547 }
548 spawnDisplays(c);
569 }
549 }
570 private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();}
571
550
551 private void cleanupTaggedDisplays() {
552 for (World w : Bukkit.getWorlds()) {
553 for (Entity e : w.getEntities()) {
554 if (e.getScoreboardTags().contains("containerpipes")) e.remove();
555 }
556 }
557 }
572 private void removeConnection(long id, boolean save) {
558 private void removeConnection(long id, boolean save) {
573 Connection removed = connections.get(id);
559 Connection removed = connections.get(id);
574 if (removed != null) {
560 if (removed != null) {
@@ -1012,7 +998,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
1012 switch(sub){
998 switch(sub){
1013 case "status" -> sender.sendMessage(commandText(sender, "status")
999 case "status" -> sender.sendMessage(commandText(sender, "status")
1014 .replace("{connections}", Integer.toString(connections.size()))
1000 .replace("{connections}", Integer.toString(connections.size()))
1015 .replace("{segments}", Integer.toString(displayIds.values().stream().mapToInt(List::size).sum())));
1001 .replace("{segments}", Integer.toString(PipeVisualManager.segmentCount())));
1016 case "reload" -> {
1002 case "reload" -> {
1017 reloadConfig();
1003 reloadConfig();
1018 startTasks();
1004 startTasks();
@@ -1023,6 +1009,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
1023 case "refresh" -> {
1009 case "refresh" -> {
1024 cleanupTaggedDisplays();
1010 cleanupTaggedDisplays();
1025 displayIds.clear();
1011 displayIds.clear();
1012 PipeVisualManager.hideAll();
1026 refreshLoadedDisplays();
1013 refreshLoadedDisplays();
1027 sender.sendMessage(commandText(sender, "refreshed"));
1014 sender.sendMessage(commandText(sender, "refreshed"));
1028 }
1015 }
src/main/java/nl/timfalken/containerpipes/PipeVisualManager.java added +285 −0
@@ -0,0 +1,285 @@
1 package nl.timfalken.containerpipes;
2
3 import com.github.retrooper.packetevents.PacketEvents;
4 import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
5 import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
6 import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
7 import com.github.retrooper.packetevents.util.Quaternion4f;
8 import com.github.retrooper.packetevents.util.Vector3d;
9 import com.github.retrooper.packetevents.util.Vector3f;
10 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
11 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
12 import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
13 import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
14 import io.github.retrooper.packetevents.util.SpigotConversionUtil;
15 import org.bukkit.Bukkit;
16 import org.bukkit.Location;
17 import org.bukkit.World;
18 import org.bukkit.block.data.BlockData;
19 import org.bukkit.entity.Player;
20 import org.bukkit.plugin.java.JavaPlugin;
21
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.UUID;
30
31 /**
32 * Client-only BlockDisplay pipe segments. Nothing here enters the server entity
33 * list, so datapack {@code @e} selectors cannot see them. Interaction hitboxes
34 * stay real and are owned by {@link ContainerPipesPlugin}.
35 */
36 public final class PipeVisualManager {
37 private PipeVisualManager() {}
38
39 private static final Map<Long, PipeVisual> visuals = new HashMap<>();
40 private static final Quaternion4f IDENTITY = new Quaternion4f(0f, 0f, 0f, 1f);
41
42 /** One packet BlockDisplay segment. */
43 public record Segment(
44 int entityId,
45 UUID entityUuid,
46 UUID worldId,
47 double x,
48 double y,
49 double z,
50 float scale,
51 BlockData block,
52 int type
53 ) {
54 boolean isSource() { return type == 1; }
55 }
56
57 static final class PipeVisual {
58 final long connectionId;
59 final List<Segment> segments;
60 final Set<UUID> viewers = new HashSet<>();
61
62 PipeVisual(long connectionId, List<Segment> segments) {
63 this.connectionId = connectionId;
64 this.segments = List.copyOf(segments);
65 }
66 }
67
68 public static void load(JavaPlugin owner) {
69 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(owner));
70 PacketEvents.getAPI().load();
71 }
72
73 public static void enable(JavaPlugin owner) {
74 if (PacketEvents.getAPI() == null) {
75 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(owner));
76 PacketEvents.getAPI().load();
77 }
78 PacketEvents.getAPI().init();
79 }
80
81 public static void disable() {
82 hideAll();
83 try {
84 if (PacketEvents.getAPI() != null) PacketEvents.getAPI().terminate();
85 } catch (Throwable ignored) {}
86 }
87
88 public static boolean isShown(long connectionId) {
89 return visuals.containsKey(connectionId);
90 }
91
92 public static int segmentCount() {
93 int total = 0;
94 for (PipeVisual visual : visuals.values()) total += visual.segments.size();
95 return total;
96 }
97
98 public static int segmentCount(long connectionId) {
99 PipeVisual visual = visuals.get(connectionId);
100 return visual == null ? 0 : visual.segments.size();
101 }
102
103 /**
104 * Replace visuals for a connection and show them to nearby players.
105 * Segments must already have allocated entity ids.
106 */
107 public static void show(long connectionId, List<Segment> segments, int radiusChunks) {
108 hide(connectionId);
109 if (segments == null || segments.isEmpty()) return;
110 PipeVisual visual = new PipeVisual(connectionId, segments);
111 visuals.put(connectionId, visual);
112 syncViewers(visual, nearbyPlayers(visual, radiusChunks));
113 }
114
115 public static void hide(long connectionId) {
116 PipeVisual visual = visuals.remove(connectionId);
117 if (visual == null) return;
118 destroyForAll(visual);
119 }
120
121 public static void hideAll() {
122 for (Long id : List.copyOf(visuals.keySet())) hide(id);
123 }
124
125 /** Update the source connector block (crafter lamp flash / filter material). */
126 public static void updateSourceBlock(long connectionId, BlockData block) {
127 PipeVisual visual = visuals.get(connectionId);
128 if (visual == null || block == null) return;
129 List<Segment> next = new ArrayList<>(visual.segments.size());
130 Segment source = null;
131 for (Segment segment : visual.segments) {
132 if (segment.isSource()) {
133 source = new Segment(
134 segment.entityId, segment.entityUuid, segment.worldId,
135 segment.x, segment.y, segment.z, segment.scale, block, segment.type);
136 next.add(source);
137 } else {
138 next.add(segment);
139 }
140 }
141 PipeVisual replaced = new PipeVisual(connectionId, next);
142 replaced.viewers.addAll(visual.viewers);
143 visuals.put(connectionId, replaced);
144 if (source == null) return;
145 for (UUID viewerId : replaced.viewers) {
146 Player player = Bukkit.getPlayer(viewerId);
147 if (player != null && player.isOnline()) sendMetadata(player, source);
148 }
149 }
150
151 public static void tickViewers(int radiusChunks) {
152 if (visuals.isEmpty()) return;
153 for (PipeVisual visual : visuals.values()) {
154 syncViewers(visual, nearbyPlayers(visual, radiusChunks));
155 }
156 }
157
158 public static Segment allocateSegment(World world, Location location, float scale, BlockData block, int type) {
159 int entityId = Bukkit.getUnsafe().nextEntityId(world);
160 return new Segment(
161 entityId,
162 UUID.randomUUID(),
163 world.getUID(),
164 location.getX(),
165 location.getY(),
166 location.getZ(),
167 scale,
168 block,
169 type
170 );
171 }
172
173 private static void syncViewers(PipeVisual visual, Set<UUID> desired) {
174 for (UUID viewerId : List.copyOf(visual.viewers)) {
175 if (desired.contains(viewerId)) continue;
176 Player player = Bukkit.getPlayer(viewerId);
177 if (player != null && player.isOnline()) destroyFor(player, visual);
178 visual.viewers.remove(viewerId);
179 }
180 for (UUID viewerId : desired) {
181 if (visual.viewers.contains(viewerId)) continue;
182 Player player = Bukkit.getPlayer(viewerId);
183 if (player == null || !player.isOnline()) continue;
184 spawnFor(player, visual);
185 visual.viewers.add(viewerId);
186 }
187 }
188
189 private static Set<UUID> nearbyPlayers(PipeVisual visual, int radiusChunks) {
190 Set<UUID> near = new HashSet<>();
191 if (visual.segments.isEmpty()) return near;
192 Segment first = visual.segments.getFirst();
193 World world = Bukkit.getWorld(first.worldId);
194 if (world == null) return near;
195 int minChunkX = Integer.MAX_VALUE, maxChunkX = Integer.MIN_VALUE;
196 int minChunkZ = Integer.MAX_VALUE, maxChunkZ = Integer.MIN_VALUE;
197 for (Segment segment : visual.segments) {
198 int cx = (int) Math.floor(segment.x) >> 4;
199 int cz = (int) Math.floor(segment.z) >> 4;
200 minChunkX = Math.min(minChunkX, cx);
201 maxChunkX = Math.max(maxChunkX, cx);
202 minChunkZ = Math.min(minChunkZ, cz);
203 maxChunkZ = Math.max(maxChunkZ, cz);
204 }
205 for (Player player : world.getPlayers()) {
206 int px = player.getLocation().getBlockX() >> 4;
207 int pz = player.getLocation().getBlockZ() >> 4;
208 boolean close =
209 chunkNear(px, pz, minChunkX, minChunkZ, radiusChunks)
210 || chunkNear(px, pz, maxChunkX, maxChunkZ, radiusChunks)
211 || chunkNear(px, pz, minChunkX, maxChunkZ, radiusChunks)
212 || chunkNear(px, pz, maxChunkX, minChunkZ, radiusChunks);
213 // Also accept players near any segment midpoint of the bbox.
214 if (!close) {
215 int midX = (minChunkX + maxChunkX) >> 1;
216 int midZ = (minChunkZ + maxChunkZ) >> 1;
217 close = chunkNear(px, pz, midX, midZ, radiusChunks);
218 }
219 if (close) near.add(player.getUniqueId());
220 }
221 return near;
222 }
223
224 private static boolean chunkNear(int px, int pz, int cx, int cz, int radius) {
225 return Math.max(Math.abs(px - cx), Math.abs(pz - cz)) <= radius;
226 }
227
228 private static void spawnFor(Player player, PipeVisual visual) {
229 for (Segment segment : visual.segments) {
230 sendSpawn(player, segment);
231 sendMetadata(player, segment);
232 }
233 }
234
235 private static void destroyFor(Player player, PipeVisual visual) {
236 int[] ids = new int[visual.segments.size()];
237 for (int i = 0; i < visual.segments.size(); i++) ids[i] = visual.segments.get(i).entityId;
238 if (ids.length == 0) return;
239 PacketEvents.getAPI().getPlayerManager().sendPacket(player, new WrapperPlayServerDestroyEntities(ids));
240 }
241
242 private static void destroyForAll(PipeVisual visual) {
243 for (UUID viewerId : visual.viewers) {
244 Player player = Bukkit.getPlayer(viewerId);
245 if (player != null && player.isOnline()) destroyFor(player, visual);
246 }
247 visual.viewers.clear();
248 }
249
250 private static void sendSpawn(Player player, Segment segment) {
251 WrapperPlayServerSpawnEntity packet = new WrapperPlayServerSpawnEntity(
252 segment.entityId,
253 Optional.of(segment.entityUuid),
254 EntityTypes.BLOCK_DISPLAY,
255 new Vector3d(segment.x, segment.y, segment.z),
256 0f,
257 0f,
258 0f,
259 0,
260 Optional.empty()
261 );
262 PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet);
263 }
264
265 private static void sendMetadata(Player player, Segment segment) {
266 float half = segment.scale / 2f;
267 Vector3f translation = new Vector3f(-half, -half, -half);
268 Vector3f scale = new Vector3f(segment.scale, segment.scale, segment.scale);
269 int blockId = SpigotConversionUtil.fromBukkitBlockData(segment.block).getGlobalId();
270
271 List<EntityData<?>> data = new ArrayList<>(8);
272 // Display entity metadata (1.19.4+ / current Paper): translation, scale, rotations, view range, shadows, block.
273 data.add(new EntityData<>(11, EntityDataTypes.VECTOR3F, translation));
274 data.add(new EntityData<>(12, EntityDataTypes.VECTOR3F, scale));
275 data.add(new EntityData<>(13, EntityDataTypes.QUATERNION, IDENTITY));
276 data.add(new EntityData<>(14, EntityDataTypes.QUATERNION, IDENTITY));
277 data.add(new EntityData<>(17, EntityDataTypes.FLOAT, 1.0f)); // view range
278 data.add(new EntityData<>(18, EntityDataTypes.FLOAT, 0f)); // shadow radius
279 data.add(new EntityData<>(19, EntityDataTypes.FLOAT, 0f)); // shadow strength
280 data.add(new EntityData<>(23, EntityDataTypes.BLOCK_STATE, blockId));
281
282 PacketEvents.getAPI().getPlayerManager().sendPacket(
283 player, new WrapperPlayServerEntityMetadata(segment.entityId, data));
284 }
285 }
@@ -0,0 +1,285 @@
1package nl.timfalken.containerpipes;
2
3import com.github.retrooper.packetevents.PacketEvents;
4import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
5import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
6import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
7import com.github.retrooper.packetevents.util.Quaternion4f;
8import com.github.retrooper.packetevents.util.Vector3d;
9import com.github.retrooper.packetevents.util.Vector3f;
10import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
11import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
12import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
13import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
14import io.github.retrooper.packetevents.util.SpigotConversionUtil;
15import org.bukkit.Bukkit;
16import org.bukkit.Location;
17import org.bukkit.World;
18import org.bukkit.block.data.BlockData;
19import org.bukkit.entity.Player;
20import org.bukkit.plugin.java.JavaPlugin;
21
22import java.util.ArrayList;
23import java.util.HashMap;
24import java.util.HashSet;
25import java.util.List;
26import java.util.Map;
27import java.util.Optional;
28import java.util.Set;
29import java.util.UUID;
30
31/**
32 * Client-only BlockDisplay pipe segments. Nothing here enters the server entity
33 * list, so datapack {@code @e} selectors cannot see them. Interaction hitboxes
34 * stay real and are owned by {@link ContainerPipesPlugin}.
35 */
36public final class PipeVisualManager {
37 private PipeVisualManager() {}
38
39 private static final Map<Long, PipeVisual> visuals = new HashMap<>();
40 private static final Quaternion4f IDENTITY = new Quaternion4f(0f, 0f, 0f, 1f);
41
42 /** One packet BlockDisplay segment. */
43 public record Segment(
44 int entityId,
45 UUID entityUuid,
46 UUID worldId,
47 double x,
48 double y,
49 double z,
50 float scale,
51 BlockData block,
52 int type
53 ) {
54 boolean isSource() { return type == 1; }
55 }
56
57 static final class PipeVisual {
58 final long connectionId;
59 final List<Segment> segments;
60 final Set<UUID> viewers = new HashSet<>();
61
62 PipeVisual(long connectionId, List<Segment> segments) {
63 this.connectionId = connectionId;
64 this.segments = List.copyOf(segments);
65 }
66 }
67
68 public static void load(JavaPlugin owner) {
69 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(owner));
70 PacketEvents.getAPI().load();
71 }
72
73 public static void enable(JavaPlugin owner) {
74 if (PacketEvents.getAPI() == null) {
75 PacketEvents.setAPI(SpigotPacketEventsBuilder.build(owner));
76 PacketEvents.getAPI().load();
77 }
78 PacketEvents.getAPI().init();
79 }
80
81 public static void disable() {
82 hideAll();
83 try {
84 if (PacketEvents.getAPI() != null) PacketEvents.getAPI().terminate();
85 } catch (Throwable ignored) {}
86 }
87
88 public static boolean isShown(long connectionId) {
89 return visuals.containsKey(connectionId);
90 }
91
92 public static int segmentCount() {
93 int total = 0;
94 for (PipeVisual visual : visuals.values()) total += visual.segments.size();
95 return total;
96 }
97
98 public static int segmentCount(long connectionId) {
99 PipeVisual visual = visuals.get(connectionId);
100 return visual == null ? 0 : visual.segments.size();
101 }
102
103 /**
104 * Replace visuals for a connection and show them to nearby players.
105 * Segments must already have allocated entity ids.
106 */
107 public static void show(long connectionId, List<Segment> segments, int radiusChunks) {
108 hide(connectionId);
109 if (segments == null || segments.isEmpty()) return;
110 PipeVisual visual = new PipeVisual(connectionId, segments);
111 visuals.put(connectionId, visual);
112 syncViewers(visual, nearbyPlayers(visual, radiusChunks));
113 }
114
115 public static void hide(long connectionId) {
116 PipeVisual visual = visuals.remove(connectionId);
117 if (visual == null) return;
118 destroyForAll(visual);
119 }
120
121 public static void hideAll() {
122 for (Long id : List.copyOf(visuals.keySet())) hide(id);
123 }
124
125 /** Update the source connector block (crafter lamp flash / filter material). */
126 public static void updateSourceBlock(long connectionId, BlockData block) {
127 PipeVisual visual = visuals.get(connectionId);
128 if (visual == null || block == null) return;
129 List<Segment> next = new ArrayList<>(visual.segments.size());
130 Segment source = null;
131 for (Segment segment : visual.segments) {
132 if (segment.isSource()) {
133 source = new Segment(
134 segment.entityId, segment.entityUuid, segment.worldId,
135 segment.x, segment.y, segment.z, segment.scale, block, segment.type);
136 next.add(source);
137 } else {
138 next.add(segment);
139 }
140 }
141 PipeVisual replaced = new PipeVisual(connectionId, next);
142 replaced.viewers.addAll(visual.viewers);
143 visuals.put(connectionId, replaced);
144 if (source == null) return;
145 for (UUID viewerId : replaced.viewers) {
146 Player player = Bukkit.getPlayer(viewerId);
147 if (player != null && player.isOnline()) sendMetadata(player, source);
148 }
149 }
150
151 public static void tickViewers(int radiusChunks) {
152 if (visuals.isEmpty()) return;
153 for (PipeVisual visual : visuals.values()) {
154 syncViewers(visual, nearbyPlayers(visual, radiusChunks));
155 }
156 }
157
158 public static Segment allocateSegment(World world, Location location, float scale, BlockData block, int type) {
159 int entityId = Bukkit.getUnsafe().nextEntityId(world);
160 return new Segment(
161 entityId,
162 UUID.randomUUID(),
163 world.getUID(),
164 location.getX(),
165 location.getY(),
166 location.getZ(),
167 scale,
168 block,
169 type
170 );
171 }
172
173 private static void syncViewers(PipeVisual visual, Set<UUID> desired) {
174 for (UUID viewerId : List.copyOf(visual.viewers)) {
175 if (desired.contains(viewerId)) continue;
176 Player player = Bukkit.getPlayer(viewerId);
177 if (player != null && player.isOnline()) destroyFor(player, visual);
178 visual.viewers.remove(viewerId);
179 }
180 for (UUID viewerId : desired) {
181 if (visual.viewers.contains(viewerId)) continue;
182 Player player = Bukkit.getPlayer(viewerId);
183 if (player == null || !player.isOnline()) continue;
184 spawnFor(player, visual);
185 visual.viewers.add(viewerId);
186 }
187 }
188
189 private static Set<UUID> nearbyPlayers(PipeVisual visual, int radiusChunks) {
190 Set<UUID> near = new HashSet<>();
191 if (visual.segments.isEmpty()) return near;
192 Segment first = visual.segments.getFirst();
193 World world = Bukkit.getWorld(first.worldId);
194 if (world == null) return near;
195 int minChunkX = Integer.MAX_VALUE, maxChunkX = Integer.MIN_VALUE;
196 int minChunkZ = Integer.MAX_VALUE, maxChunkZ = Integer.MIN_VALUE;
197 for (Segment segment : visual.segments) {
198 int cx = (int) Math.floor(segment.x) >> 4;
199 int cz = (int) Math.floor(segment.z) >> 4;
200 minChunkX = Math.min(minChunkX, cx);
201 maxChunkX = Math.max(maxChunkX, cx);
202 minChunkZ = Math.min(minChunkZ, cz);
203 maxChunkZ = Math.max(maxChunkZ, cz);
204 }
205 for (Player player : world.getPlayers()) {
206 int px = player.getLocation().getBlockX() >> 4;
207 int pz = player.getLocation().getBlockZ() >> 4;
208 boolean close =
209 chunkNear(px, pz, minChunkX, minChunkZ, radiusChunks)
210 || chunkNear(px, pz, maxChunkX, maxChunkZ, radiusChunks)
211 || chunkNear(px, pz, minChunkX, maxChunkZ, radiusChunks)
212 || chunkNear(px, pz, maxChunkX, minChunkZ, radiusChunks);
213 // Also accept players near any segment midpoint of the bbox.
214 if (!close) {
215 int midX = (minChunkX + maxChunkX) >> 1;
216 int midZ = (minChunkZ + maxChunkZ) >> 1;
217 close = chunkNear(px, pz, midX, midZ, radiusChunks);
218 }
219 if (close) near.add(player.getUniqueId());
220 }
221 return near;
222 }
223
224 private static boolean chunkNear(int px, int pz, int cx, int cz, int radius) {
225 return Math.max(Math.abs(px - cx), Math.abs(pz - cz)) <= radius;
226 }
227
228 private static void spawnFor(Player player, PipeVisual visual) {
229 for (Segment segment : visual.segments) {
230 sendSpawn(player, segment);
231 sendMetadata(player, segment);
232 }
233 }
234
235 private static void destroyFor(Player player, PipeVisual visual) {
236 int[] ids = new int[visual.segments.size()];
237 for (int i = 0; i < visual.segments.size(); i++) ids[i] = visual.segments.get(i).entityId;
238 if (ids.length == 0) return;
239 PacketEvents.getAPI().getPlayerManager().sendPacket(player, new WrapperPlayServerDestroyEntities(ids));
240 }
241
242 private static void destroyForAll(PipeVisual visual) {
243 for (UUID viewerId : visual.viewers) {
244 Player player = Bukkit.getPlayer(viewerId);
245 if (player != null && player.isOnline()) destroyFor(player, visual);
246 }
247 visual.viewers.clear();
248 }
249
250 private static void sendSpawn(Player player, Segment segment) {
251 WrapperPlayServerSpawnEntity packet = new WrapperPlayServerSpawnEntity(
252 segment.entityId,
253 Optional.of(segment.entityUuid),
254 EntityTypes.BLOCK_DISPLAY,
255 new Vector3d(segment.x, segment.y, segment.z),
256 0f,
257 0f,
258 0f,
259 0,
260 Optional.empty()
261 );
262 PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet);
263 }
264
265 private static void sendMetadata(Player player, Segment segment) {
266 float half = segment.scale / 2f;
267 Vector3f translation = new Vector3f(-half, -half, -half);
268 Vector3f scale = new Vector3f(segment.scale, segment.scale, segment.scale);
269 int blockId = SpigotConversionUtil.fromBukkitBlockData(segment.block).getGlobalId();
270
271 List<EntityData<?>> data = new ArrayList<>(8);
272 // Display entity metadata (1.19.4+ / current Paper): translation, scale, rotations, view range, shadows, block.
273 data.add(new EntityData<>(11, EntityDataTypes.VECTOR3F, translation));
274 data.add(new EntityData<>(12, EntityDataTypes.VECTOR3F, scale));
275 data.add(new EntityData<>(13, EntityDataTypes.QUATERNION, IDENTITY));
276 data.add(new EntityData<>(14, EntityDataTypes.QUATERNION, IDENTITY));
277 data.add(new EntityData<>(17, EntityDataTypes.FLOAT, 1.0f)); // view range
278 data.add(new EntityData<>(18, EntityDataTypes.FLOAT, 0f)); // shadow radius
279 data.add(new EntityData<>(19, EntityDataTypes.FLOAT, 0f)); // shadow strength
280 data.add(new EntityData<>(23, EntityDataTypes.BLOCK_STATE, blockId));
281
282 PacketEvents.getAPI().getPlayerManager().sendPacket(
283 player, new WrapperPlayServerEntityMetadata(segment.entityId, data));
284 }
285}
src/main/java/nl/timfalken/containerpipes/VisualPerformanceManager.java +146 −73
@@ -4,7 +4,7 @@ import java.lang.reflect.*;
4 4 import java.util.*;
5 5 import java.util.concurrent.ConcurrentHashMap;
6 6
7 /** Manages display radius and interaction hitbox density without retaining Bukkit objects. */
7 /** Manages display radius without retaining Bukkit objects. */
8 8 public final class VisualPerformanceManager {
9 9 private VisualPerformanceManager() {}
10 10 private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
@@ -14,97 +14,170 @@ public final class VisualPerformanceManager {
14 14
15 15 public static void tick(Object plugin) {
16 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){}
17 State state = STATES.computeIfAbsent(plugin, p -> new State());
18 if (!state.dirty && ++state.counter < state.refreshEvery) return;
19 state.counter = 0;
20 state.dirty = false;
21 Object cfg = call(plugin, "getConfig");
22 state.refreshEvery = Math.max(1, intCfg(cfg, "visuals.refresh-cycles", 5));
23 int radiusChunks = Math.max(0, intCfg(cfg, "visuals.player-tracking-radius-chunks", 5));
24 boolean unloadFar = boolCfg(cfg, "visuals.unload-when-no-player-nearby", true);
25 manage(plugin, radiusChunks, unloadFar);
26 PipeVisualManager.tickViewers(radiusChunks);
27 } catch (Throwable ignored) {}
27 28 }
28 29
29 public static boolean hasPlayerNearConnection(Object plugin,Object connection,int radius) {
30 public static boolean hasPlayerNearConnection(Object plugin, Object connection, int radius) {
30 31 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;
32 Object source = call(connection, "source");
33 UUID worldId = (UUID) call(source, "world");
34 Object world = staticCall("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);
35 if (world == null) return false;
36 double x = (int) call(source, "x") + 0.5, y = (int) call(source, "y") + 0.5, z = (int) call(source, "z") + 0.5;
37 double max = (double) radius * radius;
38 for (Object player : (Collection<?>) call(world, "getPlayers")) {
39 Object loc = call(player, "getLocation");
40 double dx = (double) call(loc, "getX") - x, dy = (double) call(loc, "getY") - y, dz = (double) call(loc, "getZ") - z;
41 if (dx * dx + dy * dy + dz * dz <= max) return true;
39 42 }
40 }catch(Throwable ignored){}
43 } catch (Throwable ignored) {}
41 44 return false;
42 45 }
43 46
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);
47 private static void manage(Object plugin, int radiusChunks, boolean unloadFar) throws Exception {
48 Map<?, ?> connections = (Map<?, ?>) field(plugin, "connections");
49 Map<?, ?> displayIds = (Map<?, ?>) field(plugin, "displayIds");
50 Set<Long> near = new HashSet<>();
51 for (Object connection : connections.values()) {
52 if (isNearPlayer(connection, radiusChunks)) {
53 near.add(((Number) call(connection, "id")).longValue());
53 54 }
54 55 }
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);
56 if (unloadFar) {
57 for (Object idObj : new ArrayList<>(displayIds.keySet())) {
58 long id = ((Number) idObj).longValue();
59 if (!near.contains(id)) invoke(plugin, "removeDisplays", new Class<?>[]{long.class}, id);
60 }
61 }
62 for (Object connection : connections.values()) {
63 long id = ((Number) call(connection, "id")).longValue();
64 if (near.contains(id) && !displayIds.containsKey(id) && !PipeVisualManager.isShown(id)) {
65 invoke(plugin, "spawnDisplays", new Class<?>[]{connection.getClass()}, connection);
66 }
58 67 }
59 thinInteractions(plugin,hitEvery);
60 68 }
61 69
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;
70 private static boolean isNearPlayer(Object connection, int radiusChunks) throws Exception {
71 Object source = call(connection, "source");
72 UUID worldId = (UUID) call(source, "world");
73 Object world = staticCall("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);
74 if (world == null) return false;
75 int sx = (int) call(source, "x") >> 4, sz = (int) call(source, "z") >> 4;
76 Object destination = call(connection, "destination");
77 int dx = (int) call(destination, "x") >> 4, dz = (int) call(destination, "z") >> 4;
78 for (Object player : (Collection<?>) call(world, "getPlayers")) {
79 Object loc = call(player, "getLocation");
80 int px = (int) call(loc, "getBlockX") >> 4, pz = (int) call(loc, "getBlockZ") >> 4;
81 if (Math.max(Math.abs(px - sx), Math.abs(pz - sz)) <= radiusChunks
82 || Math.max(Math.abs(px - dx), Math.abs(pz - dz)) <= radiusChunks) {
83 return true;
84 }
69 85 }
70 86 return false;
71 87 }
72 88
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);
89 private static final class State {
90 boolean dirty = true;
91 int counter;
92 int refreshEvery = 5;
93 }
94
95 private static boolean boolCfg(Object cfg, String p, boolean d) {
96 try {
97 return (boolean) call(cfg, "getBoolean", new Class<?>[]{String.class, boolean.class}, p, d);
98 } catch (Throwable t) {
99 return d;
100 }
101 }
102
103 private static int intCfg(Object cfg, String p, int d) {
104 try {
105 return (int) call(cfg, "getInt", new Class<?>[]{String.class, int.class}, p, d);
106 } catch (Throwable t) {
107 return d;
108 }
109 }
110
111 private static Object field(Object o, String n) throws Exception {
112 for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) {
113 try {
114 Field f = c.getDeclaredField(n);
115 f.setAccessible(true);
116 return f.get(o);
117 } catch (NoSuchFieldException ignored) {}
118 }
119 throw new NoSuchFieldException(n);
120 }
121
122 private static Object invoke(Object o, String n, Class<?>[] t, Object... a) throws Exception {
123 Method m = find(o.getClass(), n, t);
124 m.setAccessible(true);
125 return m.invoke(o, a);
126 }
127
128 private static Object call(Object o, String n, Object... a) throws Exception {
129 return call(o, n, new Class<?>[0], a);
130 }
131
132 private static Object call(Object o, String n, Class<?>[] t, Object... a) throws Exception {
133 Method m = find(o.getClass(), n, t);
134 m.setAccessible(true);
135 return m.invoke(o, a);
136 }
137
138 private static Object staticCall(String c, String n, Class<?>[] t, Object... a) throws Exception {
139 Class<?> k = Class.forName(c, false, VisualPerformanceManager.class.getClassLoader());
140 Method m = find(k, n, t);
141 m.setAccessible(true);
142 return m.invoke(null, a);
143 }
144
145 private static Method find(Class<?> c, String n, Class<?>[] t) throws Exception {
146 String key = c.getName() + "#" + n + Arrays.toString(t);
147 Method cached = METHODS.get(key);
148 if (cached != null) return cached;
149 for (Class<?> k = c; k != null; k = k.getSuperclass()) {
150 for (Method m : k.getDeclaredMethods()) {
151 if (m.getName().equals(n) && compatible(m.getParameterTypes(), t)) {
152 METHODS.put(key, m);
153 return m;
154 }
90 155 }
91 interactions.sort(java.util.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");
156 }
157 for (Method m : c.getMethods()) {
158 if (m.getName().equals(n) && compatible(m.getParameterTypes(), t)) {
159 METHODS.put(key, m);
160 return m;
94 161 }
95 162 }
163 throw new NoSuchMethodException(key);
96 164 }
97 165
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;}
166 private static boolean compatible(Class<?>[] a, Class<?>[] b) {
167 if (a.length != b.length) return false;
168 for (int i = 0; i < a.length; i++) {
169 if (!wrap(a[i]).isAssignableFrom(wrap(b[i]))) return false;
170 }
171 return true;
172 }
173
174 private static Class<?> wrap(Class<?> c) {
175 if (!c.isPrimitive()) return c;
176 if (c == int.class) return Integer.class;
177 if (c == long.class) return Long.class;
178 if (c == boolean.class) return Boolean.class;
179 if (c == double.class) return Double.class;
180 if (c == float.class) return Float.class;
181 return c;
182 }
110 183 }
@@ -4,7 +4,7 @@ import java.lang.reflect.*;
4import java.util.*;
4import java.util.*;
5import java.util.concurrent.ConcurrentHashMap;
5import java.util.concurrent.ConcurrentHashMap;
6
6
7/** Manages display radius and interaction hitbox density without retaining Bukkit objects. */
7/** Manages display radius without retaining Bukkit objects. */
8public final class VisualPerformanceManager {
8public final class VisualPerformanceManager {
9 private VisualPerformanceManager() {}
9 private VisualPerformanceManager() {}
10 private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
10 private static final Map<Object, State> STATES = Collections.synchronizedMap(new WeakHashMap<>());
@@ -14,97 +14,170 @@ public final class VisualPerformanceManager {
14
14
15 public static void tick(Object plugin) {
15 public static void tick(Object plugin) {
16 try {
16 try {
17 State state=STATES.computeIfAbsent(plugin,p->new State());
17 State state = STATES.computeIfAbsent(plugin, p -> new State());
18 if(!state.dirty && ++state.counter < state.refreshEvery) return;
18 if (!state.dirty && ++state.counter < state.refreshEvery) return;
19 state.counter=0; state.dirty=false;
19 state.counter = 0;
20 Object cfg=call(plugin,"getConfig");
20 state.dirty = false;
21 state.refreshEvery=Math.max(1,intCfg(cfg,"visuals.refresh-cycles",5));
21 Object cfg = call(plugin, "getConfig");
22 int radiusChunks=Math.max(0,intCfg(cfg,"visuals.player-tracking-radius-chunks",5));
22 state.refreshEvery = Math.max(1, intCfg(cfg, "visuals.refresh-cycles", 5));
23 int hitEvery=Math.max(1,intCfg(cfg,"interaction.hitbox-every-segments",3));
23 int radiusChunks = Math.max(0, intCfg(cfg, "visuals.player-tracking-radius-chunks", 5));
24 boolean unloadFar=boolCfg(cfg,"visuals.unload-when-no-player-nearby",true);
24 boolean unloadFar = boolCfg(cfg, "visuals.unload-when-no-player-nearby", true);
25 manage(plugin,radiusChunks,hitEvery,unloadFar);
25 manage(plugin, radiusChunks, unloadFar);
26 } catch(Throwable ignored){}
26 PipeVisualManager.tickViewers(radiusChunks);
27 } catch (Throwable ignored) {}
27 }
28 }
28
29
29 public static boolean hasPlayerNearConnection(Object plugin,Object connection,int radius) {
30 public static boolean hasPlayerNearConnection(Object plugin, Object connection, int radius) {
30 try {
31 try {
31 Object source=call(connection,"source"); UUID worldId=(UUID)call(source,"world");
32 Object source = call(connection, "source");
32 Object world=staticCall("org.bukkit.Bukkit","getWorld",new Class<?>[]{UUID.class},worldId);
33 UUID worldId = (UUID) call(source, "world");
33 if(world==null)return false;
34 Object world = staticCall("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);
34 double x=(int)call(source,"x")+0.5,y=(int)call(source,"y")+0.5,z=(int)call(source,"z")+0.5;
35 if (world == null) return false;
35 double max=(double)radius*radius;
36 double x = (int) call(source, "x") + 0.5, y = (int) call(source, "y") + 0.5, z = (int) call(source, "z") + 0.5;
36 for(Object player:(Collection<?>)call(world,"getPlayers")){
37 double max = (double) radius * radius;
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 for (Object player : (Collection<?>) call(world, "getPlayers")) {
38 if(dx*dx+dy*dy+dz*dz<=max)return true;
39 Object loc = call(player, "getLocation");
40 double dx = (double) call(loc, "getX") - x, dy = (double) call(loc, "getY") - y, dz = (double) call(loc, "getZ") - z;
41 if (dx * dx + dy * dy + dz * dz <= max) return true;
39 }
42 }
40 }catch(Throwable ignored){}
43 } catch (Throwable ignored) {}
41 return false;
44 return false;
42 }
45 }
43
46
44 private static void manage(Object plugin,int radiusChunks,int hitEvery,boolean unloadFar)throws Exception{
47 private static void manage(Object plugin, int radiusChunks, boolean unloadFar) throws Exception {
45 Map<?,?> connections=(Map<?,?>)field(plugin,"connections");
48 Map<?, ?> connections = (Map<?, ?>) field(plugin, "connections");
46 Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");
49 Map<?, ?> displayIds = (Map<?, ?>) field(plugin, "displayIds");
47 Set<Long> near=new HashSet<>();
50 Set<Long> near = new HashSet<>();
48 for(Object connection:connections.values())if(isNearPlayer(connection,radiusChunks))near.add(((Number)call(connection,"id")).longValue());
51 for (Object connection : connections.values()) {
49 if(unloadFar){
52 if (isNearPlayer(connection, radiusChunks)) {
50 for(Object idObj:new ArrayList<>(displayIds.keySet())){
53 near.add(((Number) call(connection, "id")).longValue());
51 long id=((Number)idObj).longValue();
52 if(!near.contains(id))invoke(plugin,"removeDisplays",new Class<?>[]{long.class},id);
53 }
54 }
54 }
55 }
55 for(Object connection:connections.values()){
56 if (unloadFar) {
56 long id=((Number)call(connection,"id")).longValue();
57 for (Object idObj : new ArrayList<>(displayIds.keySet())) {
57 if(near.contains(id)&&!displayIds.containsKey(id))invoke(plugin,"spawnDisplays",new Class<?>[]{connection.getClass()},connection);
58 long id = ((Number) idObj).longValue();
59 if (!near.contains(id)) invoke(plugin, "removeDisplays", new Class<?>[]{long.class}, id);
60 }
61 }
62 for (Object connection : connections.values()) {
63 long id = ((Number) call(connection, "id")).longValue();
64 if (near.contains(id) && !displayIds.containsKey(id) && !PipeVisualManager.isShown(id)) {
65 invoke(plugin, "spawnDisplays", new Class<?>[]{connection.getClass()}, connection);
66 }
58 }
67 }
59 thinInteractions(plugin,hitEvery);
60 }
68 }
61
69
62 private static boolean isNearPlayer(Object connection,int radiusChunks)throws Exception{
70 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;
71 Object source = call(connection, "source");
64 int sx=(int)call(source,"x")>>4,sz=(int)call(source,"z")>>4;
72 UUID worldId = (UUID) call(source, "world");
65 Object destination=call(connection,"destination");int dx=(int)call(destination,"x")>>4,dz=(int)call(destination,"z")>>4;
73 Object world = staticCall("org.bukkit.Bukkit", "getWorld", new Class<?>[]{UUID.class}, worldId);
66 for(Object player:(Collection<?>)call(world,"getPlayers")){
74 if (world == null) return false;
67 Object loc=call(player,"getLocation");int px=(int)call(loc,"getBlockX")>>4,pz=(int)call(loc,"getBlockZ")>>4;
75 int sx = (int) call(source, "x") >> 4, sz = (int) call(source, "z") >> 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;
76 Object destination = call(connection, "destination");
77 int dx = (int) call(destination, "x") >> 4, dz = (int) call(destination, "z") >> 4;
78 for (Object player : (Collection<?>) call(world, "getPlayers")) {
79 Object loc = call(player, "getLocation");
80 int px = (int) call(loc, "getBlockX") >> 4, pz = (int) call(loc, "getBlockZ") >> 4;
81 if (Math.max(Math.abs(px - sx), Math.abs(pz - sz)) <= radiusChunks
82 || Math.max(Math.abs(px - dx), Math.abs(pz - dz)) <= radiusChunks) {
83 return true;
84 }
69 }
85 }
70 return false;
86 return false;
71 }
87 }
72
88
73 private static void thinInteractions(Object plugin,int every)throws Exception{
89 private static final class State {
74 // Only inspect entities owned by ContainerPipes. The previous implementation
90 boolean dirty = true;
75 // scanned and sorted every entity in every world, which caused periodic MSPT
91 int counter;
76 // spikes in mob-heavy worlds.
92 int refreshEvery = 5;
77 Map<?,?> displayIds=(Map<?,?>)field(plugin,"displayIds");
93 }
78 for(Object entryObj:displayIds.entrySet()){
94
79 Map.Entry<?,?> entry=(Map.Entry<?,?>)entryObj;
95 private static boolean boolCfg(Object cfg, String p, boolean d) {
80 Object idObj=entry.getKey();
96 try {
81 long connectionId=((Number)idObj).longValue();
97 return (boolean) call(cfg, "getBoolean", new Class<?>[]{String.class, boolean.class}, p, d);
82 List<?> uuids=(List<?>)entry.getValue();
98 } catch (Throwable t) {
83 ArrayList<Object> interactions=new ArrayList<>();
99 return d;
84 for(Object uuidObj:uuids){
100 }
85 if(!(uuidObj instanceof UUID uuid))continue;
101 }
86 Object entity=staticCall("org.bukkit.Bukkit","getEntity",new Class<?>[]{UUID.class},uuid);
102
87 if(entity==null)continue;
103 private static int intCfg(Object cfg, String p, int d) {
88 Set<?> tags=(Set<?>)call(entity,"getScoreboardTags");
104 try {
89 if(tags.contains("containerpipes-filter:"+connectionId))interactions.add(entity);
105 return (int) call(cfg, "getInt", new Class<?>[]{String.class, int.class}, p, d);
106 } catch (Throwable t) {
107 return d;
108 }
109 }
110
111 private static Object field(Object o, String n) throws Exception {
112 for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) {
113 try {
114 Field f = c.getDeclaredField(n);
115 f.setAccessible(true);
116 return f.get(o);
117 } catch (NoSuchFieldException ignored) {}
118 }
119 throw new NoSuchFieldException(n);
120 }
121
122 private static Object invoke(Object o, String n, Class<?>[] t, Object... a) throws Exception {
123 Method m = find(o.getClass(), n, t);
124 m.setAccessible(true);
125 return m.invoke(o, a);
126 }
127
128 private static Object call(Object o, String n, Object... a) throws Exception {
129 return call(o, n, new Class<?>[0], a);
130 }
131
132 private static Object call(Object o, String n, Class<?>[] t, Object... a) throws Exception {
133 Method m = find(o.getClass(), n, t);
134 m.setAccessible(true);
135 return m.invoke(o, a);
136 }
137
138 private static Object staticCall(String c, String n, Class<?>[] t, Object... a) throws Exception {
139 Class<?> k = Class.forName(c, false, VisualPerformanceManager.class.getClassLoader());
140 Method m = find(k, n, t);
141 m.setAccessible(true);
142 return m.invoke(null, a);
143 }
144
145 private static Method find(Class<?> c, String n, Class<?>[] t) throws Exception {
146 String key = c.getName() + "#" + n + Arrays.toString(t);
147 Method cached = METHODS.get(key);
148 if (cached != null) return cached;
149 for (Class<?> k = c; k != null; k = k.getSuperclass()) {
150 for (Method m : k.getDeclaredMethods()) {
151 if (m.getName().equals(n) && compatible(m.getParameterTypes(), t)) {
152 METHODS.put(key, m);
153 return m;
154 }
90 }
155 }
91 interactions.sort(java.util.Comparator.comparingDouble(VisualPerformanceManager::entitySortKey));
156 }
92 for(int i=0;i<interactions.size();i++){
157 for (Method m : c.getMethods()) {
93 if(i!=0&&i!=interactions.size()-1&&i%every!=0)call(interactions.get(i),"remove");
158 if (m.getName().equals(n) && compatible(m.getParameterTypes(), t)) {
159 METHODS.put(key, m);
160 return m;
94 }
161 }
95 }
162 }
163 throw new NoSuchMethodException(key);
96 }
164 }
97
165
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;}}
166 private static boolean compatible(Class<?>[] a, Class<?>[] b) {
99 private static final class State{boolean dirty=true;int counter;int refreshEvery=5;}
167 if (a.length != b.length) return false;
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;}}
168 for (int i = 0; i < a.length; i++) {
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;}}
169 if (!wrap(a[i]).isAssignableFrom(wrap(b[i]))) return false;
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);}
170 }
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);}
171 return true;
104 private static Object call(Object o,String n,Object...a)throws Exception{return call(o,n,new Class<?>[0],a);}
172 }
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);}
173
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);}
174 private static Class<?> wrap(Class<?> c) {
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);}
175 if (!c.isPrimitive()) return c;
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;}
176 if (c == int.class) return Integer.class;
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;}
177 if (c == long.class) return Long.class;
178 if (c == boolean.class) return Boolean.class;
179 if (c == double.class) return Double.class;
180 if (c == float.class) return Float.class;
181 return c;
182 }
110}
183}
src/main/resources/config.yml +4 −6
@@ -104,14 +104,12 @@ performance:
104 104 sleeping-probe-batch-interval-ticks: 5
105 105
106 106
107 # Verdere performance-optimalisaties.
108 interaction:
109 # Slechts ieder N-de buissegment krijgt een klikbare Interaction-hitbox.
110 # Bron- en eindsegment blijven altijd klikbaar.
111 hitbox-every-segments: 3
107 # Klikbare Interaction-hitboxes bestaan alleen op de bron- en
108 # bestemmingsconnectors (de grotere eindpunten bij de kist).
109 # Tussensegmenten zijn packet-only BlockDisplays zonder hitbox.
112 110
113 111 visuals:
114 # Visuele BlockDisplays en hitboxes bestaan alleen binnen deze afstand van spelers.
112 # Packet BlockDisplays + eindpunt-hitboxes alleen binnen deze afstand van spelers.
115 113 player-tracking-radius-chunks: 5
116 114 unload-when-no-player-nearby: true
117 115 refresh-interval-ticks: 20
@@ -104,14 +104,12 @@ performance:
104 sleeping-probe-batch-interval-ticks: 5
104 sleeping-probe-batch-interval-ticks: 5
105
105
106
106
107# Verdere performance-optimalisaties.
107# Klikbare Interaction-hitboxes bestaan alleen op de bron- en
108interaction:
108# bestemmingsconnectors (de grotere eindpunten bij de kist).
109 # Slechts ieder N-de buissegment krijgt een klikbare Interaction-hitbox.
109# Tussensegmenten zijn packet-only BlockDisplays zonder hitbox.
110 # Bron- en eindsegment blijven altijd klikbaar.
111 hitbox-every-segments: 3
112
110
113visuals:
111visuals:
114 # Visuele BlockDisplays en hitboxes bestaan alleen binnen deze afstand van spelers.
112 # Packet BlockDisplays + eindpunt-hitboxes alleen binnen deze afstand van spelers.
115 player-tracking-radius-chunks: 5
113 player-tracking-radius-chunks: 5
116 unload-when-no-player-nearby: true
114 unload-when-no-player-nearby: true
117 refresh-interval-ticks: 20
115 refresh-interval-ticks: 20
src/main/resources/plugin.yml +8 −1
@@ -1,8 +1,15 @@
1 1 name: ContainerPipes
2 version: '1.8.3'
2 version: '1.8.4'
3 3 main: nl.timfalken.containerpipes.ContainerPipesPlugin
4 4 api-version: '26.2'
5 5 author: Tim Falken
6 softdepend:
7 - ProtocolLib
8 - ProtocolSupport
9 - ViaVersion
10 - ViaBackwards
11 - ViaRewind
12 - Geyser-Spigot
6 13 commands:
7 14 containerpipes:
8 15 description: Manage ContainerPipes
@@ -1,8 +1,15 @@
1name: ContainerPipes
1name: ContainerPipes
2version: '1.8.3'
2version: '1.8.4'
3main: nl.timfalken.containerpipes.ContainerPipesPlugin
3main: nl.timfalken.containerpipes.ContainerPipesPlugin
4api-version: '26.2'
4api-version: '26.2'
5author: Tim Falken
5author: Tim Falken
6softdepend:
7 - ProtocolLib
8 - ProtocolSupport
9 - ViaVersion
10 - ViaBackwards
11 - ViaRewind
12 - Geyser-Spigot
6commands:
13commands:
7 containerpipes:
14 containerpipes:
8 description: Manage ContainerPipes
15 description: Manage ContainerPipes