Major occlusion search optimizations #34

Merged
embeddedt merged 11 commits from occlusion-opts into stonecutter 2026-08-18 19:59:03 -04:00
22 changed files with 1712 additions and 405 deletions

No files matched your search

@@ -37,4 +37,18 @@ public class MathUtil {
public static boolean roughlyEqual(float a, float b) { public static boolean roughlyEqual(float a, float b) {
return Math.abs(b - a) < 0.00001f; return Math.abs(b - a) < 0.00001f;
} }
/**
* Returns the value nearest to zero in [min, max].
* <p>
* In other words, if zero is inside [min, max], returns 0. Otherwise, returns whichever endpoint is closer to zero.
*/
@SuppressWarnings("ManualMinMaxCalculation") // we know what we are doing.
public static int nearestToZero(int min, int max) {
// this compiles to slightly better code than Math.min(Math.max(0, min), max)
int clamped = 0;
if (min > 0) { clamped = min; }
if (max < 0) { clamped = max; }
return clamped;
}
} }
@@ -67,4 +67,11 @@ public enum ChunkUpdateType {
public boolean isSort() { public boolean isSort() {
return this == SORT || this == IMPORTANT_SORT; return this == SORT || this == IMPORTANT_SORT;
} }
static {
if (VALUES.length > 7) {
// See PackedSectionMetadata, OcclusionCuller, etc.
throw new AssertionError("The occlusion system currently assumes there are at most 7 update types");
}
}
} }
@@ -0,0 +1,169 @@
package org.embeddedt.embeddium.impl.render.chunk;
import org.jetbrains.annotations.Nullable;
/**
* Packs the per-section state consumed by visibility traversal and render-list
* collection into one {@code long}.
*
* <p>{@link RenderSection} owns the authoritative word. The
* {@link org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice}
* mirrors it in a flat array so the hot traversal can read all of a section's
* state with one indexed load instead of following several object references.
* The visitor receives the unpacked fields without needing the section object
* during the search.
*
* <p>Bit layout:
* <pre>
* 63 53 52 51 49 48 46 45 0
* +--------------------+--+-----------+----------+-------------------+
* | spare |IF| pending | visuals | visibility graph |
* +--------------------+--+-----------+----------+-------------------+
* </pre>
* <ul>
* <li>Bits {@code 0..45}: {@link VisibilityEncoding} entries. Entry
* {@code (from * 8) + to} describes visibility from one of six faces to
* another. Each eight-bit row uses its six low bits; the two padding
* positions are not part of the visibility field (the final row's
* padding is reused by the visual flags).</li>
* <li>Bits {@code 46..48}: {@link RenderVisualsService} visual flags.</li>
* <li>Bits {@code 49..51}: pending update type; zero means none, otherwise
* {@code ChunkUpdateType.ordinal() + 1}.</li>
* <li>Bit {@code 52}: a build is in flight.</li>
* <li>Bits {@code 53..63}: reserved.</li>
* </ul>
*
* <p>The visibility graph uses only bits {@code 0..45}, but
* {@link VisibilityEncoding#getConnections(long)} folds high bits down into
* its direction result. Therefore every value passed to that method must first
* be masked with {@link #VISIBILITY_MASK}.
*
* <p>{@link #GRAPH_INPUT_MASK} identifies the fields that affect the graph
* search or the render-list contents. Pending-update and build-in-flight bits
* are consumed separately by the visitor and do not change graph traversal by
* themselves.
*/
public final class PackedSectionMetadata {
private PackedSectionMetadata() {
}
// Bits 0..45: visibility graph encoding. The 46-bit width is 6 * 8 - 2,
// because six directions occupy six entries in each eight-bit row and the
// final row is only needed through its sixth entry.
private static final int VISIBILITY_BITS = 46;
public static final long VISIBILITY_MASK = (1L << VISIBILITY_BITS) - 1;
// Bits 46..48: RenderVisualsService.HAS_* flags.
private static final int VISUALS_FLAGS_SHIFT = 46;
private static final long VISUALS_FLAGS_MASK = 0b111L;
/**
* Fields whose changes can alter the result of a visibility search or its
* render-list output: visibility graph data and visual-presence flags.
*/
public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT);
// Bits 49..51: 0 means no pending update; otherwise ordinal + 1.
private static final int PENDING_UPDATE_SHIFT = 49;
private static final long PENDING_UPDATE_MASK = 0b111L;
// Bit 52: a build cancellation token is currently attached.
private static final int BUILD_IN_FLIGHT_BIT = 52;
private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT;
/** Returns only the visibility graph field. */
public static long getVisibilityData(long packed) {
return packed & VISIBILITY_MASK;
}
/**
* Replaces the visibility graph field and preserves every other field.
* Bits outside {@link #VISIBILITY_MASK} in {@code visibilityData} are
* discarded.
*/
public static long withVisibilityData(long packed, long visibilityData) {
return (packed & ~VISIBILITY_MASK) | (visibilityData & VISIBILITY_MASK);
}
/** Returns the three visual-presence flags. */
public static int getVisualsFlags(long packed) {
return (int) ((packed >>> VISUALS_FLAGS_SHIFT) & VISUALS_FLAGS_MASK);
}
/**
* Replaces the visual-presence flags and preserves every other field.
* Only the three low bits of {@code flags} are stored.
*/
public static long withVisualsFlags(long packed, int flags) {
return (packed & ~(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT))
| (((long) flags & VISUALS_FLAGS_MASK) << VISUALS_FLAGS_SHIFT);
}
/**
* Decodes the pending update field.
*
* @return the pending update type, or {@code null} when the field is zero
*/
public static @Nullable ChunkUpdateType getPendingUpdate(long packed) {
int encoded = (int) ((packed >>> PENDING_UPDATE_SHIFT) & PENDING_UPDATE_MASK);
return encoded == 0 ? null : ChunkUpdateType.VALUES[encoded - 1];
}
/**
* Replaces the pending update field and preserves every other field.
* {@code null} clears the field; non-null values use ordinal plus one so
* zero remains the no-update sentinel.
*/
public static long withPendingUpdate(long packed, @Nullable ChunkUpdateType type) {
long encoded = type == null ? 0L : (type.ordinal() + 1L);
return (packed & ~(PENDING_UPDATE_MASK << PENDING_UPDATE_SHIFT))
| (encoded << PENDING_UPDATE_SHIFT);
}
/** Returns whether a section build is currently in flight. */
public static boolean isBuildInFlight(long packed) {
return (packed & BUILD_IN_FLIGHT_FLAG) != 0;
}
/*
* Compact collector metadata: includes only the info the VisibleChunkCollector cares about.
*
* 6 5 3 2 0
* +--+-------+--------+
* |IF|pending|visuals |
* +--+-------+--------+
*/
private static final int COMPACT_META_SHIFT = VISUALS_FLAGS_SHIFT;
private static final long COMPACT_META_FIELDS =
(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT)
| (PENDING_UPDATE_MASK << PENDING_UPDATE_SHIFT)
| BUILD_IN_FLIGHT_FLAG;
private static final int COMPACT_META_MASK = (int) (COMPACT_META_FIELDS >>> COMPACT_META_SHIFT);
private static final int COMPACT_PENDING_SHIFT = PENDING_UPDATE_SHIFT - COMPACT_META_SHIFT;
private static final int COMPACT_BUILD_IN_FLIGHT_BIT = BUILD_IN_FLIGHT_BIT - COMPACT_META_SHIFT;
public static int toCompactMeta(long packed) {
return (int) (packed >>> COMPACT_META_SHIFT) & COMPACT_META_MASK;
}
public static int getCompactVisualsFlags(int meta) {
return meta & (int) VISUALS_FLAGS_MASK;
}
/** @return the pending update type, or {@code null} when the field is zero */
public static @Nullable ChunkUpdateType getCompactPendingUpdate(int meta) {
int encoded = (meta >>> COMPACT_PENDING_SHIFT) & (int) PENDING_UPDATE_MASK;
return encoded == 0 ? null : ChunkUpdateType.VALUES[encoded - 1];
}
public static boolean isCompactBuildInFlight(int meta) {
return (meta & (1 << COMPACT_BUILD_IN_FLIGHT_BIT)) != 0;
}
/**
* Replaces the build-in-flight flag and preserves every other field.
*/
public static long withBuildInFlight(long packed, boolean inFlight) {
return inFlight ? (packed | BUILD_IN_FLIGHT_FLAG) : (packed & ~BUILD_IN_FLIGHT_FLAG);
}
}
@@ -35,9 +35,20 @@ public class RenderSection extends AbstractSection {
// Rendering State // Rendering State
private BuiltRenderSectionData contextData; private BuiltRenderSectionData contextData;
private boolean hasAnythingToRender;
@Getter // Packed encoding of the visibility encoding, visuals flags, pending update type, and build-in-flight bit;
private int visualsServiceFlags; // see PackedSectionMetadata for the bit layout. The graph search reads a mirror of this in SectionLattice, so
// mutate it only through writeMetadata(), which notifies the mirror.
private long packedMetadata;
// Notified on every packedMetadata change to keep the lattice mirror in sync. Null until the section is
// attached to its manager (the initial constructor write predates attachment).
@Nullable
private MetadataSink metadataSink;
public interface MetadataSink {
void onMetadataChanged(RenderSection section);
}
/** /**
* A mapping from translucent render passes to the sort state for that particular pass (which contains data needed * A mapping from translucent render passes to the sort state for that particular pass (which contains data needed
@@ -64,9 +75,6 @@ public class RenderSection extends AbstractSection {
@Nullable @Nullable
private CancellationToken buildCancellationToken = null; private CancellationToken buildCancellationToken = null;
@Nullable
private ChunkUpdateType pendingUpdateType;
private int lastBuiltFrame = -1; private int lastBuiltFrame = -1;
private int lastSubmittedFrame = -1; private int lastSubmittedFrame = -1;
@@ -97,7 +105,7 @@ public class RenderSection extends AbstractSection {
public void delete() { public void delete() {
if (this.buildCancellationToken != null) { if (this.buildCancellationToken != null) {
this.buildCancellationToken.setCancelled(); this.buildCancellationToken.setCancelled();
this.buildCancellationToken = null; this.setBuildCancellationToken(null);
} }
this.setInfo(null); this.setInfo(null);
@@ -133,12 +141,39 @@ public class RenderSection extends AbstractSection {
} }
public void updateCachedContextDataFlags() { public void updateCachedContextDataFlags() {
this.visualsServiceFlags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0;
this.hasAnythingToRender = this.visualsServiceFlags != 0; long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL;
this.writeMetadata(PackedSectionMetadata.withVisibilityData(
PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData));
}
// The sole writer of packedMetadata: stores the new word and notifies the mirror.
private void writeMetadata(long packed) {
this.packedMetadata = packed;
if (this.metadataSink != null) {
this.metadataSink.onMetadataChanged(this);
}
}
public long getPackedMetadata() {
return this.packedMetadata;
}
public void setMetadataSink(@Nullable MetadataSink sink) {
this.metadataSink = sink;
}
public int getVisualsServiceFlags() {
return PackedSectionMetadata.getVisualsFlags(this.packedMetadata);
}
public long getVisibilityData() {
return PackedSectionMetadata.getVisibilityData(this.packedMetadata);
} }
public boolean hasAnythingToRender() { public boolean hasAnythingToRender() {
return this.hasAnythingToRender; return this.getVisualsServiceFlags() != 0;
} }
public void setTranslucencySortStates(@NotNull Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> sortStates) { public void setTranslucencySortStates(@NotNull Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> sortStates) {
@@ -165,14 +200,15 @@ public class RenderSection extends AbstractSection {
public void setBuildCancellationToken(@Nullable CancellationToken token) { public void setBuildCancellationToken(@Nullable CancellationToken token) {
this.buildCancellationToken = token; this.buildCancellationToken = token;
this.writeMetadata(PackedSectionMetadata.withBuildInFlight(this.packedMetadata, token != null));
} }
public @Nullable ChunkUpdateType getPendingUpdate() { public @Nullable ChunkUpdateType getPendingUpdate() {
return this.pendingUpdateType; return PackedSectionMetadata.getPendingUpdate(this.packedMetadata);
} }
public void setPendingUpdate(@Nullable ChunkUpdateType type) { public void setPendingUpdate(@Nullable ChunkUpdateType type) {
this.pendingUpdateType = type; this.writeMetadata(PackedSectionMetadata.withPendingUpdate(this.packedMetadata, type));
} }
/** /**
@@ -182,10 +218,10 @@ public class RenderSection extends AbstractSection {
* @return true if the section's chunk update type has changed * @return true if the section's chunk update type has changed
*/ */
public boolean requestUpdate(ChunkUpdateType type) { public boolean requestUpdate(ChunkUpdateType type) {
type = ChunkUpdateType.getPromotionUpdateType(this.pendingUpdateType, type); type = ChunkUpdateType.getPromotionUpdateType(this.getPendingUpdate(), type);
if (type != null) { if (type != null) {
this.pendingUpdateType = type; this.setPendingUpdate(type);
return true; return true;
} else { } else {
return false; return false;
@@ -88,6 +88,10 @@ public abstract class RenderSectionManager {
@Nullable @Nullable
protected final RenderListManager shadowRenderListManager; protected final RenderListManager shadowRenderListManager;
// Shared by every section (one allocation, not one per section); installed on each RenderSection so its
// packedMetadata changes fan out to the list manager mirror(s).
private final RenderSection.MetadataSink metadataSink = this::pushSectionMetadata;
protected final ReferenceSet<RenderSection> sectionsWithGlobalEntities = new ReferenceOpenHashSet<>(); protected final ReferenceSet<RenderSection> sectionsWithGlobalEntities = new ReferenceOpenHashSet<>();
private final Object2ObjectOpenHashMap<TerrainRenderPass, TimerQueryManager> renderPassDrawTimers = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenHashMap<TerrainRenderPass, TimerQueryManager> renderPassDrawTimers = new Object2ObjectOpenHashMap<>();
@@ -317,6 +321,7 @@ public abstract class RenderSectionManager {
RenderSection renderSection = new RenderSection(region, x, y, z); RenderSection renderSection = new RenderSection(region, x, y, z);
region.addSection(renderSection); region.addSection(renderSection);
renderSection.setMetadataSink(this.metadataSink);
this.sectionByPosition.put(key, renderSection); this.sectionByPosition.put(key, renderSection);
@@ -548,17 +553,21 @@ public abstract class RenderSectionManager {
render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates); render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates);
} }
// Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice(s) on every
// packedMetadata mutation (visibility/visuals via setInfo, pending update, build-in-flight).
private void pushSectionMetadata(RenderSection section) {
long packed = section.getPackedMetadata();
this.renderListManager.updateSectionMetadata(section.getChunkX(), section.getChunkY(), section.getChunkZ(), packed);
if (this.shadowRenderListManager != null) {
this.shadowRenderListManager.updateSectionMetadata(section.getChunkX(), section.getChunkY(), section.getChunkZ(), packed);
}
}
@MustBeInvokedByOverriders @MustBeInvokedByOverriders
protected boolean updateSectionInfo(RenderSection render, @Nullable BuiltRenderSectionData info) { protected boolean updateSectionInfo(RenderSection render, @Nullable BuiltRenderSectionData info) {
boolean changed = render.setInfo(info); boolean changed = render.setInfo(info);
if (changed) { if (changed) {
long visibilityData = info != null ? info.visibilityData : VisibilityEncoding.NULL;
this.renderListManager.updateVisibilityData(render.getChunkX(), render.getChunkY(), render.getChunkZ(), visibilityData);
if (this.shadowRenderListManager != null) {
this.shadowRenderListManager.updateVisibilityData(render.getChunkX(), render.getChunkY(), render.getChunkZ(), visibilityData);
}
if (!(info instanceof MinecraftBuiltRenderSectionData<?, ?> data)) { if (!(info instanceof MinecraftBuiltRenderSectionData<?, ?> data)) {
this.sectionsWithGlobalEntities.remove(render); this.sectionsWithGlobalEntities.remove(render);
} else if (!data.globalBlockEntities.isEmpty()) { } else if (!data.globalBlockEntities.isEmpty()) {
@@ -25,16 +25,13 @@ public class ChunkRenderList {
this.region = region; this.region = region;
} }
public void add(RenderSection render) { public void add(int index, int flags) {
if (this.size >= RenderRegion.REGION_SIZE) { if (this.size >= RenderRegion.REGION_SIZE) {
throw new ArrayIndexOutOfBoundsException("Render list is full"); throw new ArrayIndexOutOfBoundsException("Render list is full");
} }
this.size++; this.size++;
int index = render.getSectionIndex();
int flags = render.getVisualsServiceFlags();
this.sectionsWithGeometry[this.sectionsWithGeometryCount] = (byte) index; this.sectionsWithGeometry[this.sectionsWithGeometryCount] = (byte) index;
this.sectionsWithGeometryCount += (flags >>> RenderVisualsService.HAS_BLOCK_GEOMETRY) & 1; this.sectionsWithGeometryCount += (flags >>> RenderVisualsService.HAS_BLOCK_GEOMETRY) & 1;
@@ -1,18 +1,13 @@
package org.embeddedt.embeddium.impl.render.chunk.lists; package org.embeddedt.embeddium.impl.render.chunk.lists;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.GraphDirection; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionNode;
import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -31,12 +26,10 @@ public class RenderListManager {
@NotNull @NotNull
private ChunkRebuildLists rebuildLists; private ChunkRebuildLists rebuildLists;
private final OcclusionCuller occlusionCuller; private final SectionLattice lattice;
private final Long2ReferenceMap<OcclusionNode> occlusionNodes = new Long2ReferenceOpenHashMap<>();
// Non-null for the duration of an in-progress async graph search. Acts as a flag: // Non-null for the duration of an in-progress async graph search. Acts as a flag:
// structural mutations to occlusionNodes (attach/detach/rewire) are forbidden while set, // structural mutations to the lattice (attach/detach/rewire) are forbidden while set,
// and visibilityData updates are deferred to updateTasks rather than applied immediately. // and visibilityData updates are deferred to updateTasks rather than applied immediately.
private CompletableFuture<VisibleChunkCollector> currentOcclusionFuture; private CompletableFuture<VisibleChunkCollector> currentOcclusionFuture;
@@ -49,6 +42,14 @@ public class RenderListManager {
private int pendingLastUpdatedFrame; private int pendingLastUpdatedFrame;
@NotNull
private SectionLattice.VisibilitySnapshot visibilitySnapshot = SectionLattice.VisibilitySnapshot.EMPTY;
// Snapshot produced by the in-progress search. Written on the async thread; read on the render thread
// in finishPreviousGraphUpdate() after join() establishes happens-before, then published to visibilitySnapshot.
@Nullable
private SectionLattice.VisibilitySnapshot pendingVisibilitySnapshot;
// Tasks deferred by submitUpdateTask() while an async search is running. Drained on the // Tasks deferred by submitUpdateTask() while an async search is running. Drained on the
// render thread in finishPreviousGraphUpdate() after join() establishes happens-before. // render thread in finishPreviousGraphUpdate() after join() establishes happens-before.
private final ArrayDeque<Runnable> updateTasks = new ArrayDeque<>(); private final ArrayDeque<Runnable> updateTasks = new ArrayDeque<>();
@@ -93,7 +94,7 @@ public class RenderListManager {
} else { } else {
this.asyncGraphExecutor = null; this.asyncGraphExecutor = null;
} }
this.occlusionCuller = new OcclusionCuller(this.occlusionNodes, minSectionY, maxSectionY); this.lattice = new SectionLattice(minSectionY, maxSectionY);
this.renderLists = SortedRenderLists.empty(); this.renderLists = SortedRenderLists.empty();
this.rebuildLists = ChunkRebuildLists.EMPTY; this.rebuildLists = ChunkRebuildLists.EMPTY;
} }
@@ -103,10 +104,12 @@ public class RenderListManager {
throw new IllegalStateException("Occlusion work in progress while trying to submit next task"); throw new IllegalStateException("Occlusion work in progress while trying to submit next task");
} }
var visitor = new VisibleChunkCollector(frame, regionIdsLength, targetQueueSize); var visitor = new VisibleChunkCollector(this.lattice, frame, regionIdsLength, targetQueueSize);
this.lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
Supplier<VisibleChunkCollector> occlusionTask = () -> { Supplier<VisibleChunkCollector> occlusionTask = () -> {
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, useOcclusionCulling, frame); this.pendingVisibilitySnapshot = this.lattice.findVisible(visitor, viewport, searchDistance, regionIdsLength, useOcclusionCulling, frame);
// WARNING: when asyncGraphExecutor != null, this runs on the async thread. // WARNING: when asyncGraphExecutor != null, this runs on the async thread.
// SectionTicker.onRenderListUpdated() must be safe to call off the render thread. // SectionTicker.onRenderListUpdated() must be safe to call off the render thread.
@@ -136,6 +139,11 @@ public class RenderListManager {
this.renderLists = visitor.createRenderLists(); this.renderLists = visitor.createRenderLists();
this.rebuildLists = visitor.getRebuildLists(); this.rebuildLists = visitor.getRebuildLists();
// Publish the finished search's snapshot before advancing lastUpdatedFrame, so any concurrent
// reader that observes the new frame also observes the snapshot produced for it.
this.visibilitySnapshot = this.pendingVisibilitySnapshot;
this.pendingVisibilitySnapshot = null;
this.currentOcclusionFuture = null; this.currentOcclusionFuture = null;
this.lastUpdatedFrame = this.pendingLastUpdatedFrame; this.lastUpdatedFrame = this.pendingLastUpdatedFrame;
@@ -143,7 +151,7 @@ public class RenderListManager {
} }
// Run tasks deferred during the async search. The join() above establishes happens-before, // Run tasks deferred during the async search. The join() above establishes happens-before,
// so writes to OcclusionNode fields by the async thread are visible here. // so the async thread's writes to the lattice arrays are visible here.
Runnable task; Runnable task;
while ((task = updateTasks.poll()) != null) { while ((task = updateTasks.poll()) != null) {
@@ -170,36 +178,8 @@ public class RenderListManager {
} }
} }
private OcclusionNode getOcclusionNode(int x, int y, int z) { // Structural mutations to the lattice (adding/removing nodes, rewiring neighbor links)
return this.occlusionNodes.get(PositionUtil.packSection(x, y, z)); // are unsafe while the async search holds a reference to it via SectionLattice.
}
private void connectNeighborNodes(OcclusionNode render) {
for (int direction = 0; direction < GraphDirection.COUNT; direction++) {
OcclusionNode adj = this.getOcclusionNode(render.getChunkX() + GraphDirection.x(direction),
render.getChunkY() + GraphDirection.y(direction),
render.getChunkZ() + GraphDirection.z(direction));
if (adj != null) {
adj.setAdjacentNode(GraphDirection.opposite(direction), render);
render.setAdjacentNode(direction, adj);
}
}
}
private void disconnectNeighborNodes(OcclusionNode render) {
for (int direction = 0; direction < GraphDirection.COUNT; direction++) {
OcclusionNode adj = render.getAdjacent(direction);
if (adj != null) {
adj.setAdjacentNode(GraphDirection.opposite(direction), null);
render.setAdjacentNode(direction, null);
}
}
}
// Structural mutations to occlusionNodes (adding/removing nodes, rewiring neighbor links)
// are unsafe while the async thread holds a reference to the map via OcclusionCuller.
private void assertOcclusionNotRunning() { private void assertOcclusionNotRunning() {
if (this.currentOcclusionFuture != null) { if (this.currentOcclusionFuture != null) {
throw new IllegalStateException("Attempted to update occlusion graph during occlusion!"); throw new IllegalStateException("Attempted to update occlusion graph during occlusion!");
@@ -209,37 +189,19 @@ public class RenderListManager {
public void attachRenderSection(RenderSection section) { public void attachRenderSection(RenderSection section) {
this.assertOcclusionNotRunning(); this.assertOcclusionNotRunning();
var key = section.positionAsLong(); this.lattice.attach(section);
OcclusionNode occlusionNode = this.occlusionNodes.get(key);
if (occlusionNode != null) {
throw new IllegalStateException("Occlusion node already exists for section " + section);
}
var node = new OcclusionNode(section);
this.occlusionNodes.put(key, node);
this.connectNeighborNodes(node);
this.needsUpdate = true; this.needsUpdate = true;
} }
public void detachRenderSection(RenderSection section) { public void detachRenderSection(RenderSection section) {
this.assertOcclusionNotRunning(); this.assertOcclusionNotRunning();
var key = section.positionAsLong(); this.lattice.detach(section);
OcclusionNode occlusionNode = this.occlusionNodes.remove(key);
if (occlusionNode == null) {
throw new IllegalStateException("Occlusion node does not exist for section " + section);
}
this.disconnectNeighborNodes(occlusionNode);
this.needsUpdate = true; this.needsUpdate = true;
} }
// Runs the task immediately if no async search is active, otherwise defers it to // Runs the task immediately if no async search is active, otherwise defers it to
// finishPreviousGraphUpdate() to prevent concurrent writes to OcclusionNode fields. // finishPreviousGraphUpdate() to prevent concurrent writes to the lattice arrays.
private void submitUpdateTask(Runnable runnable) { private void submitUpdateTask(Runnable runnable) {
if (this.currentOcclusionFuture == null) { if (this.currentOcclusionFuture == null) {
runnable.run(); runnable.run();
@@ -248,28 +210,16 @@ public class RenderListManager {
} }
} }
public void updateVisibilityData(int x, int y, int z, long visibilityData) { public void updateSectionMetadata(int x, int y, int z, long packedMetadata) {
this.submitUpdateTask(() -> { this.submitUpdateTask(() -> {
var node = this.getOcclusionNode(x, y, z); if (this.lattice.updateSectionMetadata(x, y, z, packedMetadata)) {
if (node != null) {
node.setVisibilityData(visibilityData);
this.needsUpdate = true; this.needsUpdate = true;
} }
}); });
} }
public boolean isSectionVisible(int x, int y, int z) { public boolean isSectionVisible(int x, int y, int z) {
OcclusionNode render = this.getOcclusionNode(x, y, z); return this.visibilitySnapshot.isSectionVisible(x, y, z, this.lastUpdatedFrame);
if (render == null) {
return false;
}
// lastUpdatedFrame only advances in finishPreviousGraphUpdate(), so during an in-progress
// async search this reflects the previous frame's committed result. A section can appear
// visible slightly early (if the async thread has already written its lastVisibleFrame for
// the new frame), but can never appear invisible too early.
return render.getLastVisibleFrame() >= this.lastUpdatedFrame;
} }
public void tickVisibleRenders() { public void tickVisibleRenders() {
@@ -4,12 +4,13 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType; import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.Queue; import java.util.Queue;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller; import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionNode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
public class VisibleChunkCollector implements OcclusionCuller.Visitor { public class VisibleChunkCollector implements OcclusionCuller.Visitor {
@@ -23,9 +24,12 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
private final int targetQueueSize; private final int targetQueueSize;
private final SectionLattice lattice;
private boolean hasAdditionalUpdates; private boolean hasAdditionalUpdates;
public VisibleChunkCollector(int frame, int regionIdsLength, int targetQueueSize) { public VisibleChunkCollector(SectionLattice lattice, int frame, int regionIdsLength, int targetQueueSize) {
this.lattice = lattice;
this.frame = frame; this.frame = frame;
this.sortedRenderLists = new ObjectArrayList<>(); this.sortedRenderLists = new ObjectArrayList<>();
@@ -47,34 +51,33 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
} }
@Override @Override
public void visit(OcclusionNode node, boolean visible) { public void visit(int latticeIndex, int regionId, int sectionIndex, int meta, boolean visible) {
var section = node.getRenderSection();
// Note: even if a section does not have render objects, we must ensure the render list is initialized and put // Note: even if a section does not have render objects, we must ensure the render list is initialized and put
// into the sorted queue of lists, so that we maintain the correct order of draw calls. // into the sorted queue of lists, so that we maintain the correct order of draw calls.
int regionId = node.getRenderRegionId();
ChunkRenderList renderList = this.renderListsByRegion[regionId]; ChunkRenderList renderList = this.renderListsByRegion[regionId];
if (renderList == null) { if (renderList == null) {
renderList = this.createRenderList(section.getRegion()); renderList = this.createRenderList(this.lattice.sectionAt(latticeIndex).getRegion());
} }
if (visible) { if (visible) {
if (section.hasAnythingToRender()) { int visualsFlags = PackedSectionMetadata.getCompactVisualsFlags(meta);
renderList.add(section); if (visualsFlags != 0) {
renderList.add(sectionIndex, visualsFlags);
} }
this.addToRebuildLists(section); ChunkUpdateType type = PackedSectionMetadata.getCompactPendingUpdate(meta);
}
}
private void addToRebuildLists(RenderSection section) {
ChunkUpdateType type = section.getPendingUpdate();
// Skip sections with an in-flight build to avoid redundant work. This is an advisory // Skip sections with an in-flight build to avoid redundant work. This is an advisory
// check only: submitRebuildTasks() will validate getPendingUpdate() independently before // check only: submitRebuildTasks() will validate getPendingUpdate() independently before
// scheduling, so a stale null read of the token here cannot cause a double submission. // scheduling, so a stale read here cannot cause a double submission.
if (type != null && section.getBuildCancellationToken() == null) { if (type != null && !PackedSectionMetadata.isCompactBuildInFlight(meta)) {
this.addToRebuildLists(this.lattice.sectionAt(latticeIndex), type);
}
}
}
private void addToRebuildLists(RenderSection section, ChunkUpdateType type) {
Queue<RenderSection> queue = this.sortedRebuildLists.get(type); Queue<RenderSection> queue = this.sortedRebuildLists.get(type);
// Do not limit the queue size for rebuilds // Do not limit the queue size for rebuilds
@@ -85,7 +88,6 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
this.hasAdditionalUpdates = true; this.hasAdditionalUpdates = true;
} }
} }
}
public SortedRenderLists createRenderLists() { public SortedRenderLists createRenderLists() {
return new SortedRenderLists(this.sortedRenderLists); return new SortedRenderLists(this.sortedRenderLists);
@@ -1,70 +1,190 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion; package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.embeddedt.embeddium.impl.util.collections.DoubleBufferedQueue;
import org.embeddedt.embeddium.impl.util.collections.ReadQueue;
import org.embeddedt.embeddium.impl.util.collections.WriteQueue;
// TODO reintroduce
/*
import org.embeddedt.embeddium.api.render.chunk.RenderSectionDistanceFilter;
import org.embeddedt.embeddium.api.render.chunk.RenderSectionDistanceFilterEvent;
*/
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3ic; import org.joml.Vector3ic;
import java.util.Objects; import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.DIR_MASK;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_STEP;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_SHIFT;
import static org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice.XYZ_LOCAL_MASK;
/**
* Performs a visibility search over the installed cells of a
* {@link SectionLattice}.
*
* <p>A search has three phases:
* <ol>
* <li>prepare the reusable queue and the region cull cache;</li>
* <li>seed the search from the camera section, or scan the appropriate
* world-height plane when the camera is outside the world or unloaded;</li>
* <li>process the queue in traversal order, applying region/frustum and
* render-distance tests before expanding visible cells through the
* occlusion graph, reporting each processed cell directly to the {@link Visitor}.</li>
* </ol>
*
* <p>Occlusion traversal accumulates the directions through which each cell
* was reached, then asks {@link VisibilityEncoding} which outgoing directions
* are possible. Expansion is additionally restricted to directions pointing
* away from the camera, preventing paths from backtracking through the search
* origin. If the camera is in an unloaded section, the search remains useful
* as a frustum/render-distance scan but disables graph occlusion for that
* search.
*
* <p>The queue is reused between searches. A single
* invocation must run at a time, and the lattice's dimensions, coordinates,
* installed membership, and metadata must remain stable until the invocation
* completes. The owning {@code RenderListManager} provides that coordination.
*/
public class OcclusionCuller { public class OcclusionCuller {
private final Long2ReferenceMap<OcclusionNode> sections; private final SectionLattice lattice;
private final int minSectionY, maxSectionY; private final int minSectionY, maxSectionY;
private final DoubleBufferedQueue<OcclusionNode> queue = new DoubleBufferedQueue<>(); // When stepping from a cell in dir, the neighbour is entered from the opposite face.
private static final int[] INCOMING = new int[GraphDirection.COUNT];
static {
for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
INCOMING[dir] = GraphDirectionSet.of(GraphDirection.opposite(dir));
}
}
/*
* Single flat BFS queue. Each entry is
* (packedLocalXYZ << 32) | latticeIndex, where packedLocalXYZ contains
* the three 10-bit local coordinates used by SectionLattice. A live cell
* is enqueued at most once per search, so tail never exceeds
* lattice.installedCount and the queue needs no capacity check in the hot
* loop after it has been sized for the search.
*/
private long[] queue = new long[256];
private int tail;
private final RegionCullCache regionCullCache = new RegionCullCache();
private boolean isCameraInUnloadedSection; private boolean isCameraInUnloadedSection;
public OcclusionCuller(Long2ReferenceMap<OcclusionNode> sections, int minSectionY, int maxSectionY) { public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY) {
this.sections = sections; this.lattice = lattice;
this.minSectionY = minSectionY; this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY; this.maxSectionY = maxSectionY;
} }
/**
* Search the current lattice and report each reached section to
* {@code visitor} in traversal order.
*
* <p>Reached sections are reported even when {@code visible} is false;
* the flag controls whether the section contributes renderable work and
* whether traversal expands through it. The caller must have prepared the
* lattice with {@link SectionLattice#ensureWindowCovers} and must not
* mutate its structure or metadata until this method returns.
*
* @param useOcclusionCulling whether section visibility metadata should
* restrict graph expansion
*/
public void findVisible(Visitor visitor, public void findVisible(Visitor visitor,
Viewport viewport,
float searchDistance,
int numRegions,
boolean useOcclusionCulling,
int frame)
{
// Pre-size so enqueue is a bare store: at most one entry per installed cell.
int installed = this.lattice.installedCount;
if (this.queue.length < installed) {
this.queue = new long[Math.max(installed, this.queue.length * 2)];
}
this.tail = 0;
this.regionCullCache.begin(viewport, searchDistance, numRegions);
this.isCameraInUnloadedSection = false;
this.init(visitor, viewport, searchDistance, useOcclusionCulling, frame);
if (this.isCameraInUnloadedSection) {
useOcclusionCulling = false;
}
this.process(visitor, viewport, searchDistance, useOcclusionCulling, frame);
}
/**
* Process the BFS queue. Each queued cell is classified once, reported
* directly to the visitor, and expanded only when it is visible. Occlusion
* metadata selects the possible exits; the outward-direction mask then
* prevents moving back toward the camera. The visitor is invoked in
* traversal order, with every argument already in registers; it must not
* feed changes back into the running search.
*/
private void process(Visitor visitor,
Viewport viewport, Viewport viewport,
float searchDistance, float searchDistance,
boolean useOcclusionCulling, boolean useOcclusionCulling,
int frame) int frame)
{ {
final var queues = this.queue; final long[] visitState = this.lattice.visitState;
queues.reset(); final long[] sectionMeta = this.lattice.sectionMeta;
final int[] regionOfCell = this.lattice.regionOfCell;
final int[] delta = this.lattice.delta;
final long[] queue = this.queue;
final int baseX = this.lattice.baseX, baseY = this.lattice.baseY, baseZ = this.lattice.baseZ;
this.isCameraInUnloadedSection = false; final RegionCullCache cache = this.regionCullCache;
this.init(visitor, queues.write(), viewport, searchDistance, useOcclusionCulling, frame); final CameraTransform transform = viewport.getTransform();
if(this.isCameraInUnloadedSection) { final Vector3ic camera = viewport.getChunkCoord();
useOcclusionCulling = false; final int camX = camera.x(), camY = camera.y(), camZ = camera.z();
final long frameStamp = SectionLattice.frameStamp(frame);
int head = 0;
int tail = this.tail;
// Constant neighbour strides / packed-coord steps, hoisted so the unrolled expansion below uses
// immediates instead of per-edge array loads. delta[EAST]=+strideX, delta[SOUTH]=+strideZ, Y-stride=1.
final int strideX = delta[GraphDirection.EAST];
final int strideZ = delta[GraphDirection.SOUTH];
final int xStep = 1 << (2 * XYZ_SHIFT);
final int yStep = 1 << XYZ_SHIFT;
while (head < tail) {
long entry = queue[head++];
int idx = (int) entry;
int xyz = (int) (entry >>> 32);
int chunkX = baseX + ((xyz >>> (2 * XYZ_SHIFT)) & XYZ_LOCAL_MASK);
int chunkY = baseY + ((xyz >>> XYZ_SHIFT) & XYZ_LOCAL_MASK);
int chunkZ = baseZ + (xyz & XYZ_LOCAL_MASK);
int regionId = regionOfCell[idx];
long sm = sectionMeta[idx];
int compactMeta = PackedSectionMetadata.toCompactMeta(sm);
int classification = cache.classify(regionId,
regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH),
regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT),
regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH));
// Fully-inside regions need no per-section frustum test. Sections
// in a partial region are checked individually for both distance
// and frustum visibility; outside regions are not traversed.
boolean visible;
if (classification == Frustum.PARTIALLY_INSIDE) {
visible = isWithinRenderDistance(transform, chunkX, chunkY, chunkZ, searchDistance)
&& isWithinFrustum(viewport, chunkX, chunkY, chunkZ);
} else {
visible = classification == Frustum.FULLY_INSIDE;
} }
while (queues.flip()) { int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ);
processQueue(visitor, viewport, searchDistance, useOcclusionCulling, frame, queues.read(), queues.write()); visitor.visit(idx, regionId, sectionIndex, compactMeta, visible);
}
}
private static void processQueue(Visitor visitor,
Viewport viewport,
float searchDistance,
boolean useOcclusionCulling,
int frame,
ReadQueue<OcclusionNode> readQueue,
WriteQueue<OcclusionNode> writeQueue)
{
OcclusionNode section;
while ((section = readQueue.dequeue()) != null) {
boolean visible = isSectionVisible(section, viewport, searchDistance);
visitor.visit(section, visible);
if (!visible) { if (!visible) {
continue; continue;
@@ -72,133 +192,156 @@ public class OcclusionCuller {
int connections; int connections;
{
if (useOcclusionCulling) { if (useOcclusionCulling) {
// When using occlusion culling, we can only traverse into neighbors for which there is a path of // Merge the outgoing paths reachable from every incoming path
// visibility through this chunk. This is determined by taking all the incoming paths to this chunk and // accumulated in this cell.
// creating a union of the outgoing paths from those. int incoming = (int) (visitState[idx] & DIR_MASK);
connections = VisibilityEncoding.getConnections(section.getVisibilityData(), section.getIncomingDirections()); connections = VisibilityEncoding.getConnections(
sm & PackedSectionMetadata.VISIBILITY_MASK, incoming);
} else { } else {
// Not using any occlusion culling, so traversing in any direction is legal.
connections = GraphDirectionSet.ALL; connections = GraphDirectionSet.ALL;
} }
// We can only traverse *outwards* from the center of the graph search, so mask off any invalid // We can only traverse outwards from the centre of the search.
// directions. connections &= getOutwardDirections(chunkX, chunkY, chunkZ, camX, camY, camZ);
connections &= getOutwardDirections(viewport.getChunkCoord(), section);
}
visitNeighbors(writeQueue, section, connections, frame); // Unrolled variant of visitNeighbors, with delta, step, incoming values inlined into each branch.
// The unrolling measurably improves performance here.
if ((connections & (1 << GraphDirection.DOWN)) != 0) {
final int n = idx - 1;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - yStep) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.UP);
}
if ((connections & (1 << GraphDirection.UP)) != 0) {
final int n = idx + 1;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + yStep) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.DOWN);
}
if ((connections & (1 << GraphDirection.NORTH)) != 0) {
final int n = idx - strideZ;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - 1) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.SOUTH);
}
if ((connections & (1 << GraphDirection.SOUTH)) != 0) {
final int n = idx + strideZ;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + 1) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.NORTH);
}
if ((connections & (1 << GraphDirection.WEST)) != 0) {
final int n = idx - strideX;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz - xStep) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.EAST);
}
if ((connections & (1 << GraphDirection.EAST)) != 0) {
final int n = idx + strideX;
long ns = visitState[n];
if (ns < frameStamp) { ns = frameStamp; queue[tail++] = ((long) (xyz + xStep) << 32) | (n & 0xFFFFFFFFL); }
visitState[n] = ns | (1 << GraphDirection.WEST);
} }
} }
private static boolean isSectionVisible(OcclusionNode section, Viewport viewport, float maxDistance) { this.tail = tail;
return isWithinRenderDistance(viewport.getTransform(), section, maxDistance) && isWithinFrustum(viewport, section);
} }
private static void visitNeighbors(final WriteQueue<OcclusionNode> queue, OcclusionNode section, int outgoing, int frame) { // Visit each selected neighbour using both its linear array offset and
// Only traverse into neighbors which are actually present. // its packed-coordinate offset. The lattice border makes idx + delta safe.
// This avoids a null-check on each invocation to enqueue, and since the compiler will see that a null private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) {
// is never encountered (after profiling), it will optimize it away. while (outgoing != 0) {
outgoing &= section.getAdjacentMask(); int dir = Integer.numberOfTrailingZeros(outgoing);
outgoing &= outgoing - 1;
// Check if there are any valid connections left, and if not, early-exit. this.visitNode(visitState, queue, idx + delta[dir], xyz + XYZ_STEP[dir], INCOMING[dir], frameStamp);
if (outgoing == GraphDirectionSet.NONE) {
return;
}
// This helps the compiler move the checks for some invariants upwards.
queue.ensureCapacity(6);
if (GraphDirectionSet.contains(outgoing, GraphDirection.DOWN)) {
visitNode(queue, section.adjacentDown, GraphDirectionSet.of(GraphDirection.UP), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.UP)) {
visitNode(queue, section.adjacentUp, GraphDirectionSet.of(GraphDirection.DOWN), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.NORTH)) {
visitNode(queue, section.adjacentNorth, GraphDirectionSet.of(GraphDirection.SOUTH), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.SOUTH)) {
visitNode(queue, section.adjacentSouth, GraphDirectionSet.of(GraphDirection.NORTH), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.WEST)) {
visitNode(queue, section.adjacentWest, GraphDirectionSet.of(GraphDirection.EAST), frame);
}
if (GraphDirectionSet.contains(outgoing, GraphDirection.EAST)) {
visitNode(queue, section.adjacentEast, GraphDirectionSet.of(GraphDirection.WEST), frame);
} }
} }
private static void visitNode(final WriteQueue<OcclusionNode> queue, @NotNull OcclusionNode render, int incoming, int frame) { /*
if (render.getLastVisibleFrame() != frame) { * Ordered-compare visit gate. A slot is enqueued only on its first visit
// This is the first time we are visiting this section during the given frame, so we must * this frame, while incoming directions are OR-ed even on later visits so
// reset the state. * the cell sees the union of all reachable entry paths. SENTINEL cells,
render.setLastVisibleFrame(frame); * including the border ring, never compare below frameStamp and therefore
render.setIncomingDirections(GraphDirectionSet.NONE); * need no separate occupancy check.
*/
private void visitNode(long[] visitState, long[] queue, int idx, int xyz, int incoming, long frameStamp) {
long state = visitState[idx];
queue.enqueue(render); if (state < frameStamp) {
visitState[idx] = frameStamp | incoming;
queue[this.tail++] = ((long) xyz << 32) | (idx & 0xFFFFFFFFL);
} else {
visitState[idx] = state | incoming;
}
} }
render.addIncomingDirections(incoming); // Allow movement only away from the camera on each axis. A coordinate
} // equal to the camera coordinate permits both directions on that axis.
private static int getOutwardDirections(int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ) {
private static int getOutwardDirections(Vector3ic origin, OcclusionNode section) {
int planes = 0; int planes = 0;
planes |= section.getChunkX() <= origin.x() ? 1 << GraphDirection.WEST : 0; planes |= chunkX <= camX ? 1 << GraphDirection.WEST : 0;
planes |= section.getChunkX() >= origin.x() ? 1 << GraphDirection.EAST : 0; planes |= chunkX >= camX ? 1 << GraphDirection.EAST : 0;
planes |= section.getChunkY() <= origin.y() ? 1 << GraphDirection.DOWN : 0; planes |= chunkY <= camY ? 1 << GraphDirection.DOWN : 0;
planes |= section.getChunkY() >= origin.y() ? 1 << GraphDirection.UP : 0; planes |= chunkY >= camY ? 1 << GraphDirection.UP : 0;
planes |= section.getChunkZ() <= origin.z() ? 1 << GraphDirection.NORTH : 0; planes |= chunkZ <= camZ ? 1 << GraphDirection.NORTH : 0;
planes |= section.getChunkZ() >= origin.z() ? 1 << GraphDirection.SOUTH : 0; planes |= chunkZ >= camZ ? 1 << GraphDirection.SOUTH : 0;
return planes; return planes;
} }
private static boolean isWithinRenderDistance(CameraTransform camera, OcclusionNode section, float maxDistance) { // Convert a section coordinate to the origin of its containing render
// origin point of the chunk's bounding box (in view space) // region, in block coordinates.
int ox = section.getOriginX() - camera.intX; private static int regionOrigin(int chunkCoord, int shift, int blockSize) {
int oy = section.getOriginY() - camera.intY; return (chunkCoord >> shift) * blockSize;
int oz = section.getOriginZ() - camera.intZ; }
// coordinates of the point to compare (in view space) /**
// this is the closest point within the bounding box to the center (0, 0, 0) * Test the search's render-distance shape against a section bounding box.
* Horizontal distance is circular in X/Z, while vertical distance is
* tested independently so tall searches do not use a spherical cutoff.
*/
private static boolean isWithinRenderDistance(CameraTransform camera, int chunkX, int chunkY, int chunkZ, float maxDistance) {
// Origin point of the chunk's bounding box in view space.
int ox = (chunkX << 4) - camera.intX;
int oy = (chunkY << 4) - camera.intY;
int oz = (chunkZ << 4) - camera.intZ;
// Closest point within the bounding box to the camera at (0, 0, 0).
// Testing the closest point avoids rejecting a section whose near face
// is within range even when its origin is farther away.
float dx = nearestToZero(ox, ox + 16) - camera.fracX; float dx = nearestToZero(ox, ox + 16) - camera.fracX;
float dy = nearestToZero(oy, oy + 16) - camera.fracY; float dy = nearestToZero(oy, oy + 16) - camera.fracY;
float dz = nearestToZero(oz, oz + 16) - camera.fracZ; float dz = nearestToZero(oz, oz + 16) - camera.fracZ;
return ((((dx * dx) + (dz * dz)) < (maxDistance * maxDistance)) && (Math.abs(dy) < maxDistance)); return ((((dx * dx) + (dz * dz)) < (maxDistance * maxDistance)) && (Math.abs(dy) < maxDistance));
//return DistanceFilterHolder.INSTANCE.isWithinDistance(dx, dy, dz, maxDistance);
} }
@SuppressWarnings("ManualMinMaxCalculation") // we know what we are doing. // isBoxVisible takes a section centre and half-size. The half-size is
private static int nearestToZero(int min, int max) { // 8 blocks for the section, plus model overhang and a small precision
// this compiles to slightly better code than Math.min(Math.max(0, min), max) // epsilon (see GH#2132).
int clamped = 0; private static final float CHUNK_SECTION_SIZE = 8.0f /* section half-size */
if (min > 0) { clamped = min; } + 1.0f /* maximum model extent */
if (max < 0) { clamped = max; } + 0.125f /* epsilon */;
return clamped;
}
// The bounding box of a chunk section must be large enough to contain all possible geometry within it. Block models /**
// can extend outside a block volume by +/- 1.0 blocks on all axis. Additionally, we make use of a small epsilon * Test a section's conservatively expanded bounding box against the
// to deal with floating point imprecision during a frustum check (see GH#2132). * viewport frustum.
private static final float CHUNK_SECTION_SIZE = 8.0f /* chunk bounds */ + 1.0f /* maximum model extent */ + 0.125f /* epsilon */; */
public static boolean isWithinFrustum(Viewport viewport, int chunkX, int chunkY, int chunkZ) {
public static boolean isWithinFrustum(Viewport viewport, OcclusionNode section) { return viewport.isBoxVisible((chunkX << 4) + 8, (chunkY << 4) + 8, (chunkZ << 4) + 8, CHUNK_SECTION_SIZE);
return viewport.isBoxVisible(section.getCenterX(), section.getCenterY(), section.getCenterZ(), CHUNK_SECTION_SIZE);
} }
/**
* Choose the search seed. A loaded in-world camera section is processed
* inline; an out-of-height or unloaded camera is handled by scanning a
* horizontal plane of nearby loaded sections.
*/
private void init(Visitor visitor, private void init(Visitor visitor,
WriteQueue<OcclusionNode> queue,
Viewport viewport, Viewport viewport,
float searchDistance, float searchDistance,
boolean useOcclusionCulling, boolean useOcclusionCulling,
@@ -207,131 +350,155 @@ public class OcclusionCuller {
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
if (origin.y() < this.minSectionY) { if (origin.y() < this.minSectionY) {
// below the world // Below the world: seed the lowest section with an incoming path
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // from below so traversal can proceed upward from the boundary.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
this.minSectionY, GraphDirectionSet.of(GraphDirection.DOWN)); this.minSectionY, GraphDirectionSet.of(GraphDirection.DOWN));
} else if (origin.y() >= this.maxSectionY) { } else if (origin.y() >= this.maxSectionY) {
// above the world // Above the world: seed the highest section with an incoming path
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // from above so traversal can proceed downward from the boundary.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
this.maxSectionY - 1, GraphDirectionSet.of(GraphDirection.UP)); this.maxSectionY - 1, GraphDirectionSet.of(GraphDirection.UP));
} else if(this.getRenderSection(origin.x(), origin.y(), origin.z()) == null) { } else if (this.lattice.getRenderSection(origin.x(), origin.y(), origin.z()) == null) {
// inside the world height-wise, but in an unloaded section // Inside the world height-wise, but in an unloaded section. Seed
this.initOutsideWorldHeight(queue, viewport, searchDistance, frame, // both vertical entry paths and disable occlusion below because
// there is no camera section from which to obtain visibility data.
this.initOutsideWorldHeight(viewport, searchDistance, frame,
origin.y(), GraphDirectionSet.of(GraphDirection.UP) | GraphDirectionSet.of(GraphDirection.DOWN)); origin.y(), GraphDirectionSet.of(GraphDirection.UP) | GraphDirectionSet.of(GraphDirection.DOWN));
this.isCameraInUnloadedSection = true; this.isCameraInUnloadedSection = true;
} else { } else {
this.initWithinWorld(visitor, queue, viewport, useOcclusionCulling, frame); this.initWithinWorld(visitor, viewport, useOcclusionCulling, frame);
} }
} }
private void initWithinWorld(Visitor visitor, WriteQueue<OcclusionNode> queue, Viewport viewport, boolean useOcclusionCulling, int frame) { // The loaded camera section is the root: it is visited immediately, not
// queued, and its visible paths seed the BFS with no incoming direction.
private void initWithinWorld(Visitor visitor, Viewport viewport, boolean useOcclusionCulling, int frame) {
final long[] visitState = this.lattice.visitState;
final long[] queue = this.queue;
final int[] delta = this.lattice.delta;
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
var section = this.getRenderSection(origin.x(), origin.y(), origin.z()); int idx = this.lattice.indexOf(origin.x(), origin.y(), origin.z());
Objects.requireNonNull(section); // The camera section is loaded and, after ensureWindowCovers, installed
// in the lattice interior.
long frameStamp = SectionLattice.frameStamp(frame);
visitState[idx] = frameStamp;
section.setLastVisibleFrame(frame); // Visit the origin immediately; it is processed inline rather than
section.setIncomingDirections(GraphDirectionSet.NONE); // enqueued so the BFS starts with its neighbours.
int sectionIndex = LocalSectionIndex.pack(origin.x(), origin.y(), origin.z());
visitor.visit(section, true); long sm = this.lattice.sectionMeta[idx];
visitor.visit(idx, this.lattice.regionOfCell[idx], sectionIndex, PackedSectionMetadata.toCompactMeta(sm), true);
int outgoing; int outgoing;
if (useOcclusionCulling) { if (useOcclusionCulling) {
// Since the camera is located inside this chunk, there are no "incoming" directions. So we need to instead // The camera is inside this chunk, so there are no incoming directions; enqueue any path out.
// find any possible paths out of this chunk and enqueue those neighbors. outgoing = VisibilityEncoding.getConnections(sm & PackedSectionMetadata.VISIBILITY_MASK);
outgoing = VisibilityEncoding.getConnections(section.getVisibilityData());
} else { } else {
// Occlusion culling is disabled, so we can traverse into any neighbor.
outgoing = GraphDirectionSet.ALL; outgoing = GraphDirectionSet.ALL;
} }
visitNeighbors(queue, section, outgoing, frame); int xyz = this.lattice.packXyz(origin.x(), origin.y(), origin.z());
this.visitNeighbors(visitState, queue, delta, idx, xyz, outgoing, frameStamp);
} }
// Enqueues sections that are inside the viewport using diamond spiral iteration to avoid sorting and ensure a /**
// consistent order. Innermost layers are enqueued first. Within each layer, iteration starts at the northernmost * Seed a boundary plane with nearby loaded sections in deterministic
// section and proceeds counterclockwise (N->W->S->E). * diamond-spiral order. The complete inner layers cover Manhattan distance
private void initOutsideWorldHeight(WriteQueue<OcclusionNode> queue, * through {@code radius}; the remaining layers fill the surrounding square
Viewport viewport, * out to the same X/Z radius without sorting. Each accepted section is
* given the supplied incoming direction set before normal BFS processing.
*/
private void initOutsideWorldHeight(Viewport viewport,
float searchDistance, float searchDistance,
int frame, int frame,
int height, int height,
int direction) int direction)
{ {
final long[] visitState = this.lattice.visitState;
final long[] queue = this.queue;
var origin = viewport.getChunkCoord(); var origin = viewport.getChunkCoord();
var radius = MathUtil.mojfloor(searchDistance / 16.0f); var radius = MathUtil.mojfloor(searchDistance / 16.0f);
long frameStamp = SectionLattice.frameStamp(frame);
// Layer 0 // Layer 0: the section directly below/above the camera, if loaded and visible.
this.tryVisitNode(queue, origin.x(), height, origin.z(), direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x(), height, origin.z(), direction, frameStamp, viewport);
// Complete layers, excluding layer 0 // Complete inner layers, excluding layer 0.
for (int layer = 1; layer <= radius; layer++) { for (int layer = 1; layer <= radius; layer++) {
for (int z = -layer; z < layer; z++) { for (int z = -layer; z < layer; z++) {
int x = Math.abs(z) - layer; int x = Math.abs(z) - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = layer; z > -layer; z--) { for (int z = layer; z > -layer; z--) {
int x = layer - Math.abs(z); int x = layer - Math.abs(z);
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
} }
// Incomplete layers // Complete the surrounding square with the outer portions of the
// remaining diamond layers.
for (int layer = radius + 1; layer <= 2 * radius; layer++) { for (int layer = radius + 1; layer <= 2 * radius; layer++) {
int l = layer - radius; int l = layer - radius;
for (int z = -radius; z <= -l; z++) { for (int z = -radius; z <= -l; z++) {
int x = -z - layer; int x = -z - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = l; z <= radius; z++) { for (int z = l; z <= radius; z++) {
int x = z - layer; int x = z - layer;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = radius; z >= l; z--) { for (int z = radius; z >= l; z--) {
int x = layer - z; int x = layer - z;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
for (int z = -l; z >= -radius; z--) { for (int z = -l; z >= -radius; z--) {
int x = layer + z; int x = layer + z;
this.tryVisitNode(queue, origin.x() + x, height, origin.z() + z, direction, frame, viewport); this.tryVisitNode(visitState, queue, origin.x() + x, height, origin.z() + z, direction, frameStamp, viewport);
} }
} }
} }
private void tryVisitNode(WriteQueue<OcclusionNode> queue, int x, int y, int z, int direction, int frame, Viewport viewport) { // Seed-only visit: reject unloaded/out-of-window cells before doing a
OcclusionNode section = this.getRenderSection(x, y, z); // frustum test, then pass the accepted cell through the normal visit gate.
private void tryVisitNode(long[] visitState, long[] queue, int x, int y, int z, int direction, long frameStamp, Viewport viewport) {
int idx = this.lattice.indexOf(x, y, z);
if (section == null || !isWithinFrustum(viewport, section)) { // Out of the window or empty: visitNode would reject SENTINEL anyway,
// but avoid the frustum test for cells that cannot be searched.
if (idx < 0 || visitState[idx] == SectionLattice.SENTINEL) {
return; return;
} }
visitNode(queue, section, direction, frame); if (!isWithinFrustum(viewport, x, y, z)) {
return;
} }
private OcclusionNode getRenderSection(int x, int y, int z) { this.visitNode(visitState, queue, idx, this.lattice.packXyz(x, y, z), direction, frameStamp);
return this.sections.get(PositionUtil.packSection(x, y, z));
}
public interface Visitor {
void visit(OcclusionNode section, boolean visible);
}
/*
private static class DistanceFilterHolder {
private static final RenderSectionDistanceFilter INSTANCE;
static {
var event = new RenderSectionDistanceFilterEvent();
RenderSectionDistanceFilterEvent.BUS.post(event);
INSTANCE = event.getFilter();
}
} }
/**
* Receives one record for each section reached by a search, in traversal
* order. A record can be non-visible: such a section is reported for
* ordering/region bookkeeping but does not expand the search.
*/ */
public interface Visitor {
/**
* @param latticeIndex installed {@link SectionLattice} slot for the section
* @param regionId owning render-region identifier
* @param sectionIndex section's compact local index within its region
* @param meta compact collector metadata
* @param visible whether the section passed the visibility tests
*/
void visit(int latticeIndex, int regionId, int sectionIndex, int meta, boolean visible);
}
} }
@@ -1,95 +0,0 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import lombok.Getter;
import lombok.Setter;
import org.embeddedt.embeddium.impl.render.chunk.AbstractSection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
public class OcclusionNode extends AbstractSection {
private int incomingDirections;
private int lastVisibleFrame = -1;
private int adjacentMask;
public OcclusionNode
adjacentDown,
adjacentUp,
adjacentNorth,
adjacentSouth,
adjacentWest,
adjacentEast;
/**
* The occlusion culling data which determines this chunk's connectedness on the visibility graph.
*/
@Getter
@Setter
private long visibilityData = VisibilityEncoding.NULL;
private final RenderSection section;
@Getter
private final int renderRegionId;
public OcclusionNode(RenderSection section) {
super(section.getChunkX(), section.getChunkY(), section.getChunkZ());
this.section = section;
this.renderRegionId = section.getRegion().getId();
}
public OcclusionNode getAdjacent(int direction) {
return switch (direction) {
case GraphDirection.DOWN -> this.adjacentDown;
case GraphDirection.UP -> this.adjacentUp;
case GraphDirection.NORTH -> this.adjacentNorth;
case GraphDirection.SOUTH -> this.adjacentSouth;
case GraphDirection.WEST -> this.adjacentWest;
case GraphDirection.EAST -> this.adjacentEast;
default -> null;
};
}
public void setAdjacentNode(int direction, OcclusionNode node) {
if (node == null) {
this.adjacentMask &= ~GraphDirectionSet.of(direction);
} else {
this.adjacentMask |= GraphDirectionSet.of(direction);
}
switch (direction) {
case GraphDirection.DOWN -> this.adjacentDown = node;
case GraphDirection.UP -> this.adjacentUp = node;
case GraphDirection.NORTH -> this.adjacentNorth = node;
case GraphDirection.SOUTH -> this.adjacentSouth = node;
case GraphDirection.WEST -> this.adjacentWest = node;
case GraphDirection.EAST -> this.adjacentEast = node;
default -> { }
}
}
public int getAdjacentMask() {
return this.adjacentMask;
}
public void setLastVisibleFrame(int frame) {
this.lastVisibleFrame = frame;
}
public int getLastVisibleFrame() {
return this.lastVisibleFrame;
}
public int getIncomingDirections() {
return this.incomingDirections;
}
public void addIncomingDirections(int directions) {
this.incomingDirections |= directions;
}
public void setIncomingDirections(int directions) {
this.incomingDirections = directions;
}
public RenderSection getRenderSection() {
return this.section;
}
}
@@ -0,0 +1,188 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import java.util.Arrays;
import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero;
import static org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion.*;
/**
* Per-search memoization for region-level visibility classification.
*
* <p>Sections are grouped into dense 8x4x8-section regions
* ({@code 128x64x128} blocks). The cache computes a conservative result for
* each region once per search, then lets {@link OcclusionCuller} avoid the
* exact distance and frustum tests whenever the region result is conclusive.
* Region ids are dense and serve directly as cache indices.
*
* <p>The classification contract is:
* <ul>
* <li>{@link Frustum#OUTSIDE}: every section is guaranteed to fail the
* combined render-distance/frustum visibility test;</li>
* <li>{@link Frustum#FULLY_INSIDE}: every section is guaranteed to pass both
* tests; and</li>
* <li>{@link Frustum#PARTIALLY_INSIDE}: the region bounds are inconclusive,
* so the caller must test each section exactly.</li>
* </ul>
* The bounds include padding and floating-point slack, so a conclusive result
* must never incorrectly reject or accept a section.
*
* <p>The cache is mutable and intended for one search at a time. Call
* {@link #begin(Viewport, float, int)} before {@link #classify}; it resets the
* classification array so no result leaks between searches.
*/
final class RegionCullCache {
// Sentinel stored in unclassified slots; distinct from every Frustum result.
private static final byte UNCOMPUTED = -1;
// Per-section frustum padding is 9.125 - 8 = 1.125 blocks. Add a
// further 1/32 block to absorb camera-relative floating-point rounding.
private static final float FRUSTUM_PAD = 1.125f + 0.03125f;
// Slack for distance bounds; errors at render-distance magnitudes are
// approximately 1e-4, so this keeps conservative comparisons stable.
private static final float DISTANCE_EPSILON = 0.001f;
private static final int INITIAL_CAPACITY = 64;
// Indexed by dense region id; UNCOMPUTED until classified in the current search.
private byte[] classification = new byte[INITIAL_CAPACITY];
// Search configuration, refreshed by begin().
private Viewport viewport;
private CameraTransform camera;
private float maxDistance;
/**
* Start a search and configure the camera-relative bounds used by
* subsequent classifications.
*
* @param viewport current camera and frustum
* @param searchDistance maximum horizontal/vertical render distance
* @param numRegions exclusive upper bound of the dense region ids that
* may be passed to {@link #classify}
*/
void begin(Viewport viewport, float searchDistance, int numRegions) {
this.viewport = viewport;
this.camera = viewport.getTransform();
this.maxDistance = searchDistance;
if (numRegions > this.classification.length) {
this.grow(numRegions);
}
Arrays.fill(this.classification, 0, numRegions, UNCOMPUTED);
}
/**
* Return the cached classification for a region, computing it on first
* use in the current search.
*
* @param regionId dense region id and cache slot
* @param regionOriginX block X coordinate of the region's minimum corner
* @param regionOriginY block Y coordinate of the region's minimum corner
* @param regionOriginZ block Z coordinate of the region's minimum corner
* @return one of the {@link Frustum} classification constants
* @implNote The origin must correspond to {@code regionId}; only the first
* classification for an id is computed in a search.
*/
int classify(int regionId, int regionOriginX, int regionOriginY, int regionOriginZ) {
byte result = this.classification[regionId];
if (result == UNCOMPUTED) {
result = (byte) this.compute(regionOriginX, regionOriginY, regionOriginZ);
this.classification[regionId] = result;
}
return result;
}
// Grow the classification array; contents are reset by the next begin().
private void grow(int minimumCapacity) {
int capacity = Math.max(minimumCapacity, this.classification.length * 2);
this.classification = new byte[capacity];
}
/**
* Compute conservative region bounds. Distance is rejected first when the
* nearest possible section point is too far away; otherwise the padded
* region box is classified against the camera frustum.
*/
private int compute(int regionOriginX, int regionOriginY, int regionOriginZ) {
final CameraTransform t = this.camera;
final float maxDistance = this.maxDistance;
final int ax = regionOriginX - t.intX, bx = ax + REGION_BLOCK_WIDTH;
final int ay = regionOriginY - t.intY, by = ay + REGION_BLOCK_HEIGHT;
final int az = regionOriginZ - t.intZ, bz = az + REGION_BLOCK_LENGTH;
// Signed range of the nearest-point distance component for all member
// section boxes along each axis.
final float loX = nearestToZero(ax, ax + 16) - t.fracX;
final float hiX = nearestToZero(bx - 16, bx) - t.fracX;
final float loY = nearestToZero(ay, ay + 16) - t.fracY;
final float hiY = nearestToZero(by - 16, by) - t.fracY;
final float loZ = nearestToZero(az, az + 16) - t.fracZ;
final float hiZ = nearestToZero(bz - 16, bz) - t.fracZ;
// Upper bound on every member's absolute distance component.
final float farX = maxAbs(loX, hiX) + DISTANCE_EPSILON;
final float farY = maxAbs(loY, hiY) + DISTANCE_EPSILON;
final float farZ = maxAbs(loZ, hiZ) + DISTANCE_EPSILON;
// Lower bound on every member's absolute distance component.
final float nearX = Math.max(0.0f, minAbs(loX, hiX) - DISTANCE_EPSILON);
final float nearY = Math.max(0.0f, minAbs(loY, hiY) - DISTANCE_EPSILON);
final float nearZ = Math.max(0.0f, minAbs(loZ, hiZ) - DISTANCE_EPSILON);
final float maxDistanceSq = maxDistance * maxDistance;
// If even the nearest possible point fails the distance test, every
// section is out of range and the frustum need not be queried.
boolean distanceOut = ((nearX * nearX) + (nearZ * nearZ)) >= maxDistanceSq || nearY >= maxDistance;
if (distanceOut) {
return Frustum.OUTSIDE;
}
// Only claim FULLY_INSIDE when the farthest possible point is still
// strictly inside the distance bounds.
boolean distanceIn = ((farX * farX) + (farZ * farZ)) < maxDistanceSq && farY < maxDistance;
int result = this.viewport.intersectCameraRelativeBox(
(ax - t.fracX) - FRUSTUM_PAD,
(ay - t.fracY) - FRUSTUM_PAD,
(az - t.fracZ) - FRUSTUM_PAD,
(bx - t.fracX) + FRUSTUM_PAD,
(by - t.fracY) + FRUSTUM_PAD,
(bz - t.fracZ) + FRUSTUM_PAD);
if (result == Frustum.FULLY_INSIDE) {
// A fully-inside frustum result is conclusive only when distance
// is also conclusive for every member section.
return distanceIn ? Frustum.FULLY_INSIDE : Frustum.PARTIALLY_INSIDE;
} else {
return result;
}
}
// Largest absolute value in a signed interval.
private static float maxAbs(float lo, float hi) {
return Math.max(Math.abs(lo), Math.abs(hi));
}
// Smallest absolute value in a signed interval.
private static float minAbs(float lo, float hi) {
if (lo > 0.0f) {
return lo;
}
if (hi < 0.0f) {
return -hi;
}
return 0.0f;
}
}
@@ -0,0 +1,728 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3ic;
import java.util.Arrays;
/**
* Camera-centered spatial index backing the occlusion visibility traversal.
*
* <p>The lattice is a dense, flat window around the camera. It gives the
* traversal constant-time access to a section and to its six neighbours,
* while avoiding an object allocation for every cell on the hot path.
*
* <p>This class has two layers of state:
* <ul>
* <li>{@code sections} is the authoritative set of every attached section.
* It is used for world-coordinate lookup and for rebuilding the window.</li>
* <li>The lattice is a dense X/Z window containing the attached sections
* that can participate in the current search. A section outside that
* window remains attached, but has no lattice slot until a rebase brings
* it inside the window.</li>
* </ul>
* The lattice is therefore an index of {@code sections}, not a second
* collection or an overflow cache; {@code latticeSection} only contains the
* subset that is currently installed.
*
* <p>The arrays are parallel: for a given lattice index,
* {@code latticeSection}, {@code sectionMeta}, and {@code regionOfCell}
* describe the same cell. X and Z are camera-windowed, while Y covers the
* entire world height. The window is allocated lazily by
* {@link #ensureWindowCovers}. The first call allocates the arrays and then
* establishes their base coordinates. If a later camera position no longer
* fits, a same-sized window is normally slid in place: the overlapping cells
* are copied, and only the newly exposed X/Z band is looked up in
* {@code sections}. A resize or a move with no overlap falls back to a full
* {@link #rebase}.
*
* <p>The installable interior ({@code [1, dim-2]} on each axis) is wrapped by
* a permanent one-cell ring of sentinel cells (index {@code 0} and
* {@code dim-1}). Every installable cell therefore has a valid array index one
* step away in all six directions, so traversal can add a value from
* {@link #delta} without a bounds check: the neighbour is always in-array,
* whether it holds another cell or a sentinel. The border ring is never
* installable, even when the window holds no sections.
*
* <p>The normal lifecycle is construction with no lattice allocation, followed
* by {@link #ensureWindowCovers}, which allocates and establishes the window,
* then attachment/detachment and metadata updates between searches, and finally
* {@link #findVisible}. Structural state is single-threaded: attachment,
* detachment, metadata updates, allocation, and rebasing must not overlap the
* search. The search may run asynchronously and writes per-frame visit state
* itself, but its array lengths, window coordinates, and installed membership
* must remain stable for its duration. {@code RenderListManager} enforces this
* boundary.
*/
public final class SectionLattice {
private static final int SLACK = 4;
/*
* visitState representation:
*
* 63 40 39 8 7 0
* +----------------------+---------------------+---------+
* | unused | frame stamp | dir bits |
* +----------------------+---------------------+---------+
*
* The frame stamp is the unsigned 32-bit search frame in bits 8..39;
* the low byte accumulates incoming GraphDirectionSet bits. SENTINEL is
* larger than every valid stamped value, so empty cells fail the ordered
* visit gate. INITIAL is smaller than every frame stamp, so an installed
* but unvisited cell is eligible for the current search.
*/
static final int FRAME_SHIFT = 8;
static final int DIR_MASK = 0xFF;
// Empty slot, including the permanent border ring.
static final long SENTINEL = Long.MAX_VALUE;
// Installed slot that has not yet been visited by a search.
static final long INITIAL = -1L;
/*
* Packed local coordinate: (lx << 20) | (ly << 10) | lz. Each local axis
* therefore needs fewer than 1024 positions. MAX_DIM must stay within
* that 10-bit limit, independently of MAX_LATTICE_SLOTS, which limits
* the total number of cells (and therefore the allocation size).
* packXyz produces this representation; XYZ_LOCAL_MASK extracts an axis;
* XYZ_STEP is the corresponding per-direction increment.
*/
static final int XYZ_SHIFT = 10;
static final int XYZ_LOCAL_MASK = (1 << XYZ_SHIFT) - 1;
static final int[] XYZ_STEP = new int[GraphDirection.COUNT];
static {
for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
XYZ_STEP[dir] = GraphDirection.x(dir) * (1 << (2 * XYZ_SHIFT))
+ GraphDirection.y(dir) * (1 << XYZ_SHIFT)
+ GraphDirection.z(dir);
}
}
private static final int MAX_DIM = 1 << XYZ_SHIFT;
private static final int MAX_LATTICE_SLOTS = 1 << 22;
private final Long2ReferenceMap<RenderSection> sections = new Long2ReferenceOpenHashMap<>();
private final OcclusionCuller culler;
private final int minSectionY, maxSectionY;
/*
* Parallel primitive/object arrays, allocated lazily once the search
* distance determines the X/Z dimensions. The linear index is
* (lx * dimZ + lz) * dimY + ly, where local coordinates are relative to
* (baseX, baseY, baseZ). Package-private visibility lets OcclusionCuller
* read these arrays directly on its hot path.
*
* Invariants:
* - only local coordinates [1, dim-2] are installable;
* - the outer ring is always SENTINEL and has no section or metadata;
* - all parallel arrays describe the same cell;
* - installedCount equals the number of non-null latticeSection entries.
*/
long[] visitState;
long[] sectionMeta;
int[] regionOfCell;
RenderSection[] latticeSection;
// Y is never windowed: the complete world height plus one sentinel cell at each vertical edge.
final int dimY;
final int baseY;
int dimX, dimZ;
// baseX/baseZ become meaningful after the first rebase; baseY is fixed by the world-height bounds.
int baseX, baseZ;
// Linear offset for one neighbour step in each direction; the sentinel border makes every step safe.
final int[] delta = new int[GraphDirection.COUNT];
private int strideX, strideZ;
// True when the current dimensions, base coordinates, and installed placement are ready for a search.
private boolean established;
// Number of sections currently installed in the lattice, not total attached sections.
int installedCount;
// Two reusable destination buffers for VisibilitySnapshot, alternated every search. Copying into a
// recycled buffer avoids allocating a full visitState clone per frame. Two are needed rather than one
// so a search never overwrites the buffer backing the previously returned snapshot, which a reader on
// another thread may still hold: search k writes buffer[k % 2] while buffer[(k-1) % 2] stays readable.
private final long[][] snapshotBuffers = new long[2][];
private int snapshotParity;
public SectionLattice(int minSectionY, int maxSectionY) {
this.minSectionY = minSectionY;
this.maxSectionY = maxSectionY;
this.baseY = minSectionY - 1;
this.dimY = (maxSectionY - minSectionY) + 2;
this.culler = new OcclusionCuller(this, minSectionY, maxSectionY);
if (this.dimY > MAX_DIM) {
throw new IllegalStateException("World height " + this.dimY + " exceeds occlusion lattice limit " + MAX_DIM);
}
}
/**
* Returns the attached section at a world position, regardless of whether
* it currently has an installed lattice slot.
*
* @return the authoritative section at the position, or {@code null} if
* no section is attached
*/
@Nullable
public RenderSection getRenderSection(int x, int y, int z) {
return this.sections.get(PositionUtil.packSection(x, y, z));
}
/**
* Attach a section to the authoritative collection and install it when
* the lattice has been allocated and the section lies in its interior.
* Attaching before the first window allocation is valid; the section will
* be installed by the next allocation or rebase that covers it.
*/
public void attach(RenderSection section) {
var key = section.positionAsLong();
if (this.sections.get(key) != null) {
throw new IllegalStateException("Section already attached to lattice: " + section);
}
this.sections.put(key, section);
this.install(section);
}
/**
* Detach a section from the authoritative collection and remove its
* lattice slot, if it is currently installed.
*/
public void detach(RenderSection section) {
var key = section.positionAsLong();
RenderSection removed = this.sections.remove(key);
if (removed == null) {
throw new IllegalStateException("Section not attached to lattice: " + section);
}
this.uninstall(section);
}
/**
* Mirror a section's full packed metadata word into its slot.
*
* @return true if the change altered the graph search's output (see {@link PackedSectionMetadata#GRAPH_INPUT_MASK})
* and a re-search is therefore warranted
*/
public boolean updateSectionMetadata(int x, int y, int z, long packedMetadata) {
int idx = this.installedIndex(x, y, z);
if (idx < 0) {
// Not installed (unloaded, no window yet, or outside the current
// window): it is not traversed, and its metadata is read fresh
// from the section when it is eventually installed.
return false;
}
long previous = this.sectionMeta[idx];
this.sectionMeta[idx] = packedMetadata;
return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0;
}
/**
* Returns the section installed at a lattice index.
*
* <p>Used by deferred visitor replay to resolve the section lazily; the
* caller must provide an index belonging to an installed cell.
*/
public RenderSection sectionAt(int latticeIndex) {
return this.latticeSection[latticeIndex];
}
/**
* Encodes a frame for the ordered visit gate. The low byte is reserved for
* incoming direction bits, so the 32-bit frame occupies bits 8..39.
*/
static long frameStamp(int frame) {
return (frame & 0xFFFFFFFFL) << FRAME_SHIFT;
}
/**
* Self-contained view of the lattice's visibility state, safe to query from
* a thread other than the one mutating the lattice.
*
* <p>{@link SectionLattice#findVisible} runs asynchronously and mutates the
* live lattice while another thread queries section visibility. Rather than
* read the live arrays across that boundary, a search returns a snapshot: a
* copy of {@code visitState} plus the window geometry that indexes it. The
* snapshot's array is not the live lattice, so a running search's mutations
* cannot race a query against it.
*
* <p>To avoid a per-frame allocation, {@code visitState} is a buffer
* recycled from {@code snapshotBuffers} rather than a fresh clone. The
* lattice alternates between two buffers so the buffer a new search
* overwrites is never the one backing the currently published snapshot; see
* {@link SectionLattice#snapshot()}.
*
* @param visitState the search's per-cell visit state; a recycled buffer
* that stays valid until the search two generations later
* overwrites it
*/
public record VisibilitySnapshot(long[] visitState, int baseX, int baseY, int baseZ,
int dimX, int dimY, int dimZ) {
/** A snapshot with no window, reporting every section as not visible. */
public static final VisibilitySnapshot EMPTY =
new VisibilitySnapshot(new long[0], 0, 0, 0, 0, 0, 0);
/**
* Tests whether the section at a world position was marked visible in or
* after the requested frame. Positions outside the captured window, or
* never visited, are treated as never-visible.
*/
public boolean isSectionVisible(int x, int y, int z, int minVisibleFrame) {
int lx = x - this.baseX;
int ly = y - this.baseY;
int lz = z - this.baseZ;
// Same interior test as SectionLattice.indexOf: only cells strictly
// inside the sentinel border can hold a section, so anything outside
// it (including an empty snapshot) is never visible.
if (lx < 1 || lx > this.dimX - 2
|| ly < 1 || ly > this.dimY - 2
|| lz < 1 || lz > this.dimZ - 2) {
return false;
}
int idx = (lx * this.dimZ + lz) * this.dimY + ly;
// The frame in which the slot was last marked visible by the search. Narrowing (int) after the logical
// shift recovers the 32-bit frame; an unvisited or empty cell holds INITIAL/SENTINEL, which decode to a
// value below any real frame and are therefore treated as never-visible.
return (int) (this.visitState[idx] >>> FRAME_SHIFT) >= minVisibleFrame;
}
}
private VisibilitySnapshot snapshot() {
if (this.visitState == null) {
return VisibilitySnapshot.EMPTY;
}
int parity = this.snapshotParity;
this.snapshotParity ^= 1;
long[] dst = this.snapshotBuffers[parity];
if (dst == null || dst.length != this.visitState.length) {
dst = new long[this.visitState.length];
this.snapshotBuffers[parity] = dst;
}
System.arraycopy(this.visitState, 0, dst, 0, dst.length);
return new VisibilitySnapshot(dst, this.baseX, this.baseY, this.baseZ,
this.dimX, this.dimY, this.dimZ);
}
/**
* Returns the actual installed slot at a world position.
*
* <p>This is intentionally stricter than {@link #indexOf}: {@code indexOf}
* computes a possible interior slot, whereas this method also verifies
* that a section is attached and installed there.
*/
private int installedIndex(int x, int y, int z) {
if (this.visitState == null) {
return -1;
}
int idx = this.indexOf(x, y, z);
return idx >= 0 && this.latticeSection[idx] != null ? idx : -1;
}
/**
* Ensure the lattice window covers the search radius around the camera.
*
* <p>The traversal can reach {@code radius} sections from the camera and
* then inspect one more neighbour, so every section in that reach must be
* in the installable interior rather than merely in the backing array.
* The extra cell is what makes the border safe for unchecked neighbour
* access. {@link #SLACK} leaves room for camera movement before another
* rebase is needed.
*
* <p>The window is allocated lazily and grows when necessary. A first
* allocation or resize invalidates the old coordinates and requires a full
* rebuild. Otherwise, when the camera makes the current window invalid,
* the existing window is typically slid to the centered base: overlapping cells are
* retained and only the newly exposed band is resolved through the
* authoritative section map.
*
* <p>Call this on the render thread before dispatching a search. The
* asynchronous search must not observe allocation, rebasing, attachment,
* detachment, or metadata updates while it is running.
*/
public void ensureWindowCovers(Vector3ic cameraSectionPos, float searchDistance) {
int radius = MathUtil.mojfloor(searchDistance / 16.0f);
int neededDimXZ = 2 * (radius + SLACK) + 3;
if (this.visitState == null || neededDimXZ > this.dimX) {
this.allocate(neededDimXZ);
}
int lx = cameraSectionPos.x() - this.baseX;
int lz = cameraSectionPos.z() - this.baseZ;
// Include the neighbour of the outermost section the traversal can visit.
int reach = radius + 1;
boolean valid = this.established
&& lx - reach >= 1 && lx + reach <= this.dimX - 2
&& lz - reach >= 1 && lz + reach <= this.dimZ - 2;
if (!valid) {
int newBaseX = cameraSectionPos.x() - this.dimX / 2;
int newBaseZ = cameraSectionPos.z() - this.dimZ / 2;
if (this.established) {
// The current window is valid to slide from: reuse its retained
// contents and only resolve the newly exposed cells.
this.shiftRebase(newBaseX, newBaseZ);
} else {
// Fresh or resized arrays have no reusable contents.
this.rebase(newBaseX, newBaseZ);
}
this.established = true;
}
}
/**
* Run the visibility search over the currently installed lattice cells.
* The caller must have completed {@link #ensureWindowCovers} and must keep
* lattice structure and metadata stable until this method returns.
*
* @return a snapshot of the visit state this search produced
*/
public VisibilitySnapshot findVisible(OcclusionCuller.Visitor visitor,
Viewport viewport,
float searchDistance,
int numRegions,
boolean useOcclusionCulling,
int frame) {
this.culler.findVisible(visitor, viewport, searchDistance, numRegions, useOcclusionCulling, frame);
return this.snapshot();
}
private void allocate(int newDimXZ) {
long slotsLong = (long) newDimXZ * newDimXZ * this.dimY;
if (newDimXZ > MAX_DIM || slotsLong >= MAX_LATTICE_SLOTS) {
throw new IllegalStateException("Occlusion lattice window too large (dimXZ=" + newDimXZ
+ ", slots=" + slotsLong + "); this render distance is not supported");
}
this.dimX = newDimXZ;
this.dimZ = newDimXZ;
this.strideZ = this.dimY;
this.strideX = this.dimY * this.dimZ;
for (int dir = 0; dir < GraphDirection.COUNT; dir++) {
this.delta[dir] = GraphDirection.x(dir) * this.strideX
+ GraphDirection.z(dir) * this.strideZ
+ GraphDirection.y(dir);
}
int slots = (int) slotsLong;
this.visitState = new long[slots];
this.sectionMeta = new long[slots];
this.regionOfCell = new int[slots];
this.latticeSection = new RenderSection[slots];
// Existing coordinates are no longer valid after resizing; the next
// ensureWindowCovers must rebase and reinstall every attached section.
this.established = false;
}
/**
* Rebuilds the lattice from scratch after allocation, resizing, or a
* non-overlapping camera jump.
*/
private void rebase(int newBaseX, int newBaseZ) {
Arrays.fill(this.visitState, SENTINEL);
Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL);
Arrays.fill(this.regionOfCell, -1);
Arrays.fill(this.latticeSection, null);
this.baseX = newBaseX;
this.baseZ = newBaseZ;
this.installedCount = 0;
for (RenderSection section : this.sections.values()) {
this.install(section);
}
}
/**
* Slide the existing window to a new X/Z origin without rebuilding it.
*
* <p>{@code dX} and {@code dZ} are the changes in world-space base
* coordinates.
*
* <p>Before overwriting the old array cells, {@link #dropLeaving} removes
* the installed-count contribution of cells outside that intersection.
* After the move, {@link #fillNewBand} clears the cells that entered the
* window and installs only sections found in the authoritative map. Thus
* the map is consulted only for the exposed band, rather than once for
* every attached section as in {@link #rebase}.
*
* <p>When the old and new interiors do not intersect, there is no useful
* data to preserve and this method delegates to {@link #rebase}.
*/
private void shiftRebase(int newBaseX, int newBaseZ) {
int dX = newBaseX - this.baseX;
int dZ = newBaseZ - this.baseZ;
int interiorXHi = this.dimX - 2;
int interiorZHi = this.dimZ - 2;
int xLo = Math.max(1, 1 - dX);
int xHi = Math.min(interiorXHi, interiorXHi - dX);
int zLo = Math.max(1, 1 - dZ);
int zHi = Math.min(interiorZHi, interiorZHi - dZ);
if (xLo > xHi || zLo > zHi) {
// No overlap: sliding would move nothing, so reinstall wholesale.
this.rebase(newBaseX, newBaseZ);
return;
}
this.dropLeaving(xLo + dX, xHi + dX, zLo + dZ, zHi + dZ);
if (dZ == 0) {
this.shiftContentsXOnly(dX, xLo, xHi);
} else {
this.shiftContents(dX, dZ, xLo, xHi, zLo, zHi);
}
// The arrays now describe cells relative to the new origin.
this.baseX = newBaseX;
this.baseZ = newBaseZ;
this.fillNewBand(xLo, xHi, zLo, zHi);
}
/**
* Move retained contents for a pure X shift.
*
* <p>Whole X planes (including their permanent sentinel rows) translate
* uniformly by {@code dX}, so the retained planes form one contiguous
* range. A single {@link System#arraycopy} per parallel array performs the
* overlapping move safely.
*/
private void shiftContentsXOnly(int dX, int xLo, int xHi) {
int destOff = xLo * this.strideX;
int srcOff = (xLo + dX) * this.strideX;
int len = (xHi - xLo + 1) * this.strideX;
System.arraycopy(this.visitState, srcOff, this.visitState, destOff, len);
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len);
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len);
}
/**
* Move retained contents for a shift that includes Z.
*
* <p>A Z shift cannot cross an X-plane boundary, so it moves one
* contiguous {@code Z/Y} block per retained X-plane. The loop direction
* keeps a plane's source intact until it has been copied;
* {@link System#arraycopy} handles overlap within that block.
*/
private void shiftContents(int dX, int dZ, int xLo, int xHi, int zLo, int zHi) {
// Each Z within [zLo, zHi] contributes a full contiguous Y run, so the
// whole per-plane block is one run. The Y sentinels carried along are
// copied from equivalent source sentinels and stay empty.
int runLen = (zHi - zLo + 1) * this.strideZ;
// When data moves to lower indices (dX > 0) copy ascending so a source
// plane is read before a later write can reach it; descend otherwise.
int first = dX < 0 ? xHi : xLo;
int last = dX < 0 ? xLo : xHi;
int step = dX < 0 ? -1 : 1;
for (int lx = first; lx != last + step; lx += step) {
int destOff = lx * this.strideX + zLo * this.strideZ;
int srcOff = (lx + dX) * this.strideX + (zLo + dZ) * this.strideZ;
System.arraycopy(this.visitState, srcOff, this.visitState, destOff, runLen);
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen);
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen);
}
}
/**
* Account for cells that leave the window before their slots are reused.
*
* <p>The source rectangle is the old interior that supplies the retained
* destination rectangle. Every installed cell outside it loses its slot,
* so its contribution to {@link #installedCount} is decremented here.
* Those sections remain in {@link #sections}; their stale array entries
* are subsequently overwritten by {@link #shiftContentsXOnly} or
* {@link #shiftContents}, then cleared by {@link #fillNewBand}.
*
* <p>Because the old and new windows differ by a translation, the retained
* source rectangle touches an edge in each shifted axis. Its complement is
* therefore two non-overlapping rectangles: an X-only strip and a Z-only
* strip. Iterating those rectangles avoids testing rectangle membership for
* every cell.
*/
private void dropLeaving(int srcXLo, int srcXHi, int srcZLo, int srcZHi) {
int interiorXHi = this.dimX - 2;
int interiorZHi = this.dimZ - 2;
int interiorYHi = this.dimY - 2;
int xBandLo = srcXLo == 1 ? srcXHi + 1 : 1;
int xBandHi = srcXLo == 1 ? interiorXHi : srcXLo - 1;
int zBandLo = srcZLo == 1 ? srcZHi + 1 : 1;
int zBandHi = srcZLo == 1 ? interiorZHi : srcZLo - 1;
this.dropLeavingRectangle(xBandLo, xBandHi, 1, interiorZHi, interiorYHi);
this.dropLeavingRectangle(srcXLo, srcXHi, zBandLo, zBandHi, interiorYHi);
}
private void dropLeavingRectangle(int xLo, int xHi, int zLo, int zHi, int interiorYHi) {
for (int lx = xLo; lx <= xHi; lx++) {
for (int lz = zLo; lz <= zHi; lz++) {
int col = lx * this.strideX + lz * this.strideZ;
for (int ly = 1; ly <= interiorYHi; ly++) {
if (this.latticeSection[col + ly] != null) {
this.installedCount--;
}
}
}
}
}
/**
* Clear and repopulate the L-shaped band of cells that entered the window.
*
* <p>As with {@link #dropLeaving}, the band is visited as two
* non-overlapping rectangles: the X-only strip outside the retained X
* range, followed by the Z-only strip inside the retained X range.
*/
private void fillNewBand(int keepXLo, int keepXHi, int keepZLo, int keepZHi) {
int interiorXHi = this.dimX - 2;
int interiorZHi = this.dimZ - 2;
int interiorYHi = this.dimY - 2;
int xBandLo = keepXLo == 1 ? keepXHi + 1 : 1;
int xBandHi = keepXLo == 1 ? interiorXHi : keepXLo - 1;
int zBandLo = keepZLo == 1 ? keepZHi + 1 : 1;
int zBandHi = keepZLo == 1 ? interiorZHi : keepZLo - 1;
this.fillBandRectangle(xBandLo, xBandHi, 1, interiorZHi, interiorYHi);
this.fillBandRectangle(keepXLo, keepXHi, zBandLo, zBandHi, interiorYHi);
}
private void fillBandRectangle(int xLo, int xHi, int zLo, int zHi, int interiorYHi) {
for (int lx = xLo; lx <= xHi; lx++) {
int worldX = this.baseX + lx;
for (int lz = zLo; lz <= zHi; lz++) {
int worldZ = this.baseZ + lz;
int col = lx * this.strideX + lz * this.strideZ;
for (int ly = 1; ly <= interiorYHi; ly++) {
int idx = col + ly;
this.visitState[idx] = SENTINEL;
this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null;
RenderSection section = this.sections.get(
PositionUtil.packSection(worldX, this.baseY + ly, worldZ));
if (section != null) {
this.install(section);
}
}
}
}
}
/**
* Computes the potential lattice slot for a world position.
*
* @return the slot if the position is in the installable interior, or
* {@code -1} if it is outside the window, in the sentinel border,
* or outside the supported world-height range. This method does
* not test whether a section is actually installed at the slot.
*/
int indexOf(int x, int y, int z) {
int lx = x - this.baseX;
int ly = y - this.baseY;
int lz = z - this.baseZ;
if (lx < 1 || lx > this.dimX - 2
|| ly < 1 || ly > this.dimY - 2
|| lz < 1 || lz > this.dimZ - 2) {
return -1;
}
return (lx * this.dimZ + lz) * this.dimY + ly;
}
/**
* Packs a world position's local coordinates into 10 bits per axis for
* the traversal queue. The caller must pass a position in this lattice's
* addressable window; {@code MAX_DIM} guarantees that each coordinate fits
* in its 10-bit field, while {@code MAX_LATTICE_SLOTS} limits the total
* backing-array size.
*/
int packXyz(int x, int y, int z) {
return ((x - this.baseX) << (2 * XYZ_SHIFT)) | ((y - this.baseY) << XYZ_SHIFT) | (z - this.baseZ);
}
// Install only into the interior. An attached section outside the current
// window remains in sections and is picked up by a later rebase.
private void install(RenderSection section) {
if (this.visitState == null) {
return;
}
int idx = this.indexOf(section.getChunkX(), section.getChunkY(), section.getChunkZ());
if (idx < 0) {
return;
}
this.visitState[idx] = INITIAL;
this.latticeSection[idx] = section;
this.regionOfCell[idx] = section.getRegion().getId();
this.sectionMeta[idx] = section.getPackedMetadata();
this.installedCount++;
}
// Remove the section's complete parallel-array entry. Write SENTINEL
// first so traversal can never treat the remaining fields as live.
private void uninstall(RenderSection section) {
int idx = this.installedIndex(section.getChunkX(), section.getChunkY(), section.getChunkZ());
if (idx < 0) {
return;
}
this.visitState[idx] = SENTINEL;
this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null;
this.installedCount--;
}
}
@@ -24,13 +24,17 @@ public class RenderRegion {
public static final int REGION_HEIGHT = 4; public static final int REGION_HEIGHT = 4;
public static final int REGION_LENGTH = 8; public static final int REGION_LENGTH = 8;
public static final int REGION_BLOCK_WIDTH = REGION_WIDTH * 16;
public static final int REGION_BLOCK_HEIGHT = REGION_HEIGHT * 16;
public static final int REGION_BLOCK_LENGTH = REGION_LENGTH * 16;
private static final int REGION_WIDTH_M = RenderRegion.REGION_WIDTH - 1; private static final int REGION_WIDTH_M = RenderRegion.REGION_WIDTH - 1;
private static final int REGION_HEIGHT_M = RenderRegion.REGION_HEIGHT - 1; private static final int REGION_HEIGHT_M = RenderRegion.REGION_HEIGHT - 1;
private static final int REGION_LENGTH_M = RenderRegion.REGION_LENGTH - 1; private static final int REGION_LENGTH_M = RenderRegion.REGION_LENGTH - 1;
protected static final int REGION_WIDTH_SH = Integer.bitCount(REGION_WIDTH_M); public static final int REGION_WIDTH_SH = Integer.bitCount(REGION_WIDTH_M);
protected static final int REGION_HEIGHT_SH = Integer.bitCount(REGION_HEIGHT_M); public static final int REGION_HEIGHT_SH = Integer.bitCount(REGION_HEIGHT_M);
protected static final int REGION_LENGTH_SH = Integer.bitCount(REGION_LENGTH_M); public static final int REGION_LENGTH_SH = Integer.bitCount(REGION_LENGTH_M);
public static final int REGION_SIZE = REGION_WIDTH * REGION_HEIGHT * REGION_LENGTH; public static final int REGION_SIZE = REGION_WIDTH * REGION_HEIGHT * REGION_LENGTH;
@@ -58,6 +58,10 @@ public final class Viewport {
); );
} }
public int intersectCameraRelativeBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ);
}
public CameraTransform getTransform() { public CameraTransform getTransform() {
return this.transform; return this.transform;
} }
@@ -1,5 +1,22 @@
package org.embeddedt.embeddium.impl.render.viewport.frustum; package org.embeddedt.embeddium.impl.render.viewport.frustum;
public interface Frustum { public interface Frustum {
/**
* Returned when the box is known to be fully inside the frustum.
*/
int FULLY_INSIDE = 0;
/**
* Returned when the box is at least partially within the frustum.
*/
int PARTIALLY_INSIDE = 1;
/**
* Returned when the box is outside the frustum.
*/
int OUTSIDE = 2;
boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ);
default int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return testAab(minX, minY, minZ, maxX, maxY, maxZ) ? PARTIALLY_INSIDE : OUTSIDE;
}
} }
@@ -13,4 +13,13 @@ public final class SimpleFrustum implements Frustum {
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return this.frustum.testAab(minX, minY, minZ, maxX, maxY, maxZ); return this.frustum.testAab(minX, minY, minZ, maxX, maxY, maxZ);
} }
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return switch (this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ)) {
case FrustumIntersection.INSIDE -> Frustum.FULLY_INSIDE;
case FrustumIntersection.INTERSECT -> Frustum.PARTIALLY_INSIDE;
default -> Frustum.OUTSIDE;
};
}
} }
@@ -54,6 +54,16 @@ public class BoxCuller {
return maxZ < -this.maxDistance || minZ > this.maxDistance; return maxZ < -this.maxDistance || minZ > this.maxDistance;
} }
/**
* Camera-relative variant of a "fully inside" test: returns true only when the entire box lies within the
* allowed distance bounds on every axis, meaning no sub-box of it could ever be culled.
*/
public boolean isFullyInsideSodium(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return minX >= -this.maxDistance && maxX <= this.maxDistance
&& minY >= -this.maxDistance && maxY <= this.maxDistance
&& minZ >= -this.maxDistance && maxZ <= this.maxDistance;
}
@Override @Override
public String toString() { public String toString() {
return "Box Culling active; max distance " + maxDistance; return "Box Culling active; max distance " + maxDistance;
@@ -33,4 +33,9 @@ public class CullEverythingFrustum extends Frustum implements ViewportProvider,
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return false; return false;
} }
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return OUTSIDE;
}
} }
@@ -387,6 +387,53 @@ public class AdvancedShadowCullingFrustum extends Frustum implements ViewportPro
return (boxCuller == null || !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) && this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0; return (boxCuller == null || !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) && this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0;
} }
/**
* Tri-state variant of {@link #checkCornerVisibility}, ported from JOML's {@code FrustumIntersection#intersectAab}.
* Unlike {@link #checkCornerVisibility}, this additionally tests the near corner against each plane so that boxes
* lying entirely within the frustum can be reported as fully inside.
*/
protected int intersectCorners(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
boolean inside = true;
for (int i = 0; i < planeCount; ++i) {
Vector4f plane = this.planes[i];
float px = plane.x();
float py = plane.y();
float pz = plane.z();
float pw = plane.w();
// If the far corner (the one furthest along the plane normal) is behind the plane, the box is fully outside.
if (Math.fma(px, px < 0 ? minX : maxX, Math.fma(py, py < 0 ? minY : maxY, pz * (pz < 0 ? minZ : maxZ))) < -pw) {
return OUTSIDE;
}
// If the near corner is behind the plane, the box straddles it and can be at most partially inside.
if (Math.fma(px, px < 0 ? maxX : minX, Math.fma(py, py < 0 ? maxY : minY, pz * (pz < 0 ? maxZ : minZ))) < -pw) {
inside = false;
}
}
return inside ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller != null && boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
int result = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
// A box can only be fully inside if it is also fully within the box culler's bounds; otherwise a sub-box could
// be culled and the region must be treated as partial.
if (result == FULLY_INSIDE && boxCuller != null
&& !boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
return PARTIALLY_INSIDE;
}
return result;
}
private final Vector3d position = new Vector3d(); private final Vector3d position = new Vector3d();
@Override @Override
@@ -58,4 +58,29 @@ public class ReversedAdvancedShadowCullingFrustum extends AdvancedShadowCullingF
return this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0; return this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0;
} }
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (distanceCuller != null && distanceCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
if (boxCuller != null && !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
// The box overlaps the kept voxel region, so it is visible. It is only fully inside when the entire box
// stays within both the voxel region and the outer distance bound, so no sub-box could be culled.
boolean fullyInside = boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)
&& (distanceCuller == null || distanceCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ));
return fullyInside ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
// Outside the voxel region: fall back to the shadow planes, still bounded by the distance culler.
int result = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
if (result == FULLY_INSIDE && distanceCuller != null
&& !distanceCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
return PARTIALLY_INSIDE;
}
return result;
}
} }
@@ -50,4 +50,13 @@ public class BoxCullingFrustum extends Frustum implements ViewportProvider, org.
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ); return !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ);
} }
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
return boxCuller.isFullyInsideSodium(minX, minY, minZ, maxX, maxY, maxZ) ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
} }
@@ -37,4 +37,9 @@ public class NonCullingFrustum extends Frustum implements ViewportProvider, org.
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return true; return true;
} }
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return FULLY_INSIDE;
}
} }