Compare commits

...
6 Commits
7 changed files with 180 additions and 130 deletions

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ plugins {
}
group = 'games.cubi'
version = '1.4.1'
version = '1.4.2'
repositories {
mavenCentral()
@@ -1,6 +1,7 @@
package games.cubi.raycastedEntityOcclusion;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
@@ -12,76 +13,97 @@ import java.util.concurrent.ConcurrentHashMap;
public class ChunkSnapshotManager {
public static class Data {
public final Material[][][] snapshot;
public final ChunkSnapshot snapshot;
public final Map<Location, Material> delta = new ConcurrentHashMap<>();
public long lastRefresh;
public Data(Material[][][] snap, long time) {
this.snapshot = snap;
public Data(ChunkSnapshot snapshot, long time) {
this.snapshot = snapshot;
this.lastRefresh = time;
}
}
private final Map<String, Data> map = new ConcurrentHashMap<>();
private final Map<String, Data> dataMap = new ConcurrentHashMap<>();
public ChunkSnapshotManager(RaycastedEntityOcclusion plugin, int refreshIntervalSecs) {
ConfigManager cfg = plugin.getConfigManager();
//get loaded chunks and add them to dataMap
for (World w : plugin.getServer().getWorlds()) {
for (Chunk c : w.getLoadedChunks()) {
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
}
}
public ChunkSnapshotManager(Plugin plugin, int refreshIntervalSecs) {
new BukkitRunnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
for (Map.Entry<String, Data> e : map.entrySet()) {
if (now - e.getValue().lastRefresh >= refreshIntervalSecs*1000L) {
int chunksRefreshed = 0;
for (Map.Entry<String, Data> e : dataMap.entrySet()) {
if (now - e.getValue().lastRefresh >= refreshIntervalSecs * 1000L) {
if (cfg.debugMode) {
chunksRefreshed++;
}
String key = e.getKey();
String[] parts = key.split(":");
World w = plugin.getServer().getWorld(parts[0]);
Chunk c = w.getChunkAt(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
if (w == null) {
plugin.getLogger().warning("ChunkSnapshotManager: World " + parts[0] + " not found. Please report this on our discord (discord.cubi.games)'");
continue;
}
Chunk c = w.getChunkAt(
Integer.parseInt(parts[1]),
Integer.parseInt(parts[2])
);
e.setValue(takeSnapshot(c, now));
}
}
if (cfg.debugMode) {
plugin.getLogger().info("ChunkSnapshotManager: Refreshed " + chunksRefreshed + " chunks.");
}
}
}.runTaskTimer(plugin, refreshIntervalSecs*20L, refreshIntervalSecs*20L);
}.runTaskTimerAsynchronously(plugin, refreshIntervalSecs * 5L, refreshIntervalSecs * 5L /* This runs 4 times per refreshInterval, spreading out the refreshes */);
}
public void onChunkLoad(Chunk c) {
map.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
}
public void onChunkUnload(Chunk c) {
map.remove(key(c));
dataMap.remove(key(c));
}
// Used by SnapshotListener to update the delta map when a block is placed or broken
public void onBlockChange(Location loc, Material m) {
Data d = map.get(key(loc.getChunk()));
if (d != null) d.delta.put(loc, m);
Data d = dataMap.get(key(loc.getChunk()));
if (d != null) {
d.delta.put(loc, m);
}
}
private Data takeSnapshot(Chunk c, long now) {
World w = c.getWorld();
int height = w.getMaxHeight();
Material[][][] arr = new Material[16][height][16];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < height; y++) {
arr[x][y][z] = c.getBlock(x, y, z).getType();
}
}
}
return new Data(arr, now);
return new Data(c.getChunkSnapshot(), now);
}
private String key(Chunk c) {
return c.getWorld().getName()+":"+c.getX()+":"+c.getZ();
return c.getWorld().getName() + ":" + c.getX() + ":" + c.getZ();
}
public Material getMaterialAt(Location loc) {
Data d = map.get(key(loc.getChunk()));
if (d == null) return loc.getBlock().getType();
Data d = dataMap.get(key(loc.getChunk()));
if (d == null) {
Chunk c = loc.getChunk();
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
System.err.println("ChunkSnapshotManager: No snapshot for " + loc.getChunk()+ " Please report this on our discord (discord.cubi.games)'");
return loc.getBlock().getType();
}
Material dm = d.delta.get(loc);
if (dm != null) return dm;
if (dm != null) {
return dm;
}
int x = loc.getBlockX() & 0xF;
int y = loc.getBlockY();
int z = loc.getBlockZ() & 0xF;
return d.snapshot[x][y][z];
return d.snapshot.getBlockType(x, y, z);
}
}
}
@@ -0,0 +1,105 @@
package games.cubi.raycastedEntityOcclusion;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Engine {
private static class RayJob {
final UUID playerId, entityId;
final Location start, predictedStart, end;
RayJob(UUID p, UUID e, Location s, Location pred, Location t) {
playerId = p;
entityId = e;
start = s;
predictedStart = pred;
end = t;
}
}
private static class RayResult {
final UUID playerId, entityId;
final boolean visible;
RayResult(UUID p, UUID e, boolean v) {
playerId = p;
entityId = e;
visible = v;
}
}
public static void runEngine(ConfigManager cfg, ChunkSnapshotManager snapMgr, MovementTracker tracker, RaycastedEntityOcclusion plugin) {
// ----- PHASE 1: SYNC GATHER -----
List<RayJob> jobs = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
Location eye = p.getEyeLocation().clone();
Location predEye = null;
if (cfg.engineMode == 2) {
// getPredictedLocation returns null if insufficient data or too slow
predEye = tracker.getPredictedLocation(p);
}
for (Entity e : p.getNearbyEntities(cfg.searchRadius, cfg.searchRadius, cfg.searchRadius)) {
if (e == p) continue;
// Cull-players logic
if (e instanceof Player pl && (!cfg.cullPlayers || (cfg.onlyCullSneakingPlayers && !pl.isSneaking()))) {
p.showEntity(plugin, e);
continue;
}
Location target = e.getLocation().add(0, e.getHeight() / 2, 0).clone();
double dist = eye.distance(target);
if (dist <= cfg.alwaysShowRadius) {
p.showEntity(plugin, e);
} else if (dist > cfg.raycastRadius) {
p.hideEntity(plugin, e);
} else if (p.canSee(e) && plugin.tick % cfg.recheckInterval != 0) {
// player can see entity, no need to raycast
}
else {
// schedule for async raycast (with or without predEye)
jobs.add(new RayJob(p.getUniqueId(), e.getUniqueId(), eye, predEye, target));
}
}
}
// ----- PHASE 2: ASYNC RAYCASTS -----
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
List<RayResult> results = new ArrayList<>(jobs.size());
for (RayJob job : jobs) {
// first cast from real eye
boolean vis = RaycastUtil.raycast(job.start, job.end, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
// if that fails and we have a predEye, cast again from predicted
if (!vis && job.predictedStart != null) {
if (cfg.debugMode) {
job.predictedStart.getWorld().spawnParticle(Particle.DUST, job.predictedStart, 1, new Particle.DustOptions(org.bukkit.Color.BLUE,1f));
}
vis = RaycastUtil.raycast(job.predictedStart, job.end, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
}
results.add(new RayResult(job.playerId, job.entityId, vis));
}
// ----- PHASE 3: SYNC APPLY -----
Bukkit.getScheduler().runTask(plugin, () -> {
for (RayResult r : results) {
Player p = Bukkit.getPlayer(r.playerId);
Entity ent = Bukkit.getEntity(r.entityId);
if (p != null && ent != null) {
if (r.visible) p.showEntity(plugin, ent);
else p.hideEntity(plugin, ent);
}
}
});
});
}
}
@@ -3,11 +3,19 @@ package games.cubi.raycastedEntityOcclusion;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class RaycastUtil {
public static boolean raycast(Location start, Location end, int maxOccluding, boolean debug, ChunkSnapshotManager snap) {
Particle.DustOptions dustRed = null;
Particle.DustOptions dustGreen = null;
if (debug) {
dustRed = new Particle.DustOptions(org.bukkit.Color.RED, 1f);
dustGreen = new Particle.DustOptions(org.bukkit.Color.GREEN, 1f);
}
double total = start.distance(end);
double traveled = 0;
Location curr = start.clone();
@@ -20,12 +28,12 @@ public class RaycastUtil {
if (mat.isOccluding()) {
maxOccluding--;
if (debug) {
start.getWorld().spawnParticle(Particle.DUST, curr, 1, new Particle.DustOptions(org.bukkit.Color.RED,1f));
start.getWorld().spawnParticle(Particle.DUST, curr, 1, dustRed);
}
if (maxOccluding < 1) return false;
}
else if (debug) {
start.getWorld().spawnParticle(Particle.DUST, curr, 1, new Particle.DustOptions(org.bukkit.Color.GREEN,1f));
start.getWorld().spawnParticle(Particle.DUST, curr, 1, dustGreen);
}
}
return true;
@@ -9,7 +9,6 @@ import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
@@ -25,6 +24,8 @@ public class RaycastedEntityOcclusion extends JavaPlugin implements CommandExecu
private MovementTracker tracker;
private CommandsManager commands;
public int tick = 0;
@Override
public void onEnable() {
cfg = new ConfigManager(this);
@@ -55,99 +56,13 @@ public class RaycastedEntityOcclusion extends JavaPlugin implements CommandExecu
new BukkitRunnable() {
@Override
public void run() {
runEngine();
tick++;
Engine.runEngine(cfg, snapMgr, tracker, RaycastedEntityOcclusion.this);
}
}.runTaskTimer(this, 0L, 1L);
}
// --- helper to hold one ray job ---
private static class RayJob {
final UUID playerId, entityId;
final Location start, predictedStart, end;
RayJob(UUID p, UUID e, Location s, Location pred, Location t) {
playerId = p;
entityId = e;
start = s;
predictedStart = pred;
end = t;
}
}
// --- helper to hold one ray result ---
private static class RayResult {
final UUID playerId, entityId;
final boolean visible;
RayResult(UUID p, UUID e, boolean v) {
playerId = p;
entityId = e;
visible = v;
}
}
private void runEngine() {
// ----- PHASE 1: SYNC GATHER -----
List<RayJob> jobs = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
Location eye = p.getEyeLocation().clone();
Location predEye = null;
if (cfg.engineMode == 2) {
// getPredictedLocation returns null if insufficient data or too slow
predEye = tracker.getPredictedLocation(p);
}
for (Entity e : p.getNearbyEntities(cfg.searchRadius, cfg.searchRadius, cfg.searchRadius)) {
if (e == p) continue;
// Cull-players logic
if (e instanceof Player pl && (!cfg.cullPlayers || (cfg.onlyCullSneakingPlayers && !pl.isSneaking()))) {
p.showEntity(this, e);
continue;
}
Location target = e.getLocation().add(0, e.getHeight() / 2, 0).clone();
double dist = eye.distance(target);
if (dist <= cfg.alwaysShowRadius) {
p.showEntity(this, e);
} else if (dist > cfg.raycastRadius) {
p.hideEntity(this, e);
} else {
// schedule for async raycast (with or without predEye)
jobs.add(new RayJob(p.getUniqueId(), e.getUniqueId(), eye, predEye, target));
}
}
}
// ----- PHASE 2: ASYNC RAYCASTS -----
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
List<RayResult> results = new ArrayList<>(jobs.size());
for (RayJob job : jobs) {
// first cast from real eye
boolean vis = RaycastUtil.raycast(job.start, job.end, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
// if that fails and we have a predEye, cast again from predicted
if (!vis && job.predictedStart != null) {
if (cfg.debugMode) {
job.predictedStart.getWorld().spawnParticle(Particle.DUST, job.predictedStart, 1, new Particle.DustOptions(org.bukkit.Color.BLUE,1f));
}
vis = RaycastUtil.raycast(job.predictedStart, job.end, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
}
results.add(new RayResult(job.playerId, job.entityId, vis));
}
// ----- PHASE 3: SYNC APPLY -----
Bukkit.getScheduler().runTask(this, () -> {
for (RayResult r : results) {
Player p = Bukkit.getPlayer(r.playerId);
Entity ent = Bukkit.getEntity(r.entityId);
if (p != null && ent != null) {
if (r.visible) p.showEntity(this, ent);
else p.hideEntity(this, ent);
}
}
});
});
public ConfigManager getConfigManager() {
return cfg;
}
}
@@ -18,7 +18,7 @@ public class SnapshotListener implements Listener {
@EventHandler
public void onChunkLoad(ChunkLoadEvent e) {
if (!e.isNewChunk()) manager.onChunkLoad(e.getChunk());
manager.onChunkLoad(e.getChunk());
}
@EventHandler
+2 -2
View File
@@ -1,5 +1,5 @@
snapshot-refresh-interval: 60 # seconds between chunk snapshot refresh
engine-mode: 1 # 1 = straight-line; 2 = predictive
snapshot-refresh-interval: 60 # seconds between chunk snapshot refresh, won't change without restart
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
max-occluding-count: 3 # blocks before blocking
debug-mode: false # enable debug particles
always-show-radius: 8 # radius to always show entities