Volver al índice
src/main/java/ar/com/companeros/world/MovementHistory.java
package ar.com.companeros.world;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import net.minecraft.core.BlockPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
/** Rastro local y temporal: evita redescubrir el mismo circuito como si fuera una exploración nueva. */
final class MovementHistory {
private static final long RETENTION_TICKS = 6000;
private static final int MAX_CELLS = 2048;
private static final Map<MinecraftServer, Map<UUID, Trail>> TRAILS = new WeakHashMap<>();
private MovementHistory() { }
// Las posiciones provienen exclusivamente del cuerpo real y de destinos que decidió explorar.
static boolean observe(ServerPlayer player, long tick) {
Trail trail = trail(player, tick); BlockPos pos = player.blockPosition().immutable();
boolean fresh = !trail.cells.containsKey(pos);
trail.cells.put(pos, tick); trim(trail.cells, tick);
return fresh;
}
static boolean claimDestination(ServerPlayer player, BlockPos pos, long tick) {
Trail trail = trail(player, tick);
if (trail.cells.containsKey(pos) || trail.destinations.containsKey(pos)) return false;
trail.destinations.put(pos.immutable(), tick); trim(trail.destinations, tick);
return true;
}
private static Trail trail(ServerPlayer player, long tick) {
Map<UUID, Trail> byPlayer = TRAILS.computeIfAbsent(player.server, ignored -> new LinkedHashMap<>());
byPlayer.entrySet().removeIf(entry -> entry.getValue().body.get() == null || tick - entry.getValue().updated > RETENTION_TICKS);
Trail trail = byPlayer.get(player.getUUID());
if (trail == null || trail.body.get() != player || !trail.dimension.equals(player.level().dimension().location().toString())) {
trail = new Trail(player); byPlayer.put(player.getUUID(), trail);
}
trail.updated = tick; trim(trail.cells, tick); trim(trail.destinations, tick);
return trail;
}
private static void trim(LinkedHashMap<BlockPos, Long> map, long tick) {
// Inserciones/actualizaciones están ordenadas por uso: sólo inspeccionar el extremo antiguo.
var iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
if (map.size() <= MAX_CELLS && tick - entry.getValue() < RETENTION_TICKS) break;
iterator.remove();
}
}
private static final class Trail {
final WeakReference<ServerPlayer> body;
final String dimension;
final LinkedHashMap<BlockPos, Long> cells = new LinkedHashMap<>(32, .75f, true);
final LinkedHashMap<BlockPos, Long> destinations = new LinkedHashMap<>(32, .75f, true);
long updated;
Trail(ServerPlayer player) { body = new WeakReference<>(player); dimension = player.level().dimension().location().toString(); }
}
}