BlueGit

timfa chestpreviews

Files

chestpreviews / src / main / java / nl / timfalken / chestpreview / PreviewManager.java

PreviewManager.java

PreviewManager.java 23.0 KiB Download Raw
1package nl.timfalken.chestpreview;
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.Vector3f;
9import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
10import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
11import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
12import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
13import io.github.retrooper.packetevents.util.SpigotConversionUtil;
14import org.bukkit.Bukkit;
15import org.bukkit.Chunk;
16import org.bukkit.Location;
17import org.bukkit.Material;
18import org.bukkit.NamespacedKey;
19import org.bukkit.World;
20import org.bukkit.block.Block;
21import org.bukkit.block.BlockState;
22import org.bukkit.entity.Entity;
23import org.bukkit.entity.ItemDisplay;
24import org.bukkit.entity.Player;
25import org.bukkit.inventory.FurnaceInventory;
26import org.bukkit.inventory.Inventory;
27import org.bukkit.inventory.ItemStack;
28import org.bukkit.persistence.PersistentDataType;
29
30import java.util.ArrayDeque;
31import java.util.ArrayList;
32import java.util.HashMap;
33import java.util.HashSet;
34import java.util.Iterator;
35import java.util.List;
36import java.util.Map;
37import java.util.Queue;
38import java.util.Set;
39import java.util.UUID;
40import java.util.concurrent.ThreadLocalRandom;
41import java.util.concurrent.atomic.AtomicInteger;
42
43/**
44 * Maintains logical previews and sends them as packet-only ItemDisplay entities.
45 * No ItemDisplay is spawned into the Bukkit world by this version.
46 */
47final class PreviewManager {
48 // Minecraft 26.2 metadata indices for Display / ItemDisplay entities.
49 // Base Entity occupies 0..7, Display 8..22, ItemDisplay 23..24.
50 private static final int META_ENTITY_FLAGS = 0;
51 private static final int META_NO_GRAVITY = 5;
52 private static final int META_SCALE = 12;
53 private static final int META_LEFT_ROTATION = 13;
54 private static final int META_RIGHT_ROTATION = 14;
55 private static final int META_BILLBOARD = 15;
56 private static final int META_ITEM = 23;
57 private static final int META_ITEM_TRANSFORM = 24;
58
59 private static final byte ENTITY_FLAG_GLOWING = 0x40;
60 private static final byte BILLBOARD_FIXED = 0;
61 private static final byte ITEM_TRANSFORM_GUI = 6;
62 private static final byte ITEM_TRANSFORM_FIXED = 8;
63
64 // Client-only IDs live far above normal server entity IDs to avoid collisions.
65 private static final AtomicInteger NEXT_FAKE_ENTITY_ID = new AtomicInteger(2_000_000_000);
66
67 private final ChestPreviewPlugin plugin;
68 private final NamespacedKey legacyManagedKey;
69 private final Map<BlockKey, PreviewState> previews = new HashMap<>();
70 private final Queue<BlockKey> scanQueue = new ArrayDeque<>();
71 private final Set<BlockKey> queued = new HashSet<>();
72 private final Map<ChunkKey, Set<BlockKey>> knownContainers = new HashMap<>();
73
74 PreviewManager(ChestPreviewPlugin plugin) {
75 this.plugin = plugin;
76 // Used only to remove persisted server-side displays left by ChestPreview <= 1.0.8.
77 this.legacyManagedKey = new NamespacedKey("chestpreview", "managed");
78 }
79
80 boolean isSupported(Block block) {
81 return switch (block.getType()) {
82 case CHEST -> plugin.getConfig().getBoolean("containers.chest", true);
83 case TRAPPED_CHEST -> plugin.getConfig().getBoolean("containers.trapped-chest", true);
84 case BARREL -> plugin.getConfig().getBoolean("containers.barrel", true);
85 case FURNACE -> plugin.getConfig().getBoolean("output-containers.furnace", true);
86 case BLAST_FURNACE -> plugin.getConfig().getBoolean("output-containers.blast-furnace", true);
87 case SMOKER -> plugin.getConfig().getBoolean("output-containers.smoker", true);
88 default -> false;
89 };
90 }
91
92 void refresh(Block block) {
93 if (!isSupported(block)) {
94 removeForPhysicalBlock(BlockKey.of(block));
95 return;
96 }
97 ContainerTarget target = ContainerTarget.fromBlock(block);
98 if (target != null) refresh(target);
99 }
100
101 void refresh(ContainerTarget target) {
102 rememberTarget(target);
103 ItemStack selected = selectItem(target);
104 BlockKey key = target.key();
105
106 if (selected == null) {
107 destroyPreview(key);
108 return;
109 }
110
111 Location location = target.displayLocation(
112 plugin.getConfig().getDouble("display.forward-offset", 0.515),
113 plugin.getConfig().getDouble("display.vertical-offset", 0.42),
114 plugin.getConfig().getDouble("display.sideways-offset", 0.0),
115 plugin.getConfig().getDouble("display.rotation.yaw", 0.0),
116 plugin.getConfig().getDouble("display.rotation.pitch", 0.0));
117
118 ItemStack shown = selected.clone();
119 shown.setAmount(1);
120 VisualSpec visual = visualSpec(shown.getType());
121
122 PreviewState state = previews.get(key);
123 boolean newlyCreated = false;
124 boolean moved = false;
125 boolean metadataChanged = false;
126
127 if (state == null) {
128 state = new PreviewState(
129 NEXT_FAKE_ENTITY_ID.getAndDecrement(),
130 UUID.randomUUID(),
131 copyLocation(location),
132 shown,
133 visual);
134 previews.put(key, state);
135 newlyCreated = true;
136 } else {
137 moved = !sameLocation(state.location, location);
138 metadataChanged = !sameItem(state.item, shown) || !state.visual.equals(visual);
139 state.location = copyLocation(location);
140 state.item = shown;
141 state.visual = visual;
142 }
143
144 syncViewers(key, state, newlyCreated, moved, metadataChanged);
145 }
146
147 private ItemStack selectItem(ContainerTarget target) {
148 Inventory inventory = target.inventory();
149 if (inventory instanceof FurnaceInventory furnaceInventory) {
150 ItemStack result = furnaceInventory.getResult();
151 if (usable(result)) return result;
152
153 ItemStack input = furnaceInventory.getSmelting();
154 return usable(input) ? input : null;
155 }
156
157 ItemStack[] contents = inventory.getStorageContents();
158 int usableCount = 0;
159 for (ItemStack item : contents) {
160 if (usable(item)) usableCount++;
161 }
162 if (usableCount == 0) return null;
163
164 int selectedIndex = ThreadLocalRandom.current().nextInt(usableCount);
165 for (ItemStack item : contents) {
166 if (!usable(item)) continue;
167 if (selectedIndex-- == 0) return item;
168 }
169 return null;
170 }
171
172 private static boolean usable(ItemStack item) {
173 return item != null && item.getType() != Material.AIR && item.getAmount() > 0;
174 }
175
176 private VisualSpec visualSpec(Material material) {
177 float scale = (float) plugin.getConfig().getDouble("display.scale", 0.40);
178 float roll = radians(plugin.getConfig().getDouble("display.rotation.roll", 0.0));
179 boolean block = material.isBlock();
180
181 float modelYaw = block ? 0.0f : radians(180.0);
182 float modelPitch = 0.0f;
183
184 if (material.name().endsWith("_STAIRS")) {
185 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-yaw", 0.0));
186 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-pitch", 0.0));
187 } else if (block) {
188 modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.default-yaw", 0.0));
189 modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.default-pitch", 0.0));
190 }
191
192 byte transform = block ? ITEM_TRANSFORM_FIXED : ITEM_TRANSFORM_GUI;
193 boolean glowing = plugin.getConfig().getBoolean("display.glowing", false);
194 return new VisualSpec(scale, modelPitch, modelYaw, roll, transform, glowing);
195 }
196
197 private void syncViewers(BlockKey key, PreviewState state, boolean newlyCreated, boolean moved, boolean metadataChanged) {
198 Set<UUID> stillVisible = new HashSet<>();
199
200 for (Player player : Bukkit.getOnlinePlayers()) {
201 if (!shouldView(player, state.location)) continue;
202 UUID playerId = player.getUniqueId();
203 stillVisible.add(playerId);
204
205 if (state.viewers.add(playerId)) {
206 sendSpawn(player, state);
207 } else {
208 if (moved) sendTeleport(player, state);
209 if (metadataChanged || newlyCreated) sendMetadata(player, state);
210 }
211 }
212
213 Iterator<UUID> iterator = state.viewers.iterator();
214 while (iterator.hasNext()) {
215 UUID viewerId = iterator.next();
216 if (stillVisible.contains(viewerId)) continue;
217 Player viewer = Bukkit.getPlayer(viewerId);
218 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
219 iterator.remove();
220 }
221 }
222
223 private boolean shouldView(Player player, Location location) {
224 if (location.getWorld() == null || !player.getWorld().getUID().equals(location.getWorld().getUID())) return false;
225 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
226 int playerChunkX = player.getLocation().getChunk().getX();
227 int playerChunkZ = player.getLocation().getChunk().getZ();
228 int previewChunkX = ((int) Math.floor(location.getX())) >> 4;
229 int previewChunkZ = ((int) Math.floor(location.getZ())) >> 4;
230 return Math.abs(playerChunkX - previewChunkX) <= radius && Math.abs(playerChunkZ - previewChunkZ) <= radius;
231 }
232
233 private void sendSpawn(Player player, PreviewState state) {
234 WrapperPlayServerSpawnEntity spawn = new WrapperPlayServerSpawnEntity(
235 state.entityId,
236 state.entityUuid,
237 EntityTypes.ITEM_DISPLAY,
238 SpigotConversionUtil.fromBukkitLocation(state.location),
239 state.location.getYaw(),
240 0,
241 null);
242 PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawn);
243 sendMetadata(player, state);
244 }
245
246 private void sendMetadata(Player player, PreviewState state) {
247 List<EntityData<?>> data = new ArrayList<>(8);
248 byte flags = state.visual.glowing ? ENTITY_FLAG_GLOWING : 0;
249 data.add(new EntityData<>(META_ENTITY_FLAGS, EntityDataTypes.BYTE, flags));
250 data.add(new EntityData<>(META_NO_GRAVITY, EntityDataTypes.BOOLEAN, true));
251 data.add(new EntityData<>(META_SCALE, EntityDataTypes.VECTOR3F,
252 new Vector3f(state.visual.scale, state.visual.scale, state.visual.scale)));
253 data.add(new EntityData<>(META_LEFT_ROTATION, EntityDataTypes.QUATERNION,
254 quaternionXYZ(state.visual.pitch, state.visual.yaw, state.visual.roll)));
255 data.add(new EntityData<>(META_RIGHT_ROTATION, EntityDataTypes.QUATERNION,
256 new Quaternion4f(0.0f, 0.0f, 0.0f, 1.0f)));
257 data.add(new EntityData<>(META_BILLBOARD, EntityDataTypes.BYTE, BILLBOARD_FIXED));
258 data.add(new EntityData<>(META_ITEM, EntityDataTypes.ITEMSTACK,
259 SpigotConversionUtil.fromBukkitItemStack(state.item)));
260 data.add(new EntityData<>(META_ITEM_TRANSFORM, EntityDataTypes.BYTE, state.visual.itemTransform));
261
262 PacketEvents.getAPI().getPlayerManager().sendPacket(
263 player,
264 new WrapperPlayServerEntityMetadata(state.entityId, data));
265 }
266
267 private void sendTeleport(Player player, PreviewState state) {
268 PacketEvents.getAPI().getPlayerManager().sendPacket(
269 player,
270 new WrapperPlayServerEntityTeleport(
271 state.entityId,
272 SpigotConversionUtil.fromBukkitLocation(state.location),
273 false));
274 }
275
276 private void sendDestroy(Player player, int entityId) {
277 PacketEvents.getAPI().getPlayerManager().sendPacket(
278 player,
279 new WrapperPlayServerDestroyEntities(entityId));
280 }
281
282 private void destroyPreview(BlockKey key) {
283 PreviewState state = previews.remove(key);
284 if (state == null) return;
285 for (UUID viewerId : new HashSet<>(state.viewers)) {
286 Player viewer = Bukkit.getPlayer(viewerId);
287 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
288 }
289 state.viewers.clear();
290 }
291
292 private void pruneViewers() {
293 for (PreviewState state : previews.values()) {
294 Iterator<UUID> iterator = state.viewers.iterator();
295 while (iterator.hasNext()) {
296 UUID viewerId = iterator.next();
297 Player viewer = Bukkit.getPlayer(viewerId);
298 if (viewer != null && viewer.isOnline() && shouldView(viewer, state.location)) continue;
299 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
300 iterator.remove();
301 }
302 }
303 }
304
305 /**
306 * Register containers once when a chunk is discovered. Legacy Bukkit ItemDisplays from
307 * ChestPreview <= 1.0.8 are removed as a migration step, but no new Bukkit entity is spawned.
308 */
309 void discoverChunk(Chunk chunk) {
310 cleanupLegacyDisplays(chunk);
311 registerContainersInChunk(chunk, true);
312 }
313
314 void rebuildChunk(Chunk chunk) {
315 int chunkX = chunk.getX();
316 int chunkZ = chunk.getZ();
317 World world = chunk.getWorld();
318 ChunkKey chunkKey = ChunkKey.of(chunk);
319
320 cleanupLegacyDisplays(chunk);
321
322 List<BlockKey> toDestroy = new ArrayList<>();
323 for (BlockKey key : previews.keySet()) {
324 if (isInChunk(key, world, chunkX, chunkZ)) toDestroy.add(key);
325 }
326 for (BlockKey key : toDestroy) destroyPreview(key);
327
328 scanQueue.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
329 queued.removeIf(key -> isInChunk(key, world, chunkX, chunkZ));
330 knownContainers.remove(chunkKey);
331
332 registerContainersInChunk(chunk, true);
333 }
334
335 void forgetChunk(Chunk chunk) {
336 ChunkKey chunkKey = ChunkKey.of(chunk);
337 Set<BlockKey> forgotten = knownContainers.remove(chunkKey);
338 if (forgotten == null) return;
339
340 for (BlockKey key : forgotten) {
341 destroyPreview(key);
342 queued.remove(key);
343 }
344 scanQueue.removeIf(forgotten::contains);
345 }
346
347 private void cleanupLegacyDisplays(Chunk chunk) {
348 for (Entity entity : chunk.getEntities()) {
349 if (!(entity instanceof ItemDisplay display)) continue;
350 if (display.getPersistentDataContainer().has(legacyManagedKey, PersistentDataType.BYTE)) {
351 display.remove();
352 }
353 }
354 }
355
356 private void registerContainersInChunk(Chunk chunk, boolean enqueueForRefresh) {
357 for (BlockState state : chunk.getTileEntities()) {
358 Block block = state.getBlock();
359 if (!isSupported(block)) continue;
360 ContainerTarget target = ContainerTarget.fromBlock(block);
361 if (target == null) continue;
362 rememberTarget(target);
363 if (enqueueForRefresh) enqueue(target.key());
364 }
365 }
366
367 private void rememberTarget(ContainerTarget target) {
368 BlockKey key = target.key();
369 knownContainers.computeIfAbsent(ChunkKey.of(key), ignored -> new HashSet<>()).add(key);
370 }
371
372 private void forgetKnownKey(BlockKey key) {
373 Set<BlockKey> keys = knownContainers.get(ChunkKey.of(key));
374 if (keys == null) return;
375 keys.remove(key);
376 if (keys.isEmpty()) knownContainers.remove(ChunkKey.of(key));
377 }
378
379 private static boolean isInChunk(BlockKey key, World world, int chunkX, int chunkZ) {
380 return key.worldId().equals(world.getUID()) && (key.x() >> 4) == chunkX && (key.z() >> 4) == chunkZ;
381 }
382
383 void enqueue(BlockKey key) {
384 if (queued.add(key)) scanQueue.offer(key);
385 }
386
387 void enqueue(Block block) {
388 if (!isSupported(block)) return;
389 ContainerTarget target = ContainerTarget.fromBlock(block);
390 if (target == null) return;
391 rememberTarget(target);
392 enqueue(target.key());
393 }
394
395 void processScanBatch() {
396 int maximum = Math.max(1, plugin.getConfig().getInt("updates.containers-per-batch", 5));
397 for (int i = 0; i < maximum; i++) {
398 BlockKey key = scanQueue.poll();
399 if (key == null) return;
400 queued.remove(key);
401 World world = Bukkit.getWorld(key.worldId());
402 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
403 refresh(world.getBlockAt(key.x(), key.y(), key.z()));
404 }
405 }
406
407 /**
408 * Every interval, already-known containers near players are visited. If cycling is enabled,
409 * the preview item is reselected. The same pass also creates/removes client-only viewers as
410 * players enter or leave the configured four-chunk radius. No chunk tile-entity scan occurs.
411 */
412 void cycleNearbyContainers() {
413 int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4));
414 boolean cycling = plugin.getConfig().getBoolean("cycling.enabled", true);
415 Set<BlockKey> targets = new HashSet<>();
416 Set<ChunkKey> visitedChunks = new HashSet<>();
417
418 for (Player player : Bukkit.getOnlinePlayers()) {
419 Chunk center = player.getLocation().getChunk();
420 World world = player.getWorld();
421 for (int dx = -radius; dx <= radius; dx++) {
422 for (int dz = -radius; dz <= radius; dz++) {
423 int chunkX = center.getX() + dx;
424 int chunkZ = center.getZ() + dz;
425 if (!world.isChunkLoaded(chunkX, chunkZ)) continue;
426 ChunkKey chunkKey = new ChunkKey(world.getUID(), chunkX, chunkZ);
427 if (!visitedChunks.add(chunkKey)) continue;
428 Set<BlockKey> known = knownContainers.get(chunkKey);
429 if (known != null) targets.addAll(known);
430 }
431 }
432 }
433
434 for (BlockKey key : targets) {
435 World world = Bukkit.getWorld(key.worldId());
436 if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue;
437 Block block = world.getBlockAt(key.x(), key.y(), key.z());
438 if (!isSupported(block)) {
439 removeForPhysicalBlock(key);
440 continue;
441 }
442
443 if (cycling || !previews.containsKey(key)) {
444 refresh(block);
445 } else {
446 PreviewState state = previews.get(key);
447 if (state != null) syncViewers(key, state, false, false, false);
448 }
449 }
450
451 pruneViewers();
452 }
453
454 void enqueueLoadedChunks() {
455 for (World world : Bukkit.getWorlds()) {
456 for (Chunk chunk : world.getLoadedChunks()) discoverChunk(chunk);
457 }
458 }
459
460 void cleanupAll() {
461 destroyAllPacketDisplays();
462 scanQueue.clear();
463 queued.clear();
464 knownContainers.clear();
465 for (World world : Bukkit.getWorlds()) {
466 for (Chunk chunk : world.getLoadedChunks()) cleanupLegacyDisplays(chunk);
467 }
468 }
469
470 void shutdown() {
471 destroyAllPacketDisplays();
472 scanQueue.clear();
473 queued.clear();
474 knownContainers.clear();
475 }
476
477 private void destroyAllPacketDisplays() {
478 for (PreviewState state : previews.values()) {
479 for (UUID viewerId : new HashSet<>(state.viewers)) {
480 Player viewer = Bukkit.getPlayer(viewerId);
481 if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId);
482 }
483 state.viewers.clear();
484 }
485 previews.clear();
486 }
487
488 void removeForPhysicalBlock(BlockKey physical) {
489 Block block = physical.getBlock();
490 if (block != null && isSupported(block)) {
491 ContainerTarget target = ContainerTarget.fromBlock(block);
492 if (target != null) {
493 forgetKnownKey(target.key());
494 destroyPreview(target.key());
495 }
496 }
497 forgetKnownKey(physical);
498 destroyPreview(physical);
499 }
500
501 private static Location copyLocation(Location source) {
502 return new Location(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getYaw(), source.getPitch());
503 }
504
505 private static boolean sameLocation(Location a, Location b) {
506 if (a.getWorld() == null || b.getWorld() == null) return false;
507 return a.getWorld().getUID().equals(b.getWorld().getUID())
508 && Double.compare(a.getX(), b.getX()) == 0
509 && Double.compare(a.getY(), b.getY()) == 0
510 && Double.compare(a.getZ(), b.getZ()) == 0
511 && Float.compare(a.getYaw(), b.getYaw()) == 0
512 && Float.compare(a.getPitch(), b.getPitch()) == 0;
513 }
514
515 private static boolean sameItem(ItemStack a, ItemStack b) {
516 return a.getAmount() == b.getAmount() && a.isSimilar(b);
517 }
518
519 private static float radians(double degrees) {
520 return (float) Math.toRadians(degrees);
521 }
522
523 /** Equivalent to JOML Quaternionf().rotateXYZ(x, y, z) used by 1.0.8. */
524 private static Quaternion4f quaternionXYZ(float x, float y, float z) {
525 float sx = (float) Math.sin(x * 0.5f);
526 float cx = (float) Math.cos(x * 0.5f);
527 float sy = (float) Math.sin(y * 0.5f);
528 float cy = (float) Math.cos(y * 0.5f);
529 float sz = (float) Math.sin(z * 0.5f);
530 float cz = (float) Math.cos(z * 0.5f);
531
532 float qx = sx * cy * cz + cx * sy * sz;
533 float qy = cx * sy * cz - sx * cy * sz;
534 float qz = cx * cy * sz + sx * sy * cz;
535 float qw = cx * cy * cz - sx * sy * sz;
536 return new Quaternion4f(qx, qy, qz, qw);
537 }
538
539 private static final class PreviewState {
540 private final int entityId;
541 private final UUID entityUuid;
542 private final Set<UUID> viewers = new HashSet<>();
543 private Location location;
544 private ItemStack item;
545 private VisualSpec visual;
546
547 private PreviewState(int entityId, UUID entityUuid, Location location, ItemStack item, VisualSpec visual) {
548 this.entityId = entityId;
549 this.entityUuid = entityUuid;
550 this.location = location;
551 this.item = item;
552 this.visual = visual;
553 }
554 }
555
556 private record VisualSpec(float scale, float pitch, float yaw, float roll, byte itemTransform, boolean glowing) {}
557
558 private record ChunkKey(UUID worldId, int x, int z) {
559 static ChunkKey of(Chunk chunk) {
560 return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ());
561 }
562
563 static ChunkKey of(BlockKey key) {
564 return new ChunkKey(key.worldId(), key.x() >> 4, key.z() >> 4);
565 }
566 }
567}