From aaab62083963d8c2f8065ceeba18732dd0def525 Mon Sep 17 00:00:00 2001 From: TheMode Date: Sat, 10 Apr 2021 21:21:37 +0200 Subject: [PATCH] Reduce entity movement overhead (chunk lookup) --- .../java/net/minestom/server/entity/Entity.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index 13ec16f05..776769a18 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -1309,13 +1309,20 @@ public class Entity implements Viewable, EventHandler, DataContainer, Permission final Instance instance = getInstance(); if (instance != null) { - final Chunk lastChunk = instance.getChunkAt(lastX, lastZ); - final Chunk newChunk = instance.getChunkAt(x, z); + final int lastChunkX = ChunkUtils.getChunkCoordinate(lastX); + final int lastChunkZ = ChunkUtils.getChunkCoordinate(lastZ); - Check.notNull(lastChunk, "The entity {0} was in an unloaded chunk at {1};{2}", getEntityId(), lastX, lastZ); - Check.notNull(newChunk, "The entity {0} tried to move in an unloaded chunk at {1};{2}", getEntityId(), x, z); + final int newChunkX = ChunkUtils.getChunkCoordinate(x); + final int newChunkZ = ChunkUtils.getChunkCoordinate(z); + + if (lastChunkX != newChunkX || lastChunkZ != newChunkZ) { + // Entity moved in a new chunk + final Chunk lastChunk = instance.getChunk(lastChunkX, lastChunkZ); + final Chunk newChunk = instance.getChunk(newChunkX, newChunkZ); + + Check.notNull(lastChunk, "The entity {0} was in an unloaded chunk at {1};{2}", getEntityId(), lastX, lastZ); + Check.notNull(newChunk, "The entity {0} tried to move in an unloaded chunk at {1};{2}", getEntityId(), x, z); - if (lastChunk != newChunk) { instance.UNSAFE_switchEntityChunk(this, lastChunk, newChunk); if (this instanceof Player) { // Refresh player view