Smarter translucency sorting #42

Merged
embeddedt merged 24 commits from rdh/celeritas:ts into stonecutter 2026-09-16 11:25:42 -04:00
4 changed files with 255 additions and 42 deletions
Showing only changes of commit 8627794f2a - Show all commits

No files matched your search

@@ -201,15 +201,6 @@ public class RenderSection extends AbstractSection {
this.treeSorted = !sortStates.isEmpty() && sortStates.values().stream().allMatch(state -> state instanceof PartitionTree); this.treeSorted = !sortStates.isEmpty() && sortStates.values().stream().allMatch(state -> state instanceof PartitionTree);
} }
public boolean crossesAnyCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) {
for (SortState.Resortable state : this.translucencySortStates.values()) {
if (((PartitionTree) state).crossesCutPlane(lastX, lastY, lastZ, camX, camY, camZ)) {
return true;
}
}
return false;
}
public @Nullable CancellationToken getBuildCancellationToken() { public @Nullable CancellationToken getBuildCancellationToken() {
return this.buildCancellationToken; return this.buildCancellationToken;
} }
@@ -38,6 +38,8 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum; import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum;
import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator;
import org.embeddedt.embeddium.impl.render.chunk.sorting.CutPlaneIndex;
import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree;
import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState;
import org.embeddedt.embeddium.impl.util.suppliers.ExpiringSupplier; import org.embeddedt.embeddium.impl.util.suppliers.ExpiringSupplier;
import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.MustBeInvokedByOverriders;
@@ -82,9 +84,16 @@ public abstract class RenderSectionManager {
private final int renderDistance; private final int renderDistance;
protected @Nullable Vector3ic lastCameraPosition; /** {@link #cameraPosition}, rounded down to block coordinates */
protected @Nullable Vector3ic cameraBlockPosition;
protected Vector3d cameraPosition = new Vector3d(); protected Vector3d cameraPosition = new Vector3d();
/** last frame's exact camera position */
protected @Nullable Vector3d previousCameraPosition;
private final CutPlaneIndex<RenderSection> cutPlaneIndex = new CutPlaneIndex<>();
@Getter @Getter
private final RenderPassConfiguration<?> renderPassConfiguration; private final RenderPassConfiguration<?> renderPassConfiguration;
@@ -199,7 +208,9 @@ public abstract class RenderSectionManager {
* per-frame camera bookkeeping. * per-frame camera bookkeeping.
*/ */
public void update(Viewport positionedViewport, int frame, boolean spectator) { public void update(Viewport positionedViewport, int frame, boolean spectator) {
this.updateCameraPosition(positionedViewport); if (!this.shadowPassRanThisFrame) {
this.updateCameraPosition(positionedViewport);
}
if (this.shadowPassRanThisFrame) { if (this.shadowPassRanThisFrame) {
// The shadow pass searched for this frame if the graph was dirty then. Any needsUpdate raised by // The shadow pass searched for this frame if the graph was dirty then. Any needsUpdate raised by
@@ -239,7 +250,11 @@ public abstract class RenderSectionManager {
} }
private void updateCameraPosition(Viewport positionedViewport) { private void updateCameraPosition(Viewport positionedViewport) {
this.lastCameraPosition = positionedViewport.getBlockCoord(); if (this.cameraBlockPosition != null) {
this.previousCameraPosition = this.cameraPosition;
}
this.cameraBlockPosition = positionedViewport.getBlockCoord();
var transform = positionedViewport.getTransform(); var transform = positionedViewport.getTransform();
this.cameraPosition = new Vector3d(transform.x, transform.y, transform.z); this.cameraPosition = new Vector3d(transform.x, transform.y, transform.z);
} }
@@ -257,7 +272,7 @@ public abstract class RenderSectionManager {
} }
private void checkTranslucencyChange() { private void checkTranslucencyChange() {
if(lastCameraPosition == null) if(cameraBlockPosition == null)
return; return;
int camSectionX = PositionUtil.posToSectionCoord(cameraPosition.x); int camSectionX = PositionUtil.posToSectionCoord(cameraPosition.x);
@@ -265,6 +280,7 @@ public abstract class RenderSectionManager {
int camSectionZ = PositionUtil.posToSectionCoord(cameraPosition.z); int camSectionZ = PositionUtil.posToSectionCoord(cameraPosition.z);
this.scheduleTranslucencyUpdates(camSectionX, camSectionY, camSectionZ); this.scheduleTranslucencyUpdates(camSectionX, camSectionY, camSectionZ);
this.scheduleTreeSortedUpdates();
} }
private void scheduleTranslucencyUpdates(int camSectionX, int camSectionY, int camSectionZ) { private void scheduleTranslucencyUpdates(int camSectionX, int camSectionY, int camSectionZ) {
@@ -288,8 +304,8 @@ public abstract class RenderSectionManager {
while (sectionIterator.hasNext()) { while (sectionIterator.hasNext()) {
var section = region.getSection(sectionIterator.nextByteAsInt()); var section = region.getSection(sectionIterator.nextByteAsInt());
if (section == null || !section.isNeedsDynamicTranslucencySorting()) { // tree-sorted sections are retriggered by scheduleTreeSortedUpdates() instead
// Sections without sortable translucent data are not relevant if (section == null || !section.isNeedsDynamicTranslucencySorting() || section.isTreeSorted()) {
continue; continue;
} }
@@ -300,33 +316,22 @@ public abstract class RenderSectionManager {
continue; continue;
} }
if (section.isTreeSorted()) { double dx = cameraPosition.x - section.lastCameraX;
boolean crossed = section.crossesAnyCutPlane( double dy = cameraPosition.y - section.lastCameraY;
section.lastCameraX - section.getOriginX(), section.lastCameraY - section.getOriginY(), section.lastCameraZ - section.getOriginZ(), double dz = cameraPosition.z - section.lastCameraZ;
cameraPosition.x - section.getOriginX(), cameraPosition.y - section.getOriginY(), cameraPosition.z - section.getOriginZ() double camDelta = (dx * dx) + (dy * dy) + (dz * dz);
);
if (!crossed) { if (camDelta < 1) {
continue; // Didn't move enough, ignore
} continue;
} else { }
double dx = cameraPosition.x - section.lastCameraX;
double dy = cameraPosition.y - section.lastCameraY;
double dz = cameraPosition.z - section.lastCameraZ;
double camDelta = (dx * dx) + (dy * dy) + (dz * dz);
if (camDelta < 1) { boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) ||
// Didn't move enough, ignore camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) ||
continue; camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ);
}
boolean cameraChangedSection = camSectionX != PositionUtil.posToSectionCoord(section.lastCameraX) || if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) {
camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || continue;
camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ);
if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) {
continue;
}
} }
section.setPendingUpdate(update); section.setPendingUpdate(update);
@@ -340,6 +345,33 @@ public abstract class RenderSectionManager {
} }
} }
/** Resorts tree-sorted sections whose cut planes this frame's movement crossed, visible or not */
private void scheduleTreeSortedUpdates() {
if (this.previousCameraPosition == null || this.cutPlaneIndex.size() == 0) {
return;
}
var rebuildLists = this.getCurrentRenderListManager().getRebuildLists().byUpdateType();
var allowImportant = allowImportantRebuilds();
this.cutPlaneIndex.query(
this.previousCameraPosition.x, this.previousCameraPosition.y, this.previousCameraPosition.z,
this.cameraPosition.x, this.cameraPosition.y, this.cameraPosition.z,
section -> {
ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(),
(allowImportant && this.shouldPrioritizeRebuild(section)) ? ChunkUpdateType.IMPORTANT_SORT : ChunkUpdateType.SORT);
if (update == null) {
// We wouldn't be able to resort this section anyway
return;
}
section.setPendingUpdate(update);
rebuildLists.get(update).add(section);
}
);
}
/** /**
* {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as * {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as
* possible per frame} * possible per frame}
@@ -440,6 +472,8 @@ public abstract class RenderSectionManager {
this.sectionMetricsTracker.removeSection(section); this.sectionMetricsTracker.removeSection(section);
this.cutPlaneIndex.remove(section);
section.delete(); section.delete();
this.markGraphDirty(); this.markGraphDirty();
@@ -632,6 +666,18 @@ public abstract class RenderSectionManager {
render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex); render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex);
if (render.isTreeSorted()) {
List<PartitionTree> trees = new ArrayList<>(sortStates.size());
for (var state : sortStates.values()) {
trees.add((PartitionTree) state);
}
this.cutPlaneIndex.put(render, PartitionTree.mergeCutPlanes(trees), render.getOriginX(), render.getOriginY(), render.getOriginZ());
} else {
// a rebuild that is no longer tree-sorted must drop its stale planes
this.cutPlaneIndex.remove(render);
}
render.lastCameraX = this.cameraPosition.x; render.lastCameraX = this.cameraPosition.x;
render.lastCameraY = this.cameraPosition.y; render.lastCameraY = this.cameraPosition.y;
render.lastCameraZ = this.cameraPosition.z; render.lastCameraZ = this.cameraPosition.z;
@@ -904,7 +950,7 @@ public abstract class RenderSectionManager {
private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f); private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f);
private boolean shouldPrioritizeRebuild(RenderSection section) { private boolean shouldPrioritizeRebuild(RenderSection section) {
return this.lastCameraPosition != null && section.getSquaredDistanceFromBlockCenter(this.lastCameraPosition.x(), this.lastCameraPosition.y(), this.lastCameraPosition.z()) < NEARBY_REBUILD_DISTANCE; return this.cameraBlockPosition != null && section.getSquaredDistanceFromBlockCenter(this.cameraBlockPosition.x(), this.cameraBlockPosition.y(), this.cameraBlockPosition.z()) < NEARBY_REBUILD_DISTANCE;
} }
/** /**
@@ -1041,13 +1087,14 @@ public abstract class RenderSectionManager {
var rebuildLists = this.getCurrentRenderListManager().getRebuildLists(); var rebuildLists = this.getCurrentRenderListManager().getRebuildLists();
list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d", list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d I=%03d",
this.buildResults.size(), this.buildResults.size(),
rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD),
rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD),
rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD), rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD),
rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT),
rebuildLists.getUpdateCount(ChunkUpdateType.SORT) rebuildLists.getUpdateCount(ChunkUpdateType.SORT),
this.cutPlaneIndex.size()
)); ));
var debugStats = renderListManager.getDebugStatistics(); var debugStats = renderListManager.getDebugStatistics();
@@ -0,0 +1,155 @@
package org.embeddedt.embeddium.impl.render.chunk.sorting;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import java.util.function.Consumer;
public final class CutPlaneIndex<T> {
/** movements larger than this many buckets rescan every owner instead of walking the buckets */
static final int MAX_BUCKET_SPAN = 64;
private record Registration<T>(float[][] cuts, int[] origin, long[][] buckets) {
}
@SuppressWarnings("unchecked")
private final Long2ObjectOpenHashMap<ReferenceOpenHashSet<T>>[] bucketsByAxis = new Long2ObjectOpenHashMap[] {
new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>()
};
private final Reference2ObjectOpenHashMap<T, Registration<T>> registrations = new Reference2ObjectOpenHashMap<>();
private final ReferenceOpenHashSet<T> reported = new ReferenceOpenHashSet<>();
public void put(T owner, float[][] cutsByAxis, int originX, int originY, int originZ) {
remove(owner);
if (cutsByAxis[0].length == 0 && cutsByAxis[1].length == 0 && cutsByAxis[2].length == 0) {
// a leaf's order can never change, so it's not worth indexing
return;
}
int[] origin = { originX, originY, originZ };
long[][] buckets = new long[3][];
for (int axis = 0; axis < 3; axis++) {
LongArrayList keys = new LongArrayList();
long lastKey = 0;
boolean first = true;
// cutsByAxis[axis] is sorted, so equal bucket keys are adjacent
for (float cut : cutsByAxis[axis]) {
long key = bucketKey(cut, origin[axis]);
if (first || key != lastKey) {
keys.add(key);
lastKey = key;
first = false;
}
}
buckets[axis] = keys.toLongArray();
for (long key : buckets[axis]) {
this.bucketsByAxis[axis].computeIfAbsent(key, k -> new ReferenceOpenHashSet<>()).add(owner);
}
}
this.registrations.put(owner, new Registration<>(cutsByAxis, origin, buckets));
}
public void remove(T owner) {
Registration<T> registration = this.registrations.remove(owner);
if (registration == null) {
return;
}
for (int axis = 0; axis < 3; axis++) {
var map = this.bucketsByAxis[axis];
for (long key : registration.buckets[axis]) {
ReferenceOpenHashSet<T> owners = map.get(key);
if (owners == null) continue;
owners.remove(owner);
if (owners.isEmpty()) {
map.remove(key);
}
}
}
}
public void query(double fromX, double fromY, double fromZ, double toX, double toY, double toZ, Consumer<T> out) {
if (this.registrations.isEmpty()) {
return;
}
try {
queryAxis(0, fromX, toX, out);
queryAxis(1, fromY, toY, out);
queryAxis(2, fromZ, toZ, out);
} finally {
this.reported.clear();
}
}
private void queryAxis(int axis, double from, double to, Consumer<T> out) {
double lo = Math.min(from, to), hi = Math.max(from, to);
if (lo == hi) return;
long loBucket = (long) Math.floor(lo);
long hiBucket = (long) Math.floor(hi);
if (hiBucket - loBucket > MAX_BUCKET_SPAN) {
var iterator = this.registrations.reference2ObjectEntrySet().fastIterator();
while (iterator.hasNext()) {
var entry = iterator.next();
considerCandidate(entry.getKey(), entry.getValue(), axis, lo, hi, out);
}
return;
}
var map = this.bucketsByAxis[axis];
for (long bucket = loBucket; bucket <= hiBucket; bucket++) {
ReferenceOpenHashSet<T> candidates = map.get(bucket);
if (candidates == null) {
continue;
}
for (T candidate : candidates) {
considerCandidate(candidate, this.registrations.get(candidate), axis, lo, hi, out);
}
}
}
private void considerCandidate(T owner, Registration<T> registration, int axis, double lo, double hi, Consumer<T> out) {
if (registration == null || this.reported.contains(owner)) {
return;
}
double loLocal = lo - registration.origin[axis];
double hiLocal = hi - registration.origin[axis];
for (float cut : registration.cuts[axis]) {
if (cut > loLocal && cut <= hiLocal) {
this.reported.add(owner);
out.accept(owner);
return;
}
}
}
private static long bucketKey(float localCoord, int origin) {
return (long) Math.floor((double) localCoord + (double) origin);
}
public int size() {
return this.registrations.size();
}
}
@@ -6,6 +6,8 @@ import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntArrays; import it.unimi.dsi.fastutil.ints.IntArrays;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Collection;
public final class PartitionTree implements SortState.Resortable { public final class PartitionTree implements SortState.Resortable {
private final Node root; private final Node root;
@@ -34,6 +36,24 @@ public final class PartitionTree implements SortState.Resortable {
return new PartitionTree(root, quads.count(), cutPlanes); return new PartitionTree(root, quads.count(), cutPlanes);
} }
public static float[][] mergeCutPlanes(Collection<PartitionTree> trees) {
FloatArrayList[] merged = { new FloatArrayList(), new FloatArrayList(), new FloatArrayList() };
for (PartitionTree tree : trees) {
for (int axis = 0; axis < 3; axis++) {
for (float cut : tree.cutPlanes(axis)) {
merged[axis].add(cut);
}
}
}
float[][] result = new float[3][];
for (int axis = 0; axis < 3; axis++) {
result[axis] = sortAndDedup(merged[axis]);
}
return result;
}
private static float[] sortAndDedup(FloatArrayList floats) { private static float[] sortAndDedup(FloatArrayList floats) {
float[] array = floats.toFloatArray(); float[] array = floats.toFloatArray();
FloatArrays.quickSort(array); FloatArrays.quickSort(array);