diff --git a/leaf-server/minecraft-patches/features/0279-Raytrace-Entity-Tracker.patch b/leaf-server/minecraft-patches/features/0279-Raytrace-Entity-Tracker.patch new file mode 100644 index 0000000000..b222b0d944 --- /dev/null +++ b/leaf-server/minecraft-patches/features/0279-Raytrace-Entity-Tracker.patch @@ -0,0 +1,181 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: HaHaWTH <102713261+HaHaWTH@users.noreply.github.com> +Date: Sun, 7 Nov 2077 00:00:00 +1400 +Subject: [PATCH] Raytrace Entity Tracker + +Original project: https://github.com/tr7zw/EntityCulling +Original license: Custom License + +Original project: https://github.com/LogisticsCraft/OcclusionCulling +Original license: MIT + +Ported by: https://github.com/LuminolMC/Luminol +Fixed and updated by: https://github.com/Winds-Studio/Leaf + +TODO: +Check diff https://github.com/tr7zw/EntityCulling/compare/5774b56c6d7881fe3407ab80b662b94150dffafc...main + +EntityCulling commit: null + +diff --git a/net/minecraft/server/level/ChunkMap.java b/net/minecraft/server/level/ChunkMap.java +index 9803c395fce103cb7bc746f43a017ff9ed99728c..1cdc7f01f99355c2d9ebd6b76654c45921c20cff 100644 +--- a/net/minecraft/server/level/ChunkMap.java ++++ b/net/minecraft/server/level/ChunkMap.java +@@ -1487,7 +1487,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider + double d1 = vec3_dx * vec3_dx + vec3_dz * vec3_dz; // Paper + double d2 = d * d; + // Paper start - Configurable entity tracking range by Y +- boolean flag = d1 <= d2; ++ boolean flag = d1 <= d2 && !entity.isCulled(player); // Leaf - Raytrace Entity Tracker + if (flag && level.paperConfig().entities.trackingRangeY.enabled) { + double rangeY = level.paperConfig().entities.trackingRangeY.get(this.entity, -1); + if (rangeY != -1) { +diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java +index e7b375720c1bb78a9c3edf6d49c973eba1fcf115..0df23c381891fc9b8362b01196bfcc56c2e1903d 100644 +--- a/net/minecraft/world/entity/Entity.java ++++ b/net/minecraft/world/entity/Entity.java +@@ -145,7 +145,7 @@ import net.minecraft.world.waypoints.WaypointTransmitter; + import org.jetbrains.annotations.Contract; + import org.slf4j.Logger; + +-public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess, ScoreHolder, DataComponentGetter, ca.spottedleaf.moonrise.patches.chunk_system.entity.ChunkSystemEntity, ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity { // Paper - rewrite chunk system // Paper - optimise entity tracker ++public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess, ScoreHolder, DataComponentGetter, ca.spottedleaf.moonrise.patches.chunk_system.entity.ChunkSystemEntity, ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity, dev.tr7zw.entityculling.versionless.access.Cullable { // Paper - rewrite chunk system // Paper - optimise entity tracker // Leaf - Raytrace entity tracker + public static javax.script.ScriptEngine scriptEngine = new javax.script.ScriptEngineManager().getEngineByName("rhino"); // Purpur - Configurable entity base attributes + // CraftBukkit start + private static final int CURRENT_LEVEL = 2; +@@ -5296,6 +5296,7 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess + return; + } + // Paper end - rewrite chunk system ++ dev.tr7zw.entityculling.CullTask.onEntityRemoval(this); // Leaf - Raytrace entity tracker + org.bukkit.craftbukkit.event.CraftEventFactory.callEntityRemoveEvent(this, cause); // CraftBukkit + final boolean alreadyRemoved = this.removalReason != null; // Paper - Folia schedulers + if (this.removalReason == null) { +@@ -5600,4 +5601,36 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess + return this.distanceToSqr(entity.position()); + } + // Leaf end - Optimize Entity distanceToSqr ++ ++ // Leaf start - Raytrace entity tracker ++ private long lastTime = 0; ++ ++ @Override ++ public void setTimeout() { ++ this.lastTime = System.currentTimeMillis() + 1000; ++ } ++ ++ @Override ++ public boolean isForcedVisible() { ++ return this.lastTime > System.currentTimeMillis(); ++ } ++ ++ @Override ++ public void setCulled(boolean value, Player player) { ++ dev.tr7zw.entityculling.CullTask task = player.cullTask; ++ if (task == null) return; ++ task.setCulled(this, value); ++ if (!value) { ++ setTimeout(); ++ } ++ } ++ ++ @Override ++ public boolean isCulled(Player player) { ++ if (!org.dreeam.leaf.config.modules.misc.RaytraceTracker.enabled) return false; ++ dev.tr7zw.entityculling.CullTask task = player.cullTask; ++ if (task == null) return false; ++ return task.isEntityCulled(this); ++ } ++ // Leaf end - Raytrace entity tracker + } +diff --git a/net/minecraft/world/entity/EntityType.java b/net/minecraft/world/entity/EntityType.java +index e65b1818c49e1b7d04d5bcc912804c821f00bdbc..7ea2cdf57fc1b2d28b7b60f9beaa529640ebd4d5 100644 +--- a/net/minecraft/world/entity/EntityType.java ++++ b/net/minecraft/world/entity/EntityType.java +@@ -1086,6 +1086,7 @@ public class EntityType implements FeatureElement, EntityTypeT + private final int clientTrackingRange; + private final int updateInterval; + public boolean dabEnabled = false; // Pufferfish ++ public boolean skipRaytraceCheck = false; // Leaf - Raytrace Entity Tracker + private final String descriptionId; + @Nullable + private Component description; +diff --git a/net/minecraft/world/entity/player/Player.java b/net/minecraft/world/entity/player/Player.java +index 108ef0759e4060fc02d517175731f413c7e2532f..3dbe2fca96439f7202ffe9bd73b43d3f79f5223d 100644 +--- a/net/minecraft/world/entity/player/Player.java ++++ b/net/minecraft/world/entity/player/Player.java +@@ -223,6 +223,11 @@ public abstract class Player extends LivingEntity { + public int burpDelay = 0; // Purpur - Burp delay + public boolean canPortalInstant = false; // Purpur - Add portal permission bypass + public int sixRowEnderchestSlotCount = -1; // Purpur - Barrels and enderchests 6 rows ++ // Leaf start - Raytrace Entity Tracker ++ @Nullable public dev.tr7zw.entityculling.CullTask cullTask; ++ @Nullable private Level lastCullWorld; ++ private final boolean needToCull = !(this instanceof org.leavesmc.leaves.replay.ServerPhotographer); ++ // Leaf end - Raytrace Entity Tracker + + // CraftBukkit start + public boolean fauxSleeping; +@@ -320,6 +325,37 @@ public abstract class Player extends LivingEntity { + } + // Purpur end - Burp delay + ++ // Leaf start - Raytrace Entity Tracker ++ if (this.needToCull) { ++ if (!org.dreeam.leaf.config.modules.misc.RaytraceTracker.enabled) { ++ if (this.cullTask != null) { ++ this.cullTask.signalStop(); ++ this.cullTask = null; ++ } ++ } else { ++ Level currLevel = this.level(); ++ boolean needsUpdate = this.cullTask == null || this.lastCullWorld != currLevel; ++ ++ if (needsUpdate) { ++ if (this.cullTask != null) { ++ this.cullTask.signalStop(); ++ } ++ final com.logisticscraft.occlusionculling.OcclusionCullingInstance culling = new com.logisticscraft.occlusionculling.OcclusionCullingInstance( ++ org.dreeam.leaf.config.modules.misc.RaytraceTracker.maxTraceDistance, ++ new dev.tr7zw.entityculling.DefaultChunkDataProvider(currLevel) ++ ); ++ this.cullTask = new dev.tr7zw.entityculling.CullTask( ++ culling, ++ this, ++ org.dreeam.leaf.config.modules.misc.RaytraceTracker.boundingBoxLimit, ++ org.dreeam.leaf.config.modules.misc.RaytraceTracker.traceInterval ++ ); ++ this.cullTask.setup(); ++ this.lastCullWorld = currLevel; ++ } ++ } ++ } ++ // Leaf end - Raytrace Entity Tracker + this.noPhysics = this.isSpectator(); + if (this.isSpectator() || this.isPassenger()) { + this.setOnGround(false); +@@ -1493,6 +1529,12 @@ public abstract class Player extends LivingEntity { + if (this.containerMenu != null && this.hasContainerOpen()) { + this.doCloseContainer(); + } ++ // Leaf start - Raytrace Entity Tracker ++ if (this.cullTask != null) { ++ this.cullTask.signalStop(); ++ this.cullTask = null; ++ } ++ // Leaf end - Raytrace Entity Tracker + } + + @Override +diff --git a/net/minecraft/world/level/Level.java b/net/minecraft/world/level/Level.java +index 2a1c89bb6712c97ad48b9f64c26f36afe8c811e4..3b3199b0bb2729ac3a8dd08467a9b6e6ebdbda1e 100644 +--- a/net/minecraft/world/level/Level.java ++++ b/net/minecraft/world/level/Level.java +@@ -1185,6 +1185,7 @@ public abstract class Level implements LevelAccessor, UUIDLookup, AutoCl + } + // Imanity end - AntiXraySDK integration + this.chunkPacketBlockController.onBlockChange(this, pos, state, blockState, flags, recursionLeft); // Paper - Anti-Xray ++ dev.tr7zw.entityculling.CullTask.onBlockChange(this, pos); // Leaf - Raytrace Entity Tracker + // CraftBukkit end + if (blockState == null) { + // CraftBukkit start - remove blockstate if failed (or the same) diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/DataProvider.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/DataProvider.java new file mode 100644 index 0000000000..5ab4600554 --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/DataProvider.java @@ -0,0 +1,34 @@ +package com.logisticscraft.occlusionculling; + +import com.logisticscraft.occlusionculling.util.Vec3d; + +public interface DataProvider { + + /** + * Prepares the requested chunk. Returns true if the chunk is ready, false when + * not loaded. Should not reload the chunk when the x and y are the same as the + * last request! + * + * @param chunkX + * @param chunkZ + * @return + */ + boolean prepareChunk(int chunkX, int chunkZ); + + /** + * Location is inside the chunk. + * + * @param x + * @param y + * @param z + * @return + */ + boolean isOpaqueFullCube(int x, int y, int z); + + default void cleanup() { + } + + default void checkingPosition(Vec3d[] targetPoints, int size, Vec3d viewerPosition) { + } + +} diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/OcclusionCullingInstance.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/OcclusionCullingInstance.java new file mode 100644 index 0000000000..921f905d00 --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/OcclusionCullingInstance.java @@ -0,0 +1,511 @@ +package com.logisticscraft.occlusionculling; + +import com.logisticscraft.occlusionculling.cache.ArrayOcclusionCache; +import com.logisticscraft.occlusionculling.cache.OcclusionCache; +import com.logisticscraft.occlusionculling.util.MathUtilities; +import com.logisticscraft.occlusionculling.util.Vec3d; + +import java.util.Arrays; +import java.util.BitSet; + +public class OcclusionCullingInstance { + + private static final int ON_MIN_X = 0x01; + private static final int ON_MAX_X = 0x02; + private static final int ON_MIN_Y = 0x04; + private static final int ON_MAX_Y = 0x08; + private static final int ON_MIN_Z = 0x10; + private static final int ON_MAX_Z = 0x20; + + private final int reach; + private final double aabbExpansion; + private final DataProvider provider; + private final OcclusionCache cache; + + // Reused allocated data structures + private final BitSet skipList = new BitSet(); // Grows bigger in case some mod introduces giant hitboxes + private final Vec3d[] targetPoints = new Vec3d[15]; + private final Vec3d targetPos = new Vec3d(0, 0, 0); + private final int[] cameraPos = new int[3]; + private final boolean[] dotselectors = new boolean[14]; + private boolean allowRayChecks = false; + private final int[] lastHitBlock = new int[3]; + private boolean allowWallClipping = false; + + + public OcclusionCullingInstance(int maxDistance, DataProvider provider) { + this(maxDistance, provider, new ArrayOcclusionCache(maxDistance), org.dreeam.leaf.config.modules.misc.RaytraceTracker.boundingBoxExpansion); + } + + public OcclusionCullingInstance(int maxDistance, DataProvider provider, OcclusionCache cache, double aabbExpansion) { + this.reach = maxDistance; + this.provider = provider; + this.cache = cache; + this.aabbExpansion = aabbExpansion; + for (int i = 0; i < targetPoints.length; i++) { + targetPoints[i] = new Vec3d(0, 0, 0); + } + } + + public boolean isAABBVisible(Vec3d aabbMin, Vec3d aabbMax, Vec3d viewerPosition) { + try { + int maxX = MathUtilities.floor(aabbMax.x + + aabbExpansion); + int maxY = MathUtilities.floor(aabbMax.y + + aabbExpansion); + int maxZ = MathUtilities.floor(aabbMax.z + + aabbExpansion); + int minX = MathUtilities.floor(aabbMin.x + - aabbExpansion); + int minY = MathUtilities.floor(aabbMin.y + - aabbExpansion); + int minZ = MathUtilities.floor(aabbMin.z + - aabbExpansion); + + cameraPos[0] = MathUtilities.floor(viewerPosition.x); + cameraPos[1] = MathUtilities.floor(viewerPosition.y); + cameraPos[2] = MathUtilities.floor(viewerPosition.z); + + Relative relX = Relative.from(minX, maxX, cameraPos[0]); + Relative relY = Relative.from(minY, maxY, cameraPos[1]); + Relative relZ = Relative.from(minZ, maxZ, cameraPos[2]); + + if (relX == Relative.INSIDE && relY == Relative.INSIDE && relZ == Relative.INSIDE) { + return true; // We are inside of the AABB, don't cull + } + + skipList.clear(); + + // Just check the cache first + int id = 0; + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + int cachedValue = getCacheValue(x, y, z); + + if (cachedValue == 1) { + // non-occluding + return true; + } + + if (cachedValue != 0) { + // was checked and it wasn't visible + skipList.set(id); + } + id++; + } + } + } + + // only after the first hit wall the cache becomes valid. + allowRayChecks = false; + + // since the cache wasn't helpfull + id = 0; + for (int x = minX; x <= maxX; x++) { + byte visibleOnFaceX = 0; + byte faceEdgeDataX = 0; + faceEdgeDataX |= (x == minX) ? ON_MIN_X : 0; + faceEdgeDataX |= (x == maxX) ? ON_MAX_X : 0; + visibleOnFaceX |= (x == minX && relX == Relative.POSITIVE) ? ON_MIN_X : 0; + visibleOnFaceX |= (x == maxX && relX == Relative.NEGATIVE) ? ON_MAX_X : 0; + for (int y = minY; y <= maxY; y++) { + byte faceEdgeDataY = faceEdgeDataX; + byte visibleOnFaceY = visibleOnFaceX; + faceEdgeDataY |= (y == minY) ? ON_MIN_Y : 0; + faceEdgeDataY |= (y == maxY) ? ON_MAX_Y : 0; + visibleOnFaceY |= (y == minY && relY == Relative.POSITIVE) ? ON_MIN_Y : 0; + visibleOnFaceY |= (y == maxY && relY == Relative.NEGATIVE) ? ON_MAX_Y : 0; + for (int z = minZ; z <= maxZ; z++) { + byte faceEdgeData = faceEdgeDataY; + byte visibleOnFace = visibleOnFaceY; + faceEdgeData |= (z == minZ) ? ON_MIN_Z : 0; + faceEdgeData |= (z == maxZ) ? ON_MAX_Z : 0; + visibleOnFace |= (z == minZ && relZ == Relative.POSITIVE) ? ON_MIN_Z : 0; + visibleOnFace |= (z == maxZ && relZ == Relative.NEGATIVE) ? ON_MAX_Z : 0; + if (skipList.get(id)) { // was checked and it wasn't visible + id++; + continue; + } + + if (visibleOnFace != 0) { + targetPos.set(x, y, z); + if (isVoxelVisible(viewerPosition, targetPos, faceEdgeData, visibleOnFace)) { + return true; + } + } + id++; + } + } + } + + return false; + } catch (Throwable t) { + // Failsafe + t.printStackTrace(); + } + return true; + } + + /** + * @param viewerPosition + * @param position + * @param faceData contains rather this Block is on the outside for a given face + * @param visibleOnFace contains rather a face should be concidered + * @return + */ + private boolean isVoxelVisible(Vec3d viewerPosition, Vec3d position, byte faceData, byte visibleOnFace) { + int targetSize = 0; + Arrays.fill(dotselectors, false); + if ((visibleOnFace & ON_MIN_X) == ON_MIN_X) { + dotselectors[0] = true; + if ((faceData & ~ON_MIN_X) != 0) { + dotselectors[1] = true; + dotselectors[4] = true; + dotselectors[5] = true; + } + dotselectors[8] = true; + } + if ((visibleOnFace & ON_MIN_Y) == ON_MIN_Y) { + dotselectors[0] = true; + if ((faceData & ~ON_MIN_Y) != 0) { + dotselectors[3] = true; + dotselectors[4] = true; + dotselectors[7] = true; + } + dotselectors[9] = true; + } + if ((visibleOnFace & ON_MIN_Z) == ON_MIN_Z) { + dotselectors[0] = true; + if ((faceData & ~ON_MIN_Z) != 0) { + dotselectors[1] = true; + dotselectors[4] = true; + dotselectors[5] = true; + } + dotselectors[10] = true; + } + if ((visibleOnFace & ON_MAX_X) == ON_MAX_X) { + dotselectors[4] = true; + if ((faceData & ~ON_MAX_X) != 0) { + dotselectors[5] = true; + dotselectors[6] = true; + dotselectors[7] = true; + } + dotselectors[11] = true; + } + if ((visibleOnFace & ON_MAX_Y) == ON_MAX_Y) { + dotselectors[1] = true; + if ((faceData & ~ON_MAX_Y) != 0) { + dotselectors[2] = true; + dotselectors[5] = true; + dotselectors[6] = true; + } + dotselectors[12] = true; + } + if ((visibleOnFace & ON_MAX_Z) == ON_MAX_Z) { + dotselectors[2] = true; + if ((faceData & ~ON_MAX_Z) != 0) { + dotselectors[3] = true; + dotselectors[6] = true; + dotselectors[7] = true; + } + dotselectors[13] = true; + } + + if (dotselectors[0]) targetPoints[targetSize++].setAdd(position, 0.05, 0.05, 0.05); + if (dotselectors[1]) targetPoints[targetSize++].setAdd(position, 0.05, 0.95, 0.05); + if (dotselectors[2]) targetPoints[targetSize++].setAdd(position, 0.05, 0.95, 0.95); + if (dotselectors[3]) targetPoints[targetSize++].setAdd(position, 0.05, 0.05, 0.95); + if (dotselectors[4]) targetPoints[targetSize++].setAdd(position, 0.95, 0.05, 0.05); + if (dotselectors[5]) targetPoints[targetSize++].setAdd(position, 0.95, 0.95, 0.05); + if (dotselectors[6]) targetPoints[targetSize++].setAdd(position, 0.95, 0.95, 0.95); + if (dotselectors[7]) targetPoints[targetSize++].setAdd(position, 0.95, 0.05, 0.95); + // middle points + if (dotselectors[8]) targetPoints[targetSize++].setAdd(position, 0.05, 0.5, 0.5); + if (dotselectors[9]) targetPoints[targetSize++].setAdd(position, 0.5, 0.05, 0.5); + if (dotselectors[10]) targetPoints[targetSize++].setAdd(position, 0.5, 0.5, 0.05); + if (dotselectors[11]) targetPoints[targetSize++].setAdd(position, 0.95, 0.5, 0.5); + if (dotselectors[12]) targetPoints[targetSize++].setAdd(position, 0.5, 0.95, 0.5); + if (dotselectors[13]) targetPoints[targetSize++].setAdd(position, 0.5, 0.5, 0.95); + + return isVisible(viewerPosition, targetPoints, targetSize); + } + + private boolean rayIntersection(int[] b, Vec3d rayOrigin, Vec3d rayDir) { + Vec3d rInv = new Vec3d(1, 1, 1).div(rayDir); + + double t1 = (b[0] - rayOrigin.x) * rInv.x; + double t2 = (b[0] + 1 - rayOrigin.x) * rInv.x; + double t3 = (b[1] - rayOrigin.y) * rInv.y; + double t4 = (b[1] + 1 - rayOrigin.y) * rInv.y; + double t5 = (b[2] - rayOrigin.z) * rInv.z; + double t6 = (b[2] + 1 - rayOrigin.z) * rInv.z; + + double tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6)); + double tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); + + // if tmax > 0, ray (line) is intersecting AABB, but the whole AABB is behind us + if (tmax > 0) { + return false; + } + + // if tmin > tmax, ray doesn't intersect AABB + return !(tmin > tmax); + } + + /** + * returns the grid cells that intersect with this Vec3d
+ * http://playtechs.blogspot.de/2007/03/raytracing-on-grid.html + *

+ * Caching assumes that all Vec3d's are inside the same block + */ + private boolean isVisible(Vec3d start, Vec3d[] targets, int size) { + // start cell coordinate + int x = cameraPos[0]; + int y = cameraPos[1]; + int z = cameraPos[2]; + + for (int v = 0; v < size; v++) { + // ray-casting target + Vec3d target = targets[v]; + + double relativeX = start.x - target.getX(); + double relativeY = start.y - target.getY(); + double relativeZ = start.z - target.getZ(); + + if (allowRayChecks && rayIntersection(lastHitBlock, start, new Vec3d(relativeX, relativeY, relativeZ).normalize())) { + continue; + } + + // horizontal and vertical cell amount spanned + double dimensionX = Math.abs(relativeX); + double dimensionY = Math.abs(relativeY); + double dimensionZ = Math.abs(relativeZ); + + // distance between horizontal intersection points with cell border as a + // fraction of the total Vec3d length + double dimFracX = 1f / dimensionX; + // distance between vertical intersection points with cell border as a fraction + // of the total Vec3d length + double dimFracY = 1f / dimensionY; + double dimFracZ = 1f / dimensionZ; + + // total amount of intersected cells + int intersectCount = 1; + + // 1, 0 or -1 + // determines the direction of the next cell (horizontally / vertically) + int x_inc, y_inc, z_inc; + + // the distance to the next horizontal / vertical intersection point with a cell + // border as a fraction of the total Vec3d length + double t_next_y, t_next_x, t_next_z; + + if (dimensionX == 0f) { + x_inc = 0; + t_next_x = dimFracX; // don't increment horizontally because the Vec3d is perfectly vertical + } else if (target.x > start.x) { + x_inc = 1; // target point is horizontally greater than starting point so increment every + // step by 1 + intersectCount += MathUtilities.floor(target.x) - x; // increment total amount of intersecting cells + t_next_x = (float) ((x + 1 - start.x) * dimFracX); // calculate the next horizontal + // intersection + // point based on the position inside + // the first cell + } else { + x_inc = -1; // target point is horizontally smaller than starting point so reduce every step + // by 1 + intersectCount += x - MathUtilities.floor(target.x); // increment total amount of intersecting cells + t_next_x = (float) ((start.x - x) + * dimFracX); // calculate the next horizontal + // intersection point + // based on the position inside + // the first cell + } + + if (dimensionY == 0f) { + y_inc = 0; + t_next_y = dimFracY; // don't increment vertically because the Vec3d is perfectly horizontal + } else if (target.y > start.y) { + y_inc = 1; // target point is vertically greater than starting point so increment every + // step by 1 + intersectCount += MathUtilities.floor(target.y) - y; // increment total amount of intersecting cells + t_next_y = (float) ((y + 1 - start.y) + * dimFracY); // calculate the next vertical + // intersection + // point based on the position inside + // the first cell + } else { + y_inc = -1; // target point is vertically smaller than starting point so reduce every step + // by 1 + intersectCount += y - MathUtilities.floor(target.y); // increment total amount of intersecting cells + t_next_y = (float) ((start.y - y) + * dimFracY); // calculate the next vertical intersection + // point + // based on the position inside + // the first cell + } + + if (dimensionZ == 0f) { + z_inc = 0; + t_next_z = dimFracZ; // don't increment vertically because the Vec3d is perfectly horizontal + } else if (target.z > start.z) { + z_inc = 1; // target point is vertically greater than starting point so increment every + // step by 1 + intersectCount += MathUtilities.floor(target.z) - z; // increment total amount of intersecting cells + t_next_z = (float) ((z + 1 - start.z) + * dimFracZ); // calculate the next vertical + // intersection + // point based on the position inside + // the first cell + } else { + z_inc = -1; // target point is vertically smaller than starting point so reduce every step + // by 1 + intersectCount += z - MathUtilities.floor(target.z); // increment total amount of intersecting cells + t_next_z = (float) ((start.z - z) + * dimFracZ); // calculate the next vertical intersection + // point + // based on the position inside + // the first cell + } + + boolean finished = stepRay(start, x, y, z, + dimFracX, dimFracY, dimFracZ, intersectCount, x_inc, y_inc, + z_inc, t_next_y, t_next_x, t_next_z); + provider.cleanup(); + if (finished) { + cacheResult(targets[0], true); + return true; + } else { + allowRayChecks = true; + } + } + cacheResult(targets[0], false); + return false; + } + + private boolean stepRay(Vec3d start, int currentX, int currentY, + int currentZ, double distInX, double distInY, + double distInZ, int n, int x_inc, int y_inc, + int z_inc, double t_next_y, double t_next_x, + double t_next_z) { + allowWallClipping = true; // initially allow rays to go through walls till they are on the outside + // iterate through all intersecting cells (n times) + for (; n > 1; n--) { // n-1 times because we don't want to check the last block + // towards - where from + + + // get cached value, 0 means uncached (default) + int cVal = getCacheValue(currentX, currentY, currentZ); + + if (cVal == 2 && !allowWallClipping) { + // block cached as occluding, stop ray + lastHitBlock[0] = currentX; + lastHitBlock[1] = currentY; + lastHitBlock[2] = currentZ; + return false; + } + + if (cVal == 0) { + // save current cell + int chunkX = currentX >> 4; + int chunkZ = currentZ >> 4; + + if (!provider.prepareChunk(chunkX, chunkZ)) { // Chunk not ready + return false; + } + + if (provider.isOpaqueFullCube(currentX, currentY, currentZ)) { + if (!allowWallClipping) { + cache.setLastHidden(); + lastHitBlock[0] = currentX; + lastHitBlock[1] = currentY; + lastHitBlock[2] = currentZ; + return false; + } + } else { + // outside of wall, now clipping is not allowed + allowWallClipping = false; + cache.setLastVisible(); + } + } + + if (cVal == 1) { + // outside of wall, now clipping is not allowed + allowWallClipping = false; + } + + + if (t_next_y < t_next_x && t_next_y < t_next_z) { // next cell is upwards/downwards because the distance to + // the next vertical + // intersection point is smaller than to the next horizontal intersection point + currentY += y_inc; // move up/down + t_next_y += distInY; // update next vertical intersection point + } else if (t_next_x < t_next_y && t_next_x < t_next_z) { // next cell is right/left + currentX += x_inc; // move right/left + t_next_x += distInX; // update next horizontal intersection point + } else { + currentZ += z_inc; // move right/left + t_next_z += distInZ; // update next horizontal intersection point + } + + } + return true; + } + + // -1 = invalid location, 0 = not checked yet, 1 = visible, 2 = occluding + private int getCacheValue(int x, int y, int z) { + x -= cameraPos[0]; + y -= cameraPos[1]; + z -= cameraPos[2]; + if (Math.abs(x) > reach - 2 || Math.abs(y) > reach - 2 + || Math.abs(z) > reach - 2) { + return -1; + } + + // check if target is already known + return cache.getState(x + reach, y + reach, z + reach); + } + + + private void cacheResult(int x, int y, int z, boolean result) { + int cx = x - cameraPos[0] + reach; + int cy = y - cameraPos[1] + reach; + int cz = z - cameraPos[2] + reach; + if (result) { + cache.setVisible(cx, cy, cz); + } else { + cache.setHidden(cx, cy, cz); + } + } + + private void cacheResult(Vec3d vector, boolean result) { + int cx = MathUtilities.floor(vector.x) - cameraPos[0] + reach; + int cy = MathUtilities.floor(vector.y) - cameraPos[1] + reach; + int cz = MathUtilities.floor(vector.z) - cameraPos[2] + reach; + if (result) { + cache.setVisible(cx, cy, cz); + } else { + cache.setHidden(cx, cy, cz); + } + } + + public void resetCache() { + this.cache.resetCache(); + } + + private enum Relative { + INSIDE, POSITIVE, NEGATIVE; + + public static Relative from(int min, int max, int pos) { + if (max > pos && min > pos) { + return POSITIVE; + } else if (min < pos && max < pos) { + return NEGATIVE; + } + return INSIDE; + } + } + +} diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/ArrayOcclusionCache.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/ArrayOcclusionCache.java new file mode 100644 index 0000000000..08f0ddb343 --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/ArrayOcclusionCache.java @@ -0,0 +1,57 @@ +package com.logisticscraft.occlusionculling.cache; + +import java.util.Arrays; + +public class ArrayOcclusionCache implements OcclusionCache { + + private final int reachX2; + private final byte[] cache; + private int positionKey; + private int entry; + private int offset; + + public ArrayOcclusionCache(int reach) { + this.reachX2 = reach * 2; + this.cache = new byte[(reachX2 * reachX2 * reachX2) / 4]; + } + + @Override + public void resetCache() { + Arrays.fill(cache, (byte) 0); + } + + @Override + public void setVisible(int x, int y, int z) { + positionKey = x + y * reachX2 + z * reachX2 * reachX2; + entry = positionKey / 4; + offset = (positionKey % 4) * 2; + cache[entry] |= 1 << offset; + } + + @Override + public void setHidden(int x, int y, int z) { + positionKey = x + y * reachX2 + z * reachX2 * reachX2; + entry = positionKey / 4; + offset = (positionKey % 4) * 2; + cache[entry] |= 1 << offset + 1; + } + + @Override + public int getState(int x, int y, int z) { + positionKey = x + y * reachX2 + z * reachX2 * reachX2; + entry = positionKey / 4; + offset = (positionKey % 4) * 2; + return cache[entry] >> offset & 3; + } + + @Override + public void setLastVisible() { + cache[entry] |= 1 << offset; + } + + @Override + public void setLastHidden() { + cache[entry] |= 1 << offset + 1; + } + +} diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/OcclusionCache.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/OcclusionCache.java new file mode 100644 index 0000000000..2a2e5620fb --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/cache/OcclusionCache.java @@ -0,0 +1,17 @@ +package com.logisticscraft.occlusionculling.cache; + +public interface OcclusionCache { + + void resetCache(); + + void setVisible(int x, int y, int z); + + void setHidden(int x, int y, int z); + + int getState(int x, int y, int z); + + void setLastHidden(); + + void setLastVisible(); + +} diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/MathUtilities.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/MathUtilities.java new file mode 100644 index 0000000000..fb28265631 --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/MathUtilities.java @@ -0,0 +1,25 @@ +package com.logisticscraft.occlusionculling.util; + +/** + * Contains MathHelper methods + */ +public final class MathUtilities { + + private MathUtilities() { + } + + public static int floor(double d) { + int i = (int) d; + return d < (double) i ? i - 1 : i; + } + + public static int fastFloor(double d) { + return (int) (d + 1024.0) - 1024; + } + + public static int ceil(double d) { + int i = (int) d; + return d > (double) i ? i + 1 : i; + } + +} diff --git a/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/Vec3d.java b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/Vec3d.java new file mode 100644 index 0000000000..879499768d --- /dev/null +++ b/leaf-server/src/main/java/com/logisticscraft/occlusionculling/util/Vec3d.java @@ -0,0 +1,86 @@ +package com.logisticscraft.occlusionculling.util; + +public class Vec3d { + + public double x; + public double y; + public double z; + + public Vec3d(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public void setAdd(Vec3d vec, double x, double y, double z) { + this.x = vec.x + x; + this.y = vec.y + y; + this.z = vec.z + z; + } + + public Vec3d div(Vec3d rayDir) { + this.x /= rayDir.x; + this.z /= rayDir.z; + this.y /= rayDir.y; + return this; + } + + public Vec3d normalize() { + double mag = Math.sqrt(x * x + y * y + z * z); + this.x /= mag; + this.y /= mag; + this.z /= mag; + return this; + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Vec3d vec3d)) { + return false; + } + if (Double.compare(vec3d.x, x) != 0) { + return false; + } + if (Double.compare(vec3d.y, y) != 0) { + return false; + } + return Double.compare(vec3d.z, z) == 0; + } + + @Override + public int hashCode() { + long l = Double.doubleToLongBits(x); + int i = (int) (l ^ l >>> 32); + l = Double.doubleToLongBits(y); + i = 31 * i + (int) (l ^ l >>> 32); + l = Double.doubleToLongBits(z); + i = 31 * i + (int) (l ^ l >>> 32); + return i; + } + + @Override + public String toString() { + return "(" + x + ", " + y + ", " + z + ")"; + } + +} diff --git a/leaf-server/src/main/java/dev/tr7zw/entityculling/CullTask.java b/leaf-server/src/main/java/dev/tr7zw/entityculling/CullTask.java new file mode 100644 index 0000000000..3ec24488dd --- /dev/null +++ b/leaf-server/src/main/java/dev/tr7zw/entityculling/CullTask.java @@ -0,0 +1,212 @@ +package dev.tr7zw.entityculling; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.logisticscraft.occlusionculling.OcclusionCullingInstance; +import com.logisticscraft.occlusionculling.util.Vec3d; +import dev.tr7zw.entityculling.versionless.access.Cullable; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSets; +import net.minecraft.core.BlockPos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.players.PlayerList; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.dreeam.leaf.config.modules.misc.RaytraceTracker; + +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.*; + +public class CullTask implements Runnable { + + private static final String THREAD_PREFIX = "Leaf Raytrace Tracker"; + private volatile boolean scheduleNext = true; + private volatile boolean isInit = false; + + private final OcclusionCullingInstance culling; + private final Player checkTarget; + + private final int hitboxLimit; + + private final Vec3d lastPos = new Vec3d(0, 0, 0); + private final Vec3d aabbMin = new Vec3d(0, 0, 0); + private final Vec3d aabbMax = new Vec3d(0, 0, 0); + + private static final Executor backgroundWorker = Executors.newCachedThreadPool( + new ThreadFactoryBuilder() + .setNameFormat(THREAD_PREFIX + " Thread - %d") + .setDaemon(true) + .setPriority(Thread.NORM_PRIORITY - 1) + .build() + ); + + private static final Set tasks = ConcurrentHashMap.newKeySet(); + private final Set culledEntities = IntSets.synchronize(new IntOpenHashSet()); + private final Queue removalQueue = new ConcurrentLinkedQueue<>(); + + private final Executor worker; + + public CullTask( + OcclusionCullingInstance culling, + Player checkTarget, + int hitboxLimit, + long checkIntervalMs + ) { + this.culling = culling; + this.checkTarget = checkTarget; + this.hitboxLimit = hitboxLimit; + this.worker = CompletableFuture.delayedExecutor(checkIntervalMs, TimeUnit.MILLISECONDS, backgroundWorker); + } + + public void signalStop() { + this.scheduleNext = false; + tasks.remove(this); + } + + public void setup() { + if (!this.isInit) { + this.isInit = true; + } else { + return; + } + this.worker.execute(this); + tasks.add(this); + } + + @Override + public synchronized void run() { + try { + if (this.checkTarget.tickCount > 10) { + while (!removalQueue.isEmpty()) { + int entityId = removalQueue.poll(); + culledEntities.remove(entityId); + } + Vec3 cameraMC = this.checkTarget.getEyePosition(0); + if (!(cameraMC.x == lastPos.x && cameraMC.y == lastPos.y && cameraMC.z == lastPos.z)) { + lastPos.set(cameraMC.x, cameraMC.y, cameraMC.z); + synchronized (culling) { + culling.resetCache(); + } + } + cullEntities(cameraMC, lastPos); + } + } finally { + if (this.scheduleNext) { + this.worker.execute(this); + } + } + } + + private void cullEntities(Vec3 cameraMC, Vec3d camera) { + for (Entity entity : this.checkTarget.level().getEntities().getAll()) { // This one's safe here; moonrise returns an array for us to iterate + if (!(entity instanceof Cullable cullable) || entity == this.checkTarget) { + continue; + } + + if (entity.getType().skipRaytraceCheck) { + continue; + } + Player player = this.checkTarget; + + if (!cullable.isForcedVisible() || true) { // TODO + if (entity.isCurrentlyGlowing() || isSkippableArmorstand(entity)) { + cullable.setCulled(false, player); + continue; + } + + final double distanceSqr = entity.position().distanceToSqr(cameraMC); + if (distanceSqr < RaytraceTracker.forceVisibleRadius * RaytraceTracker.forceVisibleRadius) { + cullable.setCulled(false, player); + continue; + } + + if (distanceSqr >= RaytraceTracker.maxTraceDistance * RaytraceTracker.maxTraceDistance) { + cullable.setCulled(false, player); // If your entity view distance is larger than tracingDistance just + // render it + continue; + } + + AABB boundingBox = entity.getBoundingBox(); + if (boundingBox.getXsize() > hitboxLimit || boundingBox.getYsize() > hitboxLimit + || boundingBox.getZsize() > hitboxLimit) { + cullable.setCulled(false, player); // Too big to bother to cull + continue; + } + + aabbMin.set(boundingBox.minX, boundingBox.minY, boundingBox.minZ); + aabbMax.set(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ); + + synchronized (culling) { + boolean visible = culling.isAABBVisible(aabbMin, aabbMax, camera); + + cullable.setCulled(!visible, player); + } + } + } + } + + public static void onBlockChange(Level level, BlockPos pos) { + if (RaytraceTracker.enabled) { + MinecraftServer server = level.getServer(); + if (server == null) { // tbh this cant be null + return; + } + PlayerList playerList = server.getPlayerList(); + CompletableFuture.runAsync(() -> { + for (Player player : playerList.realPlayers) { + CullTask cullTask = player.cullTask; + if (cullTask == null) continue; + if (player.level() == level) { + int posX = pos.getX(); + int posY = pos.getY(); + int posZ = pos.getZ(); + BlockPos playerPos = player.blockPosition(); + final int playerX = playerPos.getX(), playerY = playerPos.getY(), playerZ = playerPos.getZ(); + if (Math.abs(posX - playerX) < RaytraceTracker.maxTraceDistance + && Math.abs(posY - playerY) < RaytraceTracker.maxTraceDistance + && Math.abs(posZ - playerZ) < RaytraceTracker.maxTraceDistance) { + synchronized (cullTask.culling) { + cullTask.culling.resetCache(); + } + } + } + } + }, backgroundWorker); + } + } + + public static void onEntityRemoval(Entity entity) { + if (!RaytraceTracker.enabled) return; + int id = entity.getId(); + CompletableFuture.runAsync(() -> { + for (CullTask cullTask : tasks) { + cullTask.scheduleForRemoval(id); + } + }, backgroundWorker); + } + + public void scheduleForRemoval(int entityId) { + removalQueue.offer(entityId); + } + + private boolean isSkippableArmorstand(Entity entity) { + if (!RaytraceTracker.skipMarkerArmorStand) return false; + return entity instanceof ArmorStand && entity.isInvisible(); + } + + public boolean isEntityCulled(Entity entity) { + return culledEntities.contains(entity.getId()); + } + + public void setCulled(Entity entity, boolean value) { + if (value) { + culledEntities.add(entity.getId()); + } else { + culledEntities.remove(entity.getId()); + } + } +} diff --git a/leaf-server/src/main/java/dev/tr7zw/entityculling/DefaultChunkDataProvider.java b/leaf-server/src/main/java/dev/tr7zw/entityculling/DefaultChunkDataProvider.java new file mode 100644 index 0000000000..a4960b1ee2 --- /dev/null +++ b/leaf-server/src/main/java/dev/tr7zw/entityculling/DefaultChunkDataProvider.java @@ -0,0 +1,45 @@ +package dev.tr7zw.entityculling; + +import com.logisticscraft.occlusionculling.DataProvider; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; + +public class DefaultChunkDataProvider implements DataProvider { + private final Level level; + + public DefaultChunkDataProvider(Level level) { + this.level = level; + } + + @Override + public boolean prepareChunk(int chunkX, int chunkZ) { + return this.level.getChunkIfLoaded(chunkX, chunkZ) != null; + } + + @Override + public boolean isOpaqueFullCube(int x, int y, int z) { + BlockPos pos = new BlockPos(x, y, z); + + final ChunkAccess access = this.level.getChunkIfLoaded(pos); + if (access == null) { + return false; + } + + if (this.level.isOutsideBuildHeight(pos)) { + BlockState bs = Blocks.VOID_AIR.defaultBlockState(); + return !bs.canOcclude() && bs.isSolidRender(); + } else { + BlockState bs = access.getBlockState(pos); + return !bs.canOcclude() && bs.isSolidRender(); + } + } + + @Override + public void cleanup() { + DataProvider.super.cleanup(); + } + +} diff --git a/leaf-server/src/main/java/dev/tr7zw/entityculling/versionless/access/Cullable.java b/leaf-server/src/main/java/dev/tr7zw/entityculling/versionless/access/Cullable.java new file mode 100644 index 0000000000..3b0d09a905 --- /dev/null +++ b/leaf-server/src/main/java/dev/tr7zw/entityculling/versionless/access/Cullable.java @@ -0,0 +1,15 @@ +package dev.tr7zw.entityculling.versionless.access; + +import net.minecraft.world.entity.player.Player; + +public interface Cullable { + + void setTimeout(); + + boolean isForcedVisible(); + + void setCulled(boolean value, Player player); + + boolean isCulled(Player player); + +} diff --git a/leaf-server/src/main/java/org/dreeam/leaf/config/modules/misc/RaytraceTracker.java b/leaf-server/src/main/java/org/dreeam/leaf/config/modules/misc/RaytraceTracker.java new file mode 100644 index 0000000000..c30da035ff --- /dev/null +++ b/leaf-server/src/main/java/org/dreeam/leaf/config/modules/misc/RaytraceTracker.java @@ -0,0 +1,116 @@ +package org.dreeam.leaf.config.modules.misc; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.EntityType; +import org.dreeam.leaf.config.ConfigModules; +import org.dreeam.leaf.config.EnumConfigCategory; +import org.dreeam.leaf.config.LeafConfig; +import org.dreeam.leaf.config.annotations.Experimental; + +import java.util.*; + +public class RaytraceTracker extends ConfigModules { + + public String getBasePath() { + return EnumConfigCategory.MISC.getBaseKeyName() + ".raytrace-entity-tracker"; + } + + @Experimental + public static boolean enabled = false; + + public static int maxTraceDistance = 64; + public static boolean skipMarkerArmorStand = false; + public static int boundingBoxLimit = 20; + public static int traceInterval = 50; + public static double forceVisibleRadius = 2.0D; + public static double boundingBoxExpansion = 0.5D; + public static List skippedEntities = List.of(); + public static boolean invertSkipEntities = false; + + @Override + public void onLoaded() { + config.addCommentRegionBased(getBasePath(), """ + *** EXPERIMENTAL FEATURE *** + Raytrace Entity Tracker uses async ray-tracing to untrack entities players cannot see, + which can reduce bandwidth usage significantly, + especially in some massive entities in small area situations. + Also it provides a way to guard against Entity ESP hacks.""", + """ + *** 实验性功能 *** + 使用异步射线追踪来动态取消跟踪玩家看不见的实体, + 可以显著降低带宽使用, + 在实体数量多且密集的情况下效果明显. + 也提供了一种对抗 Entity ESP 作弊的方案."""); + + enabled = config.getBoolean(getBasePath() + ".enabled", enabled); + maxTraceDistance = config.getInt(getBasePath() + ".max-trace-distance", maxTraceDistance, config.pickStringRegionBased( + """ + The maximum distance to trace entities in blocks.""", + """ + 最大追踪实体距离, 单位: 方块.""")); + skipMarkerArmorStand = config.getBoolean(getBasePath() + ".skip-marker-armor-stand", skipMarkerArmorStand, config.pickStringRegionBased( + """ + Whether to skip tracing entities with marker armor stand.""", + """ + 是否跳过追踪带标记盔甲架的实体.""")); + boundingBoxLimit = config.getInt(getBasePath() + ".bounding-box-limit", boundingBoxLimit, config.pickStringRegionBased( + """ + The maximum size of bounding box to trace. + Entities with bounding box larger than this value will be skipped.""", + """ + 碰撞箱大小限制, + 实体碰撞箱大于该值将被跳过.""")); + traceInterval = config.getInt(getBasePath() + ".trace-interval", traceInterval, config.pickStringRegionBased( + """ + The interval between each trace in milliseconds. + Lower value means more frequent trace.""", + """ + 追踪间隔(单位: 毫秒), 越小越频繁.""")); + forceVisibleRadius = config.getDouble(getBasePath() + ".force-visible-radius", forceVisibleRadius, config.pickStringRegionBased( + """ + The radius to force visible entities. + Entities within this radius will be forced visible. + Set to values less than or equal to zero to disable.""", + """ + 强制可见半径, + 实体在范围内将被强制可见. + 设置为小于等于 0 的值来禁用强制可见.""")); + boundingBoxExpansion = config.getDouble(getBasePath() + ".bounding-box-expansion", boundingBoxExpansion, config.pickStringRegionBased( + """ + The expansion of bounding box. + This modifier will be added to the actual bounding box when tracing.""", + """ + 碰撞箱扩大量. + 此值将会在射线追踪时添加到实际碰撞箱上.""")); + skippedEntities = config.getList(getBasePath() + ".skipped-entities", skippedEntities, config.pickStringRegionBased( + """ + The entities to skip tracing.""", + """ + 跳过追踪的实体.""")); + invertSkipEntities = config.getBoolean(getBasePath() + ".invert-skip-entities", invertSkipEntities, config.pickStringRegionBased( + """ + Whether to invert the skip entities list.""", + """ + 是否反转跳过实体列表.""")); + } + + @Override + public void onPostLoaded() { + for (EntityType entityType : BuiltInRegistries.ENTITY_TYPE) { + entityType.skipRaytraceCheck = invertSkipEntities; + } + + final String DEFAULT_PREFIX = ResourceLocation.DEFAULT_NAMESPACE + ResourceLocation.NAMESPACE_SEPARATOR; + + for (String name : skippedEntities) { + String lowerName = name.toLowerCase(Locale.ROOT); + String typeId = lowerName.startsWith(DEFAULT_PREFIX) ? lowerName : DEFAULT_PREFIX + lowerName; + + EntityType.byString(typeId).ifPresentOrElse(entityType -> + entityType.skipRaytraceCheck = !invertSkipEntities, + () -> LeafConfig.LOGGER.warn("Skip unknown entity {}, in {}", name, getBasePath() + ".skipped-entities") + ); + } + } +}