diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java index aa96a8b11..f0f331245 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.Nullable; * *

Bit layout: *

- * 63                 54 53 52 51       49 48      46 45                0
+ * 63                 55 54 53 52       50 49      46 45                0
  * +--------------------+--+--+-----------+----------+-------------------+
  * |       spare        |OD|IF| pending   | visuals  | visibility graph  |
  * +--------------------+--+--+-----------+----------+-------------------+
@@ -26,12 +26,12 @@ import org.jetbrains.annotations.Nullable;
  *       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).
- *   
  • Bits {@code 46..48}: {@link RenderVisualsService} visual flags.
  • - *
  • Bits {@code 49..51}: pending update type; zero means none, otherwise + *
  • Bits {@code 46..49}: {@link RenderVisualsService} visual flags.
  • + *
  • Bits {@code 50..52}: pending update type; zero means none, otherwise * {@code ChunkUpdateType.ordinal() + 1}.
  • - *
  • Bit {@code 52}: a build is in flight.
  • - *
  • Bit {@code 53}: the section's built data has occluder boxes.
  • - *
  • Bits {@code 54..63}: reserved.
  • + *
  • Bit {@code 53}: a build is in flight.
  • + *
  • Bit {@code 54}: the section's built data has occluder boxes.
  • + *
  • Bits {@code 55..63}: reserved.
  • * * *

    The visibility graph uses only bits {@code 0..45}, but @@ -54,20 +54,20 @@ public final class PackedSectionMetadata { private static final int VISIBILITY_BITS = 46; public static final long VISIBILITY_MASK = (1L << VISIBILITY_BITS) - 1; - // Bits 46..48: RenderVisualsService.HAS_* flags. + // Bits 46..49: RenderVisualsService flags. private static final int VISUALS_FLAGS_SHIFT = 46; - private static final long VISUALS_FLAGS_MASK = 0b111L; + private static final long VISUALS_FLAGS_MASK = 0b1111L; - // Bits 49..51: 0 means no pending update; otherwise ordinal + 1. - private static final int PENDING_UPDATE_SHIFT = 49; + // Bits 50..52: 0 means no pending update; otherwise ordinal + 1. + private static final int PENDING_UPDATE_SHIFT = 50; 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; + // Bit 53: a build cancellation token is currently attached. + private static final int BUILD_IN_FLIGHT_BIT = 53; private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; - // Bit 53: the section's built data has occluder boxes. - private static final int HAS_OCCLUDER_DATA_BIT = 53; + // Bit 54: the section's built data has occluder boxes. + private static final int HAS_OCCLUDER_DATA_BIT = 54; private static final long HAS_OCCLUDER_DATA_FLAG = 1L << HAS_OCCLUDER_DATA_BIT; /** @@ -90,14 +90,14 @@ public final class PackedSectionMetadata { return (packed & ~VISIBILITY_MASK) | (visibilityData & VISIBILITY_MASK); } - /** Returns the three visual-presence flags. */ + /** Returns the four visual 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. + * Replaces the visual flags and preserves every other field. + * Only the four low bits of {@code flags} are stored. */ public static long withVisualsFlags(long packed, int flags) { return (packed & ~(VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT)) @@ -145,7 +145,7 @@ public final class PackedSectionMetadata { /* * Compact collector metadata: includes only the info the VisibleChunkCollector cares about. * - * 6 5 3 2 0 + * 7 6 4 3 0 * +--+-------+--------+ * |IF|pending|visuals | * +--+-------+--------+ diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java index db4eceffe..6581789aa 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java @@ -8,7 +8,8 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.util.task.CancellationToken; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.PartitionTree; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -50,21 +51,34 @@ public class RenderSection extends AbstractSection { void onMetadataChanged(RenderSection section); } + /** Marks a section with no translucent render passes at all, which the debug overlay does not count */ + public static final int NO_TRANSLUCENT_GEOMETRY = -1; + /** - * A mapping from translucent render passes to the sort state for that particular pass (which contains data needed - * to perform a resort of the geometry as the camera moves). Will be empty for sections without any translucent - * render passes. + * A mapping from translucent render passes to the sort state for that particular pass, holding the data needed to + * resort that pass' geometry as the camera moves. Only passes that actually need resorting appear here, so this is + * empty for sections whose translucent geometry (if any) was sorted once at mesh time. */ @Getter @NotNull - private Map translucencySortStates = Collections.emptyMap(); + private Map translucencySortStates = Collections.emptyMap(); + + /** + * The {@link SortState#debugIndex()} of the most expensive sort among this section's translucent passes, or + * {@link #NO_TRANSLUCENT_GEOMETRY} if it has none. Only consumed by the debug overlay. + */ + @Getter + private int highestSortingIndex = NO_TRANSLUCENT_GEOMETRY; + + public enum SortMode { + NONE, + TREE, + DYNAMIC + } @Getter - private TranslucentQuadAnalyzer.Level highestSortingLevel = TranslucentQuadAnalyzer.Level.NONE; - - @Getter - @Setter - private boolean needsDynamicTranslucencySorting; + @NotNull + private SortMode sortMode = SortMode.NONE; // Pending Update State @@ -143,7 +157,13 @@ public class RenderSection extends AbstractSection { } public void updateCachedContextDataFlags() { - int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; + int flags = 0; + if (this.contextData != null) { + flags = this.contextData.getVisualBitmaskForSection(); + if (this.sortMode == SortMode.DYNAMIC) { + flags |= 1 << RenderVisualsService.NEEDS_DYNAMIC_SORT; + } + } long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; boolean hasOccluderData = this.contextData != null && this.contextData.occluderBoxes != null; @@ -179,22 +199,31 @@ public class RenderSection extends AbstractSection { return this.getVisualsServiceFlags() != 0; } - public void setTranslucencySortStates(@NotNull Map sortStates) { + /** + * @param sortStates the passes needing a resort as the camera moves; every entry implies dynamic sorting + * @param highestSortingIndex the highest variant seen before compaction, or {@link #NO_TRANSLUCENT_GEOMETRY} + */ + public void setTranslucencySortStates(@NotNull Map sortStates, int highestSortingIndex) { this.translucencySortStates = Map.copyOf(sortStates); - - TranslucentQuadAnalyzer.Level level = TranslucentQuadAnalyzer.Level.NONE; - boolean needsDynamicSorting = false; - - if (!sortStates.isEmpty()) { - // Find highest level among all sort states - for (TranslucentQuadAnalyzer.SortState state : sortStates.values()) { - level = state.level().ordinal() > level.ordinal() ? state.level() : level; - needsDynamicSorting |= state.requiresDynamicSorting(); - } + this.highestSortingIndex = highestSortingIndex; + if (sortStates.isEmpty()) { + this.sortMode = SortMode.NONE; + } else if (sortStates.values().stream().allMatch(state -> state instanceof PartitionTree)) { + this.sortMode = SortMode.TREE; + } else { + this.sortMode = SortMode.DYNAMIC; } + this.updateCachedContextDataFlags(); + } - this.highestSortingLevel = level; - this.needsDynamicTranslucencySorting = needsDynamicSorting; + public void clearTranslucencySortStates() { + this.translucencySortStates = Collections.emptyMap(); + this.sortMode = SortMode.NONE; + this.updateCachedContextDataFlags(); + } + + public boolean isTreeSorted() { + return this.sortMode == SortMode.TREE; } public @Nullable CancellationToken getBuildCancellationToken() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index b237bfe54..a6bfaea65 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -28,7 +28,6 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker; import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists; import org.embeddedt.embeddium.impl.render.chunk.metrics.RenderSectionMetricsTracker; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderFogComponent; @@ -39,7 +38,10 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum; import org.embeddedt.embeddium.impl.util.PositionUtil; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput; +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.util.suppliers.ExpiringSupplier; import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.Nullable; @@ -83,9 +85,20 @@ public abstract class RenderSectionManager { private final int renderDistance; - protected @Nullable Vector3ic lastCameraPosition; + /** {@link #cameraPosition}, rounded down to block coordinates */ + protected @Nullable Vector3ic cameraBlockPosition; + protected Vector3d cameraPosition = new Vector3d(); + /** last frame's exact camera position */ + protected @Nullable Vector3d previousCameraPosition; + + private final CutPlaneIndex cutPlaneIndex = new CutPlaneIndex<>(); + + private final ChunkJobMetricsTracker.MetricsData treeSortMetrics = new ChunkJobMetricsTracker.MetricsData(); + private long treeStatsWindowStart = System.nanoTime(); + private int treeTriggersThisSecond, treeTriggersLastSecond; + @Getter private final RenderPassConfiguration renderPassConfiguration; @@ -200,7 +213,9 @@ public abstract class RenderSectionManager { * per-frame camera bookkeeping. */ public void update(Viewport positionedViewport, int frame, boolean spectator) { - this.updateCameraPosition(positionedViewport); + if (!this.shadowPassRanThisFrame) { + this.updateCameraPosition(positionedViewport); + } if (this.shadowPassRanThisFrame) { // The shadow pass searched for this frame if the graph was dirty then. Any needsUpdate raised by @@ -240,7 +255,11 @@ public abstract class RenderSectionManager { } 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(); this.cameraPosition = new Vector3d(transform.x, transform.y, transform.z); } @@ -258,7 +277,15 @@ public abstract class RenderSectionManager { } private void checkTranslucencyChange() { - if(lastCameraPosition == null) + long now = System.nanoTime(); + if (now - this.treeStatsWindowStart >= ChunkJobMetricsTracker.OBSERVATION_COUNT_TIME) { + this.treeTriggersLastSecond = this.treeTriggersThisSecond; + this.treeTriggersThisSecond = 0; + this.treeSortMetrics.flipInterval(); + this.treeStatsWindowStart = now; + } + + if(cameraBlockPosition == null) return; int camSectionX = PositionUtil.posToSectionCoord(cameraPosition.x); @@ -266,6 +293,7 @@ public abstract class RenderSectionManager { int camSectionZ = PositionUtil.posToSectionCoord(cameraPosition.z); this.scheduleTranslucencyUpdates(camSectionX, camSectionY, camSectionZ); + this.scheduleTreeSortedUpdates(); } private void scheduleTranslucencyUpdates(int camSectionX, int camSectionY, int camSectionZ) { @@ -282,15 +310,15 @@ public abstract class RenderSectionManager { if (!region.hasSectionsInPass(translucentPass)) { continue; } - ByteIterator sectionIterator = entry.sectionsWithGeometryIterator(); + ByteIterator sectionIterator = entry.sectionsNeedingDynamicSortIterator(); if (sectionIterator == null) { continue; } while (sectionIterator.hasNext()) { var section = region.getSection(sectionIterator.nextByteAsInt()); - if (section == null || !section.isNeedsDynamicTranslucencySorting()) { - // Sections without sortable translucent data are not relevant + // tree-sorted sections are retriggered by scheduleTreeSortedUpdates() instead + if (section == null || section.getSortMode() != RenderSection.SortMode.DYNAMIC) { continue; } @@ -315,19 +343,50 @@ public abstract class RenderSectionManager { camSectionY != PositionUtil.posToSectionCoord(section.lastCameraY) || camSectionZ != PositionUtil.posToSectionCoord(section.lastCameraZ); - if (cameraChangedSection || section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { - section.setPendingUpdate(update); - // Inject it into the appropriate list - rebuildLists.get(update).add(section); - - section.lastCameraX = cameraPosition.x; - section.lastCameraY = cameraPosition.y; - section.lastCameraZ = cameraPosition.z; + if (!cameraChangedSection && !section.isAlignedWithSectionOnGrid(camSectionX, camSectionY, camSectionZ)) { + continue; } + + section.setPendingUpdate(update); + // Inject it into the appropriate list + rebuildLists.get(update).add(section); + + section.lastCameraX = cameraPosition.x; + section.lastCameraY = cameraPosition.y; + section.lastCameraZ = cameraPosition.z; } } } + /** 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; + } + + this.cutPlaneIndex.query( + this.previousCameraPosition.x, this.previousCameraPosition.y, this.previousCameraPosition.z, + this.cameraPosition.x, this.cameraPosition.y, this.cameraPosition.z, + section -> { + this.treeTriggersThisSecond++; + this.scheduleTreeSort(section); + } + ); + } + + private void scheduleTreeSort(RenderSection section) { + ChunkUpdateType update = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), + (allowImportantRebuilds() && 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); + this.getCurrentRenderListManager().getRebuildLists().byUpdateType().get(update).add(section); + } + /** * {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as * possible per frame} @@ -428,6 +487,8 @@ public abstract class RenderSectionManager { this.sectionMetricsTracker.removeSection(section); + this.cutPlaneIndex.remove(section); + section.delete(); this.markGraphDirty(); @@ -571,6 +632,10 @@ public abstract class RenderSectionManager { for (var holder : filtered) { var result = holder.output(); + + // whether this result belongs to the most recently submitted build + boolean latest = result.buildTime >= result.render.getLastSubmittedFrame(); + if (result instanceof ChunkBuildOutput buildResult) { boolean changed = this.updateSectionInfo(result.render, buildResult.info); @@ -582,15 +647,12 @@ public abstract class RenderSectionManager { } // We only change the translucency info on full rebuilds, as sorts can keep using the same data - this.updateTranslucencyInfo(result.render, buildResult.meshes); + this.updateTranslucencyInfo(result.render, buildResult.meshes, latest); } var job = result.render.getBuildCancellationToken(); - // Only clear the token if this result belongs to the most recently submitted build. - // A stale result from an earlier submission must not clear the token for a newer - // in-flight job, which is identified by a higher lastSubmittedFrame. - if (job != null && result.buildTime >= result.render.getLastSubmittedFrame()) { + if (job != null && latest) { result.render.setBuildCancellationToken(null); } @@ -599,14 +661,62 @@ public abstract class RenderSectionManager { } } - private void updateTranslucencyInfo(RenderSection render, Map meshes) { - Map sortStates = new Reference2ObjectArrayMap<>(); + /** + * @param latestBuild whether the meshes come from the most recent submission; a stale build keeps its planes + * indexed but leaves the camera bookkeeping to the build still in flight + */ + private void updateTranslucencyInfo(RenderSection render, Map meshes, boolean latestBuild) { + Map sortStates = new Reference2ObjectArrayMap<>(); + int highestIndex = RenderSection.NO_TRANSLUCENT_GEOMETRY; + for(var entry : meshes.entrySet()) { - if(entry.getKey().isSorted()) { - sortStates.put(entry.getKey(), Objects.requireNonNull(entry.getValue().sortState()).compactForStorage()); + if(!entry.getKey().isSorted()) { + continue; + } + + var state = Objects.requireNonNull(entry.getValue().sortState()); + + highestIndex = Math.max(highestIndex, state.debugIndex()); + + // Only resortable states survive compaction; everything else is already in its final order. + if(state.compactForStorage() instanceof SortState.Resortable resortable) { + sortStates.put(entry.getKey(), resortable); } } - render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates); + + render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates, highestIndex); + + if (render.isTreeSorted()) { + List 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()); + + // The build sorted for the camera at submission (see submitRebuildTasks). A crossing since then happened + // before the planes were indexed, so it has to be caught here or the order stays stale until the next one. + int ox = render.getOriginX(), oy = render.getOriginY(), oz = render.getOriginZ(); + for (PartitionTree tree : trees) { + if (latestBuild && tree.crossesCutPlane(render.lastCameraX - ox, render.lastCameraY - oy, render.lastCameraZ - oz, + this.cameraPosition.x - ox, this.cameraPosition.y - oy, this.cameraPosition.z - oz)) { + this.treeTriggersThisSecond++; + this.scheduleTreeSort(render); + break; + } + } + + // any crossing up to now was just handled. Dynamic sections keep the submission camera so that + // scheduleTranslucencyUpdates still sees movement made during the build. + if (latestBuild) { + render.lastCameraX = this.cameraPosition.x; + render.lastCameraY = this.cameraPosition.y; + render.lastCameraZ = this.cameraPosition.z; + } + } else { + // a rebuild that is no longer tree-sorted must drop its stale planes + this.cutPlaneIndex.remove(render); + } } // Section MetadataSink: mirrors a section's packed metadata into the graph-search lattice on every @@ -658,6 +768,10 @@ public abstract class RenderSectionManager { while ((result = this.buildResults.poll()) != null) { if (result instanceof ChunkJobResult.Success successfulResult) { this.jobMetricsTracker.collectMetrics(successfulResult); + + if (successfulResult.output() instanceof ChunkSortOutput sort && sort.render.isTreeSorted() && successfulResult.executionTimeNanos() >= 0) { + this.treeSortMetrics.collect(successfulResult.executionTimeNanos()); + } results.add(successfulResult); } else if (result instanceof ChunkJobResult.Failure failure) { failure.abort(); @@ -715,7 +829,12 @@ public abstract class RenderSectionManager { if (!type.isSort()) { // Prevent further sorts from being performed on this section - section.setNeedsDynamicTranslucencySorting(false); + section.clearTranslucencySortStates(); + + // the meshing task sorts its translucent geometry for this camera + section.lastCameraX = this.cameraPosition.x; + section.lastCameraY = this.cameraPosition.y; + section.lastCameraZ = this.cameraPosition.z; } } else { var result = new ChunkJobResult.Success<>(new ChunkBuildOutput(section, RenderSection.EMPTY_DATA, Reference2ReferenceMaps.emptyMap(), frame), -1); @@ -732,9 +851,9 @@ public abstract class RenderSectionManager { protected abstract @Nullable ChunkBuilderTask createRebuildTask(RenderSection render, int frame); public ChunkBuilderSortTask createSortTask(RenderSection render, int frame) { - if(!render.isNeedsDynamicTranslucencySorting()) + if(render.getTranslucencySortStates().isEmpty()) return null; - return new ChunkBuilderSortTask(render, (float)cameraPosition.x, (float)cameraPosition.y, (float)cameraPosition.z, frame, render.getTranslucencySortStates(), this.renderPassConfiguration); + return new ChunkBuilderSortTask(render, cameraPosition.x, cameraPosition.y, cameraPosition.z, frame, render.getTranslucencySortStates(), this.renderPassConfiguration); } public void markGraphDirty() { @@ -876,7 +995,7 @@ public abstract class RenderSectionManager { private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f); 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; } /** @@ -965,46 +1084,6 @@ public abstract class RenderSectionManager { return Collections.unmodifiableCollection(this.sectionByPosition.values()); } - private Collection getSortingStrings() { - List list = new ArrayList<>(); - - int[] sectionCounts = new int[TranslucentQuadAnalyzer.Level.VALUES.length]; - - for (Iterator it = this.getCurrentRenderListManager().getRenderLists().iterator(); it.hasNext(); ) { - var renderList = it.next(); - var region = renderList.getRegion(); - var listIter = renderList.sectionsWithGeometryIterator(); - if(listIter != null) { - while(listIter.hasNext()) { - RenderSection section = region.getSection(listIter.nextByteAsInt()); - // Do not count sections without translucent data - if(section == null || section.getTranslucencySortStates().isEmpty()) { - continue; - } - - sectionCounts[section.getHighestSortingLevel().ordinal()]++; - } - } - } - - StringBuilder sb = new StringBuilder(); - sb.append("Sorting: "); - TranslucentQuadAnalyzer.Level[] values = TranslucentQuadAnalyzer.Level.VALUES; - for (int i = 0; i < values.length; i++) { - TranslucentQuadAnalyzer.Level level = values[i]; - sb.append(level.name()); - sb.append('='); - sb.append(sectionCounts[level.ordinal()]); - if((i + 1) < values.length) { - sb.append(", "); - } - } - - list.add(sb.toString()); - - return list; - } - private Object2LongMap computeRenderPassTimingsMap() { Object2LongOpenHashMap map = new Object2LongOpenHashMap<>(); for (var entry : renderPassDrawTimers.entrySet()) { @@ -1053,11 +1132,13 @@ public abstract class RenderSectionManager { var rebuildLists = this.getCurrentRenderListManager().getRebuildLists(); - list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d)", + list.add(String.format("Chunk Queues: U=%02d (P0=%03d | P1=%03d | P2=%03d) S=%03d/%03d", this.buildResults.size(), rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_REBUILD), rebuildLists.getUpdateCount(ChunkUpdateType.REBUILD), - rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD) + rebuildLists.getUpdateCount(ChunkUpdateType.INITIAL_BUILD), + rebuildLists.getUpdateCount(ChunkUpdateType.IMPORTANT_SORT), + rebuildLists.getUpdateCount(ChunkUpdateType.SORT) )); var debugStats = renderListManager.getDebugStatistics(); @@ -1081,6 +1162,10 @@ public abstract class RenderSectionManager { if (renderListManager.getRenderLists().getPasses().stream().anyMatch(TerrainRenderPass::isSorted)) { list.add(debugStats.getSortingString()); + list.add(String.format("Tree Sort: %d planes, %d trig/s, %d sorts/s, %s avg", + this.cutPlaneIndex.planeCount(), this.treeTriggersLastSecond, + this.treeSortMetrics.getObservationsInLastTimeInterval(), + TimeUtil.stringifyTime((long) this.treeSortMetrics.getAverageNanos(0), TimeUnit.NANOSECONDS))); } return list; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java index 45de97b44..a90c9a7c3 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/ChunkBuildBuffers.java @@ -13,7 +13,7 @@ import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; import java.nio.ByteBuffer; @@ -90,7 +90,7 @@ public final class ChunkBuildBuffers { int vertexCount = 0; ModelQuadFacing[] facingsToUpload = pass.isSorted() ? ONLY_UNASSIGNED : ModelQuadFacing.VALUES; - TranslucentQuadAnalyzer.SortState sortState = pass.isSorted() ? builder.getVertexBuffer(ModelQuadFacing.UNASSIGNED).getSortState() : null; + SortState sortState = pass.isSorted() ? builder.getVertexBuffer(ModelQuadFacing.UNASSIGNED).getSortState() : null; for (ModelQuadFacing facing : facingsToUpload) { var buffer = builder.getVertexBuffer(facing); @@ -134,7 +134,8 @@ public final class ChunkBuildBuffers { mergedIndexBuffer = null; } - return new BuiltSectionMeshParts(mergedBuffer, mergedIndexBuffer, TranslucentQuadAnalyzer.SortState.compacted(sortState), vertexRanges); + // Uncompacted: the consumer needs the sorting level before it throws away the data behind it. + return new BuiltSectionMeshParts(mergedBuffer, mergedIndexBuffer, sortState, vertexRanges); } public void destroy() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java index 7add606b6..6cbd3da96 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/executor/ChunkJobMetricsTracker.java @@ -64,6 +64,11 @@ public class ChunkJobMetricsTracker { } } + public void flipInterval() { + this.observationsInLastTimeInterval = this.observationsInCurrentTimeInterval; + this.observationsInCurrentTimeInterval = 0; + } + public int getObservationsInLastTimeInterval() { return this.observationsInLastTimeInterval; } @@ -103,8 +108,7 @@ public class ChunkJobMetricsTracker { long time = System.nanoTime(); if ((time - lastTimeIntervalFlip) >= OBSERVATION_COUNT_TIME) { for (var data : metricsByTask.values()) { - data.observationsInLastTimeInterval = data.observationsInCurrentTimeInterval; - data.observationsInCurrentTimeInterval = 0; + data.flipInterval(); } lastTimeIntervalFlip = time; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java index a93a4ecbd..280293740 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/ChunkPrimitiveType.java @@ -1,6 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.compile.sorting; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; @@ -45,7 +45,7 @@ public interface ChunkPrimitiveType { * @param y y position of the camera * @param z z position of the camera */ - void generateSortedIndexBuffer(ByteBuffer indexBuffer, int numPrimitives, @Nullable TranslucentQuadAnalyzer.SortState chunkData, float x, float y, float z); + void generateSortedIndexBuffer(ByteBuffer indexBuffer, int numPrimitives, @Nullable SortState chunkData, float x, float y, float z); default List getDefines() { return List.of(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java index db57d7b2b..2cb38d6a9 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/sorting/QuadPrimitiveType.java @@ -1,12 +1,12 @@ package org.embeddedt.embeddium.impl.render.chunk.compile.sorting; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; -import org.embeddedt.embeddium.impl.util.sorting.MergeSort; +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.TranslucentSorter; import org.jetbrains.annotations.Nullable; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import java.nio.ByteBuffer; -import java.util.BitSet; public final class QuadPrimitiveType implements ChunkPrimitiveType { /** @@ -22,8 +22,6 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { private static final int VERTICES_PER_PRIMITIVE = 4; - private static final int FAKE_STATIC_CAMERA_OFFSET = 1000; - public QuadPrimitiveType(boolean triangulating) { this.triangulating = triangulating; } @@ -46,24 +44,26 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { } long ptr = LWJGL.memAddress(indexBuffer); - int elementsPerPrimitive = this.getIndexBufferElementsPerPrimitive(); - boolean triangulating = this.triangulating; - for (int primitiveIndex = 0; primitiveIndex < numPrimitives; primitiveIndex++) { - int indexOffset = primitiveIndex * elementsPerPrimitive; - int vertexOffset = primitiveIndex * VERTICES_PER_PRIMITIVE; + this.writePrimitive(ptr, primitiveIndex, primitiveIndex); + } + } - LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); - LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); - LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + /** writes the indices of the given quad as the primitive at the given position */ + private void writePrimitive(long ptr, int primitiveIndex, int quad) { + int indexOffset = primitiveIndex * this.getIndexBufferElementsPerPrimitive(); + int vertexOffset = quad * VERTICES_PER_PRIMITIVE; - if (triangulating) { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); - LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); - LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); - } else { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); - } + LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); + LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); + LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + + if (this.triangulating) { + LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); + LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); + LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); + } else { + LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); } } @@ -74,93 +74,59 @@ public final class QuadPrimitiveType implements ChunkPrimitiveType { } long ptr = LWJGL.memAddress(indexBuffer); - int elementsPerPrimitive = this.getIndexBufferElementsPerPrimitive(); - boolean triangulating = this.triangulating; - for (int primitiveIndex = 0; primitiveIndex < primitiveMapping.length; primitiveIndex++) { - int indexOffset = primitiveIndex * elementsPerPrimitive; + this.writePrimitive(ptr, primitiveIndex, primitiveMapping[primitiveIndex]); + } + } - // Map to the desired primitive - int vertexOffset = primitiveMapping[primitiveIndex] * VERTICES_PER_PRIMITIVE; + /** streams a partition tree's readout straight into the index buffer */ + private final class BufferSink implements PartitionTree.Sink { + private final long ptr; + private int primitiveIndex; - LWJGL.memPutInt(ptr + (indexOffset + 0) * 4, vertexOffset + 0); - LWJGL.memPutInt(ptr + (indexOffset + 1) * 4, vertexOffset + 1); - LWJGL.memPutInt(ptr + (indexOffset + 2) * 4, vertexOffset + 2); + private BufferSink(long ptr) { + this.ptr = ptr; + } - if (triangulating) { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 2); - LWJGL.memPutInt(ptr + (indexOffset + 4) * 4, vertexOffset + 3); - LWJGL.memPutInt(ptr + (indexOffset + 5) * 4, vertexOffset + 0); - } else { - LWJGL.memPutInt(ptr + (indexOffset + 3) * 4, vertexOffset + 3); + @Override + public void accept(int[] quads) { + for (int quad : quads) { + writePrimitive(this.ptr, this.primitiveIndex++, quad); } } } - private static void buildStaticDistanceArray(float[] centers, float[] distanceArray, float x, float y, float z, - float normX, float normY, float normZ, int quadCount, BitSet normalSigns) { - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - int centerIdx = quadIdx * 3; - - // Compute distance using projection of vector from camera->quad center onto shared normal, flipped by sign - // to accommodate backwards-facing quads in the same plane extensions - - float qX = centers[centerIdx + 0] - x; - float qY = centers[centerIdx + 1] - y; - float qZ = centers[centerIdx + 2] - z; - - distanceArray[quadIdx] = (normX * qX + normY * qY + normZ * qZ) * (normalSigns.get(quadIdx) ? 1 : -1); - } - } - - private static void buildDynamicDistanceArray(float[] centers, float[] distanceArray, int quadCount, float x, - float y, float z) { - // Sort using distance to camera directly - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - int centerIdx = quadIdx * 3; - - float qX = centers[centerIdx + 0] - x; - float qY = centers[centerIdx + 1] - y; - float qZ = centers[centerIdx + 2] - z; - distanceArray[quadIdx] = qX * qX + qY * qY + qZ * qZ; - } - } - @Override - public void generateSortedIndexBuffer(ByteBuffer indexBuffer, int quadCount, @Nullable TranslucentQuadAnalyzer.SortState chunkData, float x, float y, float z) { - if (chunkData == null || chunkData.level() == TranslucentQuadAnalyzer.Level.NONE || chunkData.centersLength() < 3) { + public void generateSortedIndexBuffer(ByteBuffer indexBuffer, int quadCount, @Nullable SortState chunkData, float x, float y, float z) { + if (chunkData instanceof PartitionTree tree) { + int bufferSize = getIndexBufferSize(quadCount); + if (indexBuffer.capacity() != bufferSize) { + throw new IllegalStateException("Given index buffer has length " + indexBuffer.capacity() + " but we expected " + bufferSize); + } + if (quadCount != tree.quadCount()) { + throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", tree.quadCount(), quadCount)); + } + + var sink = new BufferSink(LWJGL.memAddress(indexBuffer)); + tree.order(x, y, z, sink); + + if (sink.primitiveIndex != quadCount) { + throw new IllegalStateException(String.format("Partition tree wrote %d of %d quads", sink.primitiveIndex, quadCount)); + } + return; + } + + int[] order = chunkData != null ? TranslucentSorter.order(chunkData, x, y, z) : null; + + if (order == null) { generateSimpleIndexBuffer(indexBuffer, quadCount); return; } - if (quadCount != (chunkData.centersLength() / 3)) { - throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", chunkData.centersLength() / 3, quadCount)); + if (quadCount != order.length) { + throw new IllegalStateException(String.format("Mismatched SortState (%d) vs given quad count (%d)", order.length, quadCount)); } - float[] centers = chunkData.centers(); - int[] indicesArray = new int[quadCount]; - float[] distanceArray = new float[quadCount]; - boolean isStatic = chunkData.level() == TranslucentQuadAnalyzer.Level.STATIC; - for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { - indicesArray[quadIdx] = quadIdx; - } - - if (isStatic) { - buildStaticDistanceArray(centers, distanceArray, - centers[0] + chunkData.sharedNormal().x * FAKE_STATIC_CAMERA_OFFSET, - centers[1] + chunkData.sharedNormal().y * FAKE_STATIC_CAMERA_OFFSET, - centers[2] + chunkData.sharedNormal().z * FAKE_STATIC_CAMERA_OFFSET, - chunkData.sharedNormal().x, - chunkData.sharedNormal().y, - chunkData.sharedNormal().z, - quadCount, - chunkData.normalSigns()); - } else { - buildDynamicDistanceArray(centers, distanceArray, quadCount, x, y, z); - } - - MergeSort.mergeSort(indicesArray, distanceArray); - - generateIndexBuffer(indexBuffer, indicesArray); + generateIndexBuffer(indexBuffer, order); } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java index ca447e802..d1453eedd 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/compile/tasks/ChunkBuilderSortTask.java @@ -8,18 +8,18 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.util.task.CancellationToken; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import java.util.Map; public class ChunkBuilderSortTask extends ChunkBuilderTask { private final RenderSection render; - private final float cameraX, cameraY, cameraZ; + private final double cameraX, cameraY, cameraZ; private final int frame; - private final Map translucentMeshes; + private final Map translucentMeshes; private final RenderPassConfiguration renderPassConfiguration; - public ChunkBuilderSortTask(RenderSection render, float cameraX, float cameraY, float cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { + public ChunkBuilderSortTask(RenderSection render, double cameraX, double cameraY, double cameraZ, int frame, Map translucentMeshes, RenderPassConfiguration renderPassConfiguration) { this.render = render; this.cameraX = cameraX; this.cameraY = cameraY; @@ -32,11 +32,11 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask { @Override public ChunkSortOutput execute(ChunkBuildContext context, CancellationToken cancellationSource) { var meshes = new Reference2ReferenceOpenHashMap(); - for(Map.Entry entry : translucentMeshes.entrySet()) { + for(Map.Entry entry : translucentMeshes.entrySet()) { var sortInfo = entry.getValue(); var primitiveType = this.renderPassConfiguration.getPrimitiveTypeForPass(entry.getKey()); - var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.centersLength() / 3)); - primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.centersLength() / 3, sortInfo, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ()); + var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.quadCount())); + primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.quadCount(), sortInfo, (float) (cameraX - this.render.getOriginX()), (float) (cameraY - this.render.getOriginY()), (float) (cameraZ - this.render.getOriginZ())); meshes.put(entry.getKey(), new ChunkSortOutput.SortedMesh( newIndexBuffer )); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java index a13aff9e9..6809b2ad9 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltSectionMeshParts.java @@ -6,13 +6,13 @@ import org.embeddedt.embeddium.impl.gl.util.VertexRange; import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.jetbrains.annotations.Nullable; import java.util.Map; -public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable TranslucentQuadAnalyzer.SortState sortState, Map ranges) { +public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable SortState sortState, Map ranges) { public void free() { vertexBuffer.free(); if (indexBuffer != null) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java index 9ee315bd5..4a45e7743 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/ChunkRenderList.java @@ -19,6 +19,9 @@ public class ChunkRenderList { private final byte[] sectionsWithEntities = new byte[RenderRegion.REGION_SIZE]; private int sectionsWithEntitiesCount = 0; + private final byte[] sectionsNeedingDynamicSort = new byte[RenderRegion.REGION_SIZE]; + private int sectionsNeedingDynamicSortCount = 0; + private int size; public ChunkRenderList(RenderRegion region) { @@ -40,6 +43,17 @@ public class ChunkRenderList { this.sectionsWithEntities[this.sectionsWithEntitiesCount] = (byte) index; this.sectionsWithEntitiesCount += (flags >>> RenderVisualsService.HAS_BLOCK_ENTITIES) & 1; + + this.sectionsNeedingDynamicSort[this.sectionsNeedingDynamicSortCount] = (byte) index; + this.sectionsNeedingDynamicSortCount += (flags >>> RenderVisualsService.NEEDS_DYNAMIC_SORT) & 1; + } + + public @Nullable ByteIterator sectionsNeedingDynamicSortIterator() { + if (this.sectionsNeedingDynamicSortCount == 0) { + return null; + } + + return new ByteArrayIterator(this.sectionsNeedingDynamicSort, this.sectionsNeedingDynamicSortCount); } public @Nullable ByteIterator sectionsWithGeometryIterator() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java index 32960b5ae..12ae2164a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderListManager.java @@ -5,7 +5,8 @@ import lombok.Getter; import lombok.Setter; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.jetbrains.annotations.NotNull; @@ -65,13 +66,12 @@ public class RenderListManager { StringBuilder sb = new StringBuilder(); sb.append("Sorting: "); - TranslucentQuadAnalyzer.Level[] values = TranslucentQuadAnalyzer.Level.VALUES; - for (int i = 0; i < values.length; i++) { - TranslucentQuadAnalyzer.Level level = values[i]; - sb.append(level.name()); + String[] names = SortState.DEBUG_NAMES; + for (int i = 0; i < names.length; i++) { + sb.append(names[i]); sb.append('='); - sb.append(sortingSectionCounts[level.ordinal()]); - if((i + 1) < values.length) { + sb.append(sortingSectionCounts[i]); + if((i + 1) < names.length) { sb.append(", "); } } @@ -226,7 +226,7 @@ public class RenderListManager { var iterator = renderLists.iterator(); - int[] sectionCounts = new int[TranslucentQuadAnalyzer.Level.VALUES.length]; + int[] sectionCounts = new int[SortState.DEBUG_NAMES.length]; boolean isSorting = renderLists.getPasses().stream().anyMatch(TerrainRenderPass::isSorted); @@ -265,11 +265,11 @@ public class RenderListManager { var section = region.getSection(sectionIndex); // Do not count sections without translucent data - if(section == null || section.getTranslucencySortStates().isEmpty()) { + if(section == null || section.getHighestSortingIndex() == RenderSection.NO_TRANSLUCENT_GEOMETRY) { continue; } - sectionCounts[section.getHighestSortingLevel().ordinal()]++; + sectionCounts[section.getHighestSortingIndex()]++; } } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java index 18b4bd527..996a93c48 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/RenderVisualsService.java @@ -4,4 +4,5 @@ public class RenderVisualsService { public static final int HAS_BLOCK_GEOMETRY = 0; public static final int HAS_SPRITES = 1; public static final int HAS_BLOCK_ENTITIES = 2; + public static final int NEEDS_DYNAMIC_SORT = 3; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java new file mode 100644 index 000000000..8c7d99863 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/CutPlaneIndex.java @@ -0,0 +1,165 @@ +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 { + /** movements larger than this many buckets rescan every owner instead of walking the buckets */ + static final int MAX_BUCKET_SPAN = 64; + + private record Registration(float[][] cuts, int[] origin, long[][] buckets) { + } + + @SuppressWarnings("unchecked") + private final Long2ObjectOpenHashMap>[] bucketsByAxis = new Long2ObjectOpenHashMap[] { + new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>(), new Long2ObjectOpenHashMap<>() + }; + + private final Reference2ObjectOpenHashMap> registrations = new Reference2ObjectOpenHashMap<>(); + + private final ReferenceOpenHashSet reported = new ReferenceOpenHashSet<>(); + + private int planeCount; + + 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; + } + + this.planeCount += cutsByAxis[0].length + cutsByAxis[1].length + cutsByAxis[2].length; + + 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 registration = this.registrations.remove(owner); + + if (registration == null) { + return; + } + + this.planeCount -= registration.cuts[0].length + registration.cuts[1].length + registration.cuts[2].length; + + for (int axis = 0; axis < 3; axis++) { + var map = this.bucketsByAxis[axis]; + + for (long key : registration.buckets[axis]) { + ReferenceOpenHashSet 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 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 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 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 registration, int axis, double lo, double hi, Consumer 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(); + } + + public int planeCount() { + return this.planeCount; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java new file mode 100644 index 000000000..a92f2b672 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/PartitionTree.java @@ -0,0 +1,445 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.floats.FloatArrays; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrays; +import org.embeddedt.embeddium.impl.util.sorting.MergeSort; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; + +public final class PartitionTree implements SortState.Resortable { + + private final Node root; + private final int quadCount; + private final float[][] cutPlanes; + + private PartitionTree(Node root, int quadCount, float[][] cutPlanes) { + this.root = root; + this.quadCount = quadCount; + this.cutPlanes = cutPlanes; + } + + static final int STATIC_LEAF_QUADS = 256; + + // null when some slab has no free cut + public static @Nullable PartitionTree build(QuadSet quads) { + return build(quads, STATIC_LEAF_QUADS); + } + + static @Nullable PartitionTree build(QuadSet quads, int staticLeafQuads) { + int[] all = new int[quads.count()]; + for (int i = 0; i < all.length; i++) all[i] = i; + + FloatArrayList[] cuts = { new FloatArrayList(), new FloatArrayList(), new FloatArrayList() }; + Node root = partition(quads, all, 2, cuts, staticLeafQuads); + if (root == null) return null; + + float[][] cutPlanes = new float[3][]; + for (int a = 0; a < 3; a++) { + cutPlanes[a] = sortAndDedup(cuts[a]); + } + return new PartitionTree(root, quads.count(), cutPlanes); + } + + public static float[][] mergeCutPlanes(Collection 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) { + float[] array = floats.toFloatArray(); + FloatArrays.quickSort(array); + + int n = 0; + for (int i = 0; i < array.length; i++) { + if (n == 0 || array[i] != array[n - 1]) { + array[n++] = array[i]; + } + } + return FloatArrays.copy(array, 0, n); + } + + private static Node partition(QuadSet quads, int[] group, int parentAxis, FloatArrayList[] collectedCuts, int staticLeafQuads) { + if (group.length <= 1) { + return new Leaf(group); + } + + int[] parallel = parallelOrder(quads, group); + if (parallel != null) { + return new Leaf(parallel); + } + + boolean triedStatic = group.length <= staticLeafQuads; + if (triedStatic) { + int[] topological = TranslucentSorter.topologicalOrder(quads, group); + if (topological != null) { + return new Leaf(topological); + } + } + + int axis = -1; + float[] planes = FloatArrays.EMPTY_ARRAY; + for (int i = 0; i < 3; i++) { + axis = (parentAxis + 1 + i) % 3; + planes = cutsOn(quads, group, axis); + if (planes.length > 0) break; + } + if (planes.length == 0) { + // no free cut does not imply a cycle: a camera-independent order may still exist + int[] topological = !triedStatic && group.length <= TranslucentSorter.MAX_TOPO_QUADS ? TranslucentSorter.topologicalOrder(quads, group) : null; + if (topological != null) { + return new Leaf(topological); + } + return partitionIntersectors(quads, group, collectedCuts, staticLeafQuads); + } + + Buckets buckets = bucket(quads, group, axis, planes); + + // gaps between quads that are all parallel would only slice one static leaf into pieces, each gap a trigger + // plane: keep just the cuts carrying quads on the plane (some do, else the group itself was parallel) + float[] carrying = planesWithQuads(planes, buckets.onPlane); + if (carrying.length > 0 && carrying.length < planes.length && allParallel(quads, buckets.slabs)) { + planes = carrying; + buckets = bucket(quads, group, axis, planes); + } + + IntArrayList[] onPlaneLists = buckets.onPlane, slabLists = buckets.slabs; + int slabCount = planes.length + 1; + + Node[] slabs = new Node[slabCount]; + for (int i = 0; i < slabCount; i++) { + int[] slabGroup = slabLists[i].toIntArray(); + if (slabGroup.length == 0) { + slabs[i] = EMPTY; + continue; + } + Node child = partition(quads, slabGroup, axis, collectedCuts, staticLeafQuads); + if (child == null) return null; + slabs[i] = child; + } + + int[][] onPlane = new int[planes.length][]; + for (int i = 0; i < planes.length; i++) { + onPlane[i] = onPlaneLists[i].toIntArray(); + } + + for (float plane : planes) { + collectedCuts[axis].add(plane); + } + return new Split(axis, planes, slabs, onPlane); + } + + private record Buckets(IntArrayList[] onPlane, IntArrayList[] slabs) {} + + /** sorts the group into the quads lying on each plane and those in each slab between the planes */ + private static Buckets bucket(QuadSet quads, int[] group, int axis, float[] planes) { + IntArrayList[] onPlane = new IntArrayList[planes.length]; + for (int i = 0; i < planes.length; i++) onPlane[i] = new IntArrayList(); + IntArrayList[] slabs = new IntArrayList[planes.length + 1]; + for (int i = 0; i <= planes.length; i++) slabs[i] = new IntArrayList(); + + for (int quad : group) { + float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); + + // slab = number of planes at or below this quad's lo + int slab = 0; + while (slab < planes.length && planes[slab] <= lo + QuadSet.EPSILON) slab++; + + if (hi - lo <= QuadSet.EPSILON && slab > 0 && Math.abs(planes[slab - 1] - lo) <= QuadSet.EPSILON) { + onPlane[slab - 1].add(quad); + } else { + slabs[slab].add(quad); + } + } + return new Buckets(onPlane, slabs); + } + + private static float[] planesWithQuads(float[] planes, IntArrayList[] onPlane) { + FloatArrayList kept = new FloatArrayList(planes.length); + for (int i = 0; i < planes.length; i++) { + if (!onPlane[i].isEmpty()) kept.add(planes[i]); + } + return kept.toFloatArray(); + } + + private static boolean allParallel(QuadSet quads, IntArrayList[] slabs) { + int reference = -1; + for (IntArrayList slab : slabs) { + for (int i = 0; i < slab.size(); i++) { + int quad = slab.getInt(i); + if (reference < 0) { + reference = quad; + } else if (Math.abs(quads.normalDot(quad, reference)) < 1 - QuadSet.EPSILON) { + return false; + } + } + } + return true; + } + + private static @Nullable Node partitionIntersectors(QuadSet quads, int[] group, FloatArrayList[] collectedCuts, int staticLeafQuads) { + int n = group.length; + if (n > TranslucentSorter.MAX_TOPO_QUADS) return null; + + int[] degree = new int[n]; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (intersects(quads, group[i], group[j])) { + degree[i]++; + degree[j]++; + } + } + } + + boolean[] primary = new boolean[n]; + int count = 0; + while (true) { + int best = -1; + for (int i = 0; i < n; i++) { + if (degree[i] > 0 && (best < 0 || degree[i] > degree[best])) best = i; + } + if (best < 0) break; + primary[best] = true; + count++; + degree[best] = 0; + for (int j = 0; j < n; j++) { + if (!primary[j] && intersects(quads, group[best], group[j])) degree[j]--; + } + } + if (count == 0 || count == n) return null; + + int[] first = new int[count], rest = new int[n - count]; + for (int i = 0, f = 0, r = 0; i < n; i++) { + if (primary[i]) first[f++] = group[i]; else rest[r++] = group[i]; + } + Node a = partition(quads, first, 2, collectedCuts, staticLeafQuads); + Node b = a == null ? null : partition(quads, rest, 2, collectedCuts, staticLeafQuads); + return b == null ? null : new Fixed(a, b); + } + + private static boolean intersects(QuadSet quads, int p, int q) { + for (int axis = 0; axis < 3; axis++) { + if (quads.boundsMin(p, axis) >= quads.boundsMax(q, axis) - QuadSet.EPSILON + || quads.boundsMin(q, axis) >= quads.boundsMax(p, axis) - QuadSet.EPSILON) return false; + } + return true; + } + + private static int @Nullable [] parallelOrder(QuadSet quads, int[] group) { + int reference = group[0]; + float nx = quads.normalX(reference), ny = quads.normalY(reference), nz = quads.normalZ(reference); + float[] centers = quads.centers(); + int far = TranslucentSorter.FAKE_STATIC_CAMERA_OFFSET; + float camX = centers[reference * 3] + nx * far, camY = centers[reference * 3 + 1] + ny * far, camZ = centers[reference * 3 + 2] + nz * far; + + float[] keys = new float[group.length]; + for (int i = 0; i < group.length; i++) { + int quad = group[i]; + float dot = quads.normalDot(quad, reference); + if (Math.abs(dot) < 1 - QuadSet.EPSILON) return null; + + int c = quad * 3; + keys[i] = (nx * (centers[c] - camX) + ny * (centers[c + 1] - camY) + nz * (centers[c + 2] - camZ)) * (dot < 0 ? 1 : -1); + } + + int[] byKey = MergeSort.mergeSort(keys); + int[] order = new int[group.length]; + for (int i = 0; i < order.length; i++) order[i] = group[byKey[i]]; + return order; + } + + private static float[] cutsOn(QuadSet quads, int[] group, int axis) { + int n = group.length; + + // a quad either spans an interval on this axis, or lies flat on a single plane + float[] starts = new float[n], ends = new float[n], points = new float[n]; + int startCount = 0, endCount = 0, pointCount = 0; + + for (int quad : group) { + float lo = quads.boundsMin(quad, axis), hi = quads.boundsMax(quad, axis); + + if (hi - lo <= QuadSet.EPSILON) { + points[pointCount++] = lo; + } else { + starts[startCount++] = lo; + ends[endCount++] = hi; + } + } + + FloatArrays.quickSort(starts, 0, startCount); + FloatArrays.quickSort(ends, 0, endCount); + FloatArrays.quickSort(points, 0, pointCount); + + FloatArrayList cuts = new FloatArrayList(); + + int nextStart = 0, nextEnd = 0, nextPoint = 0; + int opened = 0; + int below = 0; + int sinceCut = 0; + + // only ends/planes can be cuts since a gap is always available at the last end before it, + // and a cut anywhere else in that gap would separate the same quads + while (nextEnd < endCount || nextPoint < pointCount) { + float plane = nextPoint == pointCount ? ends[nextEnd] + : nextEnd == endCount ? points[nextPoint] + : Math.min(ends[nextEnd], points[nextPoint]); + + // ends first, then quads on the plane, then starts: a quad beginning here is not yet in the way + while (nextEnd < endCount && ends[nextEnd] <= plane + QuadSet.EPSILON) { + nextEnd++; + below++; + sinceCut++; + } + + int onPlane = 0; + + while (nextPoint < pointCount && points[nextPoint] <= plane + QuadSet.EPSILON) { + nextPoint++; + onPlane++; + } + + while (nextStart < startCount && starts[nextStart] < plane - QuadSet.EPSILON) { + nextStart++; + opened++; + } + + int above = n - below - onPlane; + boolean free = opened == nextEnd; // nothing spans the plane + boolean useful = (below > 0 ? 1 : 0) + (onPlane > 0 ? 1 : 0) + (above > 0 ? 1 : 0) >= 2; + boolean separatesSomethingNew = onPlane > 0 || sinceCut > 0; + + if (free && useful && separatesSomethingNew) { + cuts.add(plane); + sinceCut = 0; + } + + // quads on this plane are behind the next one either way + below += onPlane; + sinceCut += onPlane; + } + + return cuts.toFloatArray(); + } + + public float[] cutPlanes(int axis) { + return cutPlanes[axis]; + } + + /** Receives the quads of one leaf or one plane at a time, farthest first */ + public interface Sink { + void accept(int[] quads); + } + + public int @Nullable [] order(float camX, float camY, float camZ) { + var sink = new ArraySink(new int[quadCount]); + order(camX, camY, camZ, sink); + return sink.order; + } + + /** The draw order for the camera position, streamed so the caller can write it out without an array in between */ + public void order(float camX, float camY, float camZ, Sink sink) { + write(root, camX, camY, camZ, sink); + } + + private static void write(Node node, float camX, float camY, float camZ, Sink sink) { + if (node instanceof Leaf leaf) { + sink.accept(leaf.quads); + return; + } + + if (node instanceof Fixed fixed) { + write(fixed.first, camX, camY, camZ, sink); + write(fixed.rest, camX, camY, camZ, sink); + return; + } + + Split split = (Split) node; + float camCoord = switch (split.axis) { + case 0 -> camX; + case 1 -> camY; + case 2 -> camZ; + default -> throw new AssertionError(); + }; + + int slab = 0; + while (slab < split.planes.length && split.planes[slab] <= camCoord + QuadSet.EPSILON) slab++; + + // slabs below the camera's, farthest first, each followed by the plane above it + for (int i = 0; i < slab; i++) { + write(split.slabs[i], camX, camY, camZ, sink); + sink.accept(split.onPlane[i]); + } + + // slabs above the camera's, farthest first, each followed by the plane below it + for (int i = split.slabs.length - 1; i > slab; i--) { + write(split.slabs[i], camX, camY, camZ, sink); + sink.accept(split.onPlane[i - 1]); + } + + // the camera's own slab is nearest, drawn last + write(split.slabs[slab], camX, camY, camZ, sink); + } + + private static final class ArraySink implements Sink { + private final int[] order; + private int pos; + + private ArraySink(int[] order) { + this.order = order; + } + + @Override + public void accept(int[] quads) { + System.arraycopy(quads, 0, order, pos, quads.length); + pos += quads.length; + } + } + + public boolean crossesCutPlane(double lastX, double lastY, double lastZ, double camX, double camY, double camZ) { + return crossesOnAxis(0, lastX, camX) || crossesOnAxis(1, lastY, camY) || crossesOnAxis(2, lastZ, camZ); + } + + private boolean crossesOnAxis(int axis, double from, double to) { + double lo = Math.min(from, to), hi = Math.max(from, to); + + for (float cut : cutPlanes[axis]) { + if (cut > lo && cut <= hi) { + return true; + } + } + + return false; + } + + @Override + public int debugIndex() { + return 2; + } + + @Override + public int quadCount() { + return quadCount; + } + + private static final Node EMPTY = new Leaf(IntArrays.EMPTY_ARRAY); + + sealed interface Node permits Leaf, Split, Fixed {} + record Leaf(int[] quads) implements Node {} + record Split(int axis, float[] planes, Node[] slabs, int[][] onPlane) implements Node {} + record Fixed(Node first, Node rest) implements Node {} +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java new file mode 100644 index 000000000..18f9c6f1e --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/QuadSet.java @@ -0,0 +1,139 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; + +public record QuadSet(int count, float[] centers, float[] bounds, float[] normals, float[] dots, byte[] facings) { + static final float EPSILON = 1e-4f; + + public QuadSet { + if (count < 0) { + throw new IllegalArgumentException("count must be non-negative"); + } + + if (centers.length != count * 3) { + throw new IllegalArgumentException("centers length must be count * 3"); + } + + if (bounds.length != count * 6) { + throw new IllegalArgumentException("bounds length must be count * 6"); + } + + if (normals.length != count * 3) { + throw new IllegalArgumentException("normals length must be count * 3"); + } + + if (dots.length != count) { + throw new IllegalArgumentException("dots length must be count"); + } + + if (facings.length != count) { + throw new IllegalArgumentException("facings length must be count"); + } + } + + /** + * The smallest projection of the quad's bounds onto {@code (nx, ny, nz)}. The nearest corner is the one that is + * lowest along each axis the direction points up, and highest along each axis it points down, so no corner + * enumeration is needed. + */ + public float minDot(int quad, float nx, float ny, float nz) { + int boundOffset = quad * 6; + + return nx * (nx >= 0 ? bounds[boundOffset + 0] : bounds[boundOffset + 3]) + + ny * (ny >= 0 ? bounds[boundOffset + 1] : bounds[boundOffset + 4]) + + nz * (nz >= 0 ? bounds[boundOffset + 2] : bounds[boundOffset + 5]); + } + + /** + * The largest projection of the quad's bounds onto {@code (nx, ny, nz)}: {@link #minDot} with the corner choices + * reversed. + */ + public float maxDot(int quad, float nx, float ny, float nz) { + int boundOffset = quad * 6; + + return nx * (nx >= 0 ? bounds[boundOffset + 3] : bounds[boundOffset + 0]) + + ny * (ny >= 0 ? bounds[boundOffset + 4] : bounds[boundOffset + 1]) + + nz * (nz >= 0 ? bounds[boundOffset + 5] : bounds[boundOffset + 2]); + } + + public boolean isCoplanar(int a, int b) { + float normalDot = normalDot(a, b); + + if (Math.abs(Math.abs(normalDot) - 1.0f) > EPSILON) { + return false; + } + + float offsetB = normalDot < 0 ? -dots[b] : dots[b]; + return Math.abs(dots[a] - offsetB) < EPSILON; + } + + public float normalDot(int a, int b) { + int ao = a * 3, bo = b * 3; + + return normals[ao] * normals[bo] + normals[ao + 1] * normals[bo + 1] + normals[ao + 2] * normals[bo + 2]; + } + + public boolean isDegenerate(int quad) { + int normalOffset = quad * 3; + + return normals[normalOffset] == 0 && normals[normalOffset + 1] == 0 && normals[normalOffset + 2] == 0; + } + + public float normalX(int quad) { + return normals[quad * 3]; + } + + public float normalY(int quad) { + return normals[quad * 3 + 1]; + } + + public float normalZ(int quad) { + return normals[quad * 3 + 2]; + } + + public ModelQuadFacing facing(int quad) { + return ModelQuadFacing.VALUES[facings[quad]]; + } + + public Bounds union() { + float minX = Float.POSITIVE_INFINITY, minY = Float.POSITIVE_INFINITY, minZ = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY, maxZ = Float.NEGATIVE_INFINITY; + + for (int quad = 0; quad < count; quad++) { + int boundOffset = quad * 6; + + minX = Math.min(minX, bounds[boundOffset + 0]); + minY = Math.min(minY, bounds[boundOffset + 1]); + minZ = Math.min(minZ, bounds[boundOffset + 2]); + maxX = Math.max(maxX, bounds[boundOffset + 3]); + maxY = Math.max(maxY, bounds[boundOffset + 4]); + maxZ = Math.max(maxZ, bounds[boundOffset + 5]); + } + + return new Bounds(minX, minY, minZ, maxX, maxY, maxZ); + } + + public record Bounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + public float minDot(float nx, float ny, float nz) { + return nx * (nx >= 0 ? minX : maxX) + ny * (ny >= 0 ? minY : maxY) + nz * (nz >= 0 ? minZ : maxZ); + } + + public float maxDot(float nx, float ny, float nz) { + return nx * (nx >= 0 ? maxX : minX) + ny * (ny >= 0 ? maxY : minY) + nz * (nz >= 0 ? maxZ : minZ); + } + } + + /** if p must be drawn before q */ + public boolean isSeenThrough(int p, int q) { + return !isCoplanar(p, q) && minDot(p, normalX(q), normalY(q), normalZ(q)) < dots[q] - EPSILON + && maxDot(q, normalX(p), normalY(p), normalZ(p)) > dots[p] + EPSILON; + } + + public float boundsMin(int quad, int axis) { + return bounds[quad * 6 + axis]; + } + + public float boundsMax(int quad, int axis) { + return bounds[quad * 6 + 3 + axis]; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java new file mode 100644 index 000000000..3d05ff1cf --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/SortState.java @@ -0,0 +1,77 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +public sealed interface SortState { + SortState NONE = new None(); + + /** Variant names for the debug overlay, indexed by {@link #debugIndex()} and ordered by sorting cost */ + String[] DEBUG_NAMES = { "NONE", "STATIC", "TREE", "DYNAMIC" }; + + /** Position in {@link #DEBUG_NAMES}, doubling as the cost ranking used to pick a section's highest variant */ + int debugIndex(); + + int quadCount(); + + SortState compactForStorage(); + + default boolean requiresDynamicSorting() { + return this instanceof Resortable; + } + + /** A state whose order depends on the camera, and so survives compaction to be re-sorted on every move */ + sealed interface Resortable extends SortState permits Dynamic, PartitionTree { + @Override + default Resortable compactForStorage() { + return this; + } + } + + /** Any draw order is correct */ + record None() implements SortState { + @Override + public int debugIndex() { + return 0; + } + + @Override + public int quadCount() { + return 0; + } + + @Override + public SortState compactForStorage() { + return NONE; + } + } + + /** One camera-independent order, computed once during meshing */ + record Static(int[] order) implements SortState { + @Override + public int debugIndex() { + return 1; + } + + @Override + public int quadCount() { + return order.length; + } + + // The order is consumed by the index buffer written at build time, and can never change afterwards + @Override + public SortState compactForStorage() { + return NONE; + } + } + + /** Resortable, so the quad centers are kept for every re-sort */ + record Dynamic(float[] centers) implements Resortable { + @Override + public int debugIndex() { + return 3; + } + + @Override + public int quadCount() { + return centers.length / 3; + } + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java deleted file mode 100644 index 9ec7ed1f7..000000000 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadAnalyzer.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.embeddedt.embeddium.impl.render.chunk.sorting; - -import it.unimi.dsi.fastutil.floats.FloatArrayList; -import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; -import org.joml.Vector3f; - -import java.util.BitSet; - -public class TranslucentQuadAnalyzer { - // X/Y/Z for each quad center - private static final int EXPECTED_QUADS = 1000; - private final FloatArrayList quadCenters = new FloatArrayList(EXPECTED_QUADS * 3); - private final Vector3f[] vertexPositions = new Vector3f[4]; - private final Vector3f currentNormal = new Vector3f(); - private final Vector3f globalNormal = new Vector3f(); - private final BitSet normalSigns = new BitSet(EXPECTED_QUADS); - private static final BitSet EMPTY = new BitSet(); - private int currentVertex; - private boolean hasDistinctNormals; - - public enum Level { - /** - * No sorting is required of the current section. - */ - NONE, - /** - * Sorting is required once during meshing. - */ - STATIC, - /** - * Sorting is required any time the camera moves. - */ - DYNAMIC; - - public static final Level[] VALUES = values(); - - public boolean requiresDynamicSorting() { - return this.ordinal() >= Level.DYNAMIC.ordinal(); - } - } - - public TranslucentQuadAnalyzer() { - for(int i = 0; i < 4; i++) { - vertexPositions[i] = new Vector3f(); - } - } - - public record SortState(Level level, float[] centers, int centersLength, BitSet normalSigns, Vector3f sharedNormal) { - public static final SortState NONE = new SortState(Level.NONE, null, 0, null, null); - - public boolean requiresDynamicSorting() { - return level.requiresDynamicSorting(); - } - - public SortState compactForStorage() { - if(this == NONE || requiresDynamicSorting()) { - return this; - } else { - return new SortState(level, null, 0, null, null); - } - } - - public static SortState compacted(SortState state) { - return state != null ? state.compactForStorage() : null; - } - } - - private static BitSet cloneBits(BitSet bits) { - if(bits.isEmpty()) { - return EMPTY; - } else { - return (BitSet)bits.clone(); - } - } - - private boolean areAllQuadsOnSamePlane() { - // Let globalNormal = (a, b, c). Any plane with this normal vector is denoted by the equation ax + by + cz = d, - // for some real number d. - // - // Next, we know that any quad has either globalNormal or -globalNormal as a normal vector. Suppose a quad q has center (x, y, z). - // We define the "plane extension" of q as the unique plane in 3D space that q resides within. In particular, - // any quad's plane extension (when all share parallel normals) is uniquely determined by the choice of d. - // - // If all quads are on the same plane, we don't need to sort at all. Otherwise, we need to use a static sort. - // Recalling that d is given by ax + by + cz, and that we know all those variables for any quad, we can - // easily determine if all quads reside in the same plane by computing this expression for each quad center, - // and checking that we obtain at most one value. - - var centerArray = quadCenters.elements(); - - float a = globalNormal.x, b = globalNormal.y, c = globalNormal.z; - float d = a * centerArray[0] + b * centerArray[1] + c * centerArray[2]; - int nQuads = quadCenters.size() / 3; - for(int quadIdx = 1; quadIdx < nQuads; quadIdx++) { - int centerOff = quadIdx * 3; - float candidateD = a * centerArray[centerOff + 0] + b * centerArray[centerOff + 1] + c * centerArray[centerOff + 2]; - if(Math.abs(candidateD - d) >= 1.0E-5F) { - // Different planes - return false; - } - } - - return true; - } - - public SortState getSortState() { - if(quadCenters.isEmpty()) { - return SortState.NONE; - } else { - Level sortLevel; - - // Figure out what sort level is required - if(hasDistinctNormals) { - // Must use dynamic sort - sortLevel = Level.DYNAMIC; - } else { - // If all quads are on the same plane we can use NONE sorting, otherwise we need to sort statically to put - // them in the right order - sortLevel = areAllQuadsOnSamePlane() ? Level.NONE : Level.STATIC; - } - - SortState finalState; - - if (sortLevel == Level.NONE) { - finalState = SortState.NONE; - } else if (sortLevel.requiresDynamicSorting()) { - // Clone everything - finalState = new SortState(sortLevel, quadCenters.toArray(new float[0]), quadCenters.size(), cloneBits(normalSigns), new Vector3f(globalNormal)); - } else { - // Just make a thin wrapper around our backing objects - finalState = new SortState(sortLevel, quadCenters.elements(), quadCenters.size(), normalSigns, globalNormal); - } - - return finalState; - } - } - - public void clear() { - quadCenters.clear(); - currentVertex = 0; - globalNormal.zero(); - normalSigns.clear(); - hasDistinctNormals = false; - } - - private void calculateNormal() { - final Vector3f v0 = vertexPositions[0]; - - final float x0 = v0.x; - final float y0 = v0.y; - final float z0 = v0.z; - - final Vector3f v1 = vertexPositions[1]; - - final float x1 = v1.x; - final float y1 = v1.y; - final float z1 = v1.z; - - final Vector3f v2 = vertexPositions[2]; - - final float x2 = v2.x; - final float y2 = v2.y; - final float z2 = v2.z; - - final Vector3f v3 = vertexPositions[3]; - - final float x3 = v3.x; - final float y3 = v3.y; - final float z3 = v3.z; - - final float dx0 = x2 - x0; - final float dy0 = y2 - y0; - final float dz0 = z2 - z0; - final float dx1 = x3 - x1; - final float dy1 = y3 - y1; - final float dz1 = z3 - z1; - - float normX = dy0 * dz1 - dz0 * dy1; - float normY = dz0 * dx1 - dx0 * dz1; - float normZ = dx0 * dy1 - dy0 * dx1; - - float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); - - if (l != 0) { - normX /= l; - normY /= l; - normZ /= l; - } - - currentNormal.set(normX, normY, normZ); - } - - private void captureQuad() { - // The four positions in vertexPositions form a quad. Find its center - float totalX = 0, totalY = 0, totalZ = 0; - for (Vector3f vertex : vertexPositions) { - totalX += vertex.x; - totalY += vertex.y; - totalZ += vertex.z; - } - - var centers = quadCenters; - int currentQuadIndex = centers.size() / 3; - - centers.ensureCapacity(centers.size() + 3); - centers.add(totalX / 4); - centers.add(totalY / 4); - centers.add(totalZ / 4); - - if(!hasDistinctNormals) { - calculateNormal(); - - if(globalNormal.x == 0 && globalNormal.y == 0 && globalNormal.z == 0) { - // No normal has been tracked thus far, choose this one - globalNormal.set(currentNormal); - } else { - float dotProduct = globalNormal.dot(currentNormal); - // Technically, only 1 and -1 imply that the quads share a normal. However, if the dot products - // are very, very similar, we pretend they share a normal for optimization purposes. This is an - // approximation that allows very slightly slanted water in edges of underwater lakes to be counted as - // STATIC rather than DYNAMIC. - if (Math.abs(dotProduct) >= 0.98) { - if (dotProduct < 0) { - // Flag this quad as being flipped relative to the global normal - normalSigns.set(currentQuadIndex); - } - } else { - hasDistinctNormals = true; - } - } - } - } - - public void capture(ChunkVertexEncoder.Vertex vertex) { - int i = currentVertex; - vertexPositions[i].set(vertex.x, vertex.y, vertex.z); - i++; - if(i == 4) { - captureQuad(); - i = 0; - } - currentVertex = i; - } -} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java new file mode 100644 index 000000000..98cfcf166 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentQuadRecorder.java @@ -0,0 +1,146 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import it.unimi.dsi.fastutil.bytes.ByteArrayList; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; +import org.embeddedt.embeddium.impl.util.QuadUtil; +import org.joml.Vector3f; + +public class TranslucentQuadRecorder { + private static final int EXPECTED_QUADS = 1000; + + private final FloatArrayList quadCenters = new FloatArrayList(EXPECTED_QUADS * 3); + private final FloatArrayList quadBounds = new FloatArrayList(EXPECTED_QUADS * 6); + private final FloatArrayList quadNormals = new FloatArrayList(EXPECTED_QUADS * 3); + private final FloatArrayList quadDots = new FloatArrayList(EXPECTED_QUADS); + private final ByteArrayList quadFacings = new ByteArrayList(EXPECTED_QUADS); + + private final Vector3f[] vertexPositions = new Vector3f[4]; + private final Vector3f currentNormal = new Vector3f(); + private int currentVertex; + + public TranslucentQuadRecorder() { + for(int i = 0; i < 4; i++) { + vertexPositions[i] = new Vector3f(); + } + } + + public SortState getSortState() { + return TranslucentSorter.analyze(this.toQuadSet()); + } + + public void clear() { + quadCenters.clear(); + quadBounds.clear(); + quadNormals.clear(); + quadDots.clear(); + quadFacings.clear(); + currentVertex = 0; + } + + private void calculateNormal() { + final Vector3f v0 = vertexPositions[0]; + + final float x0 = v0.x; + final float y0 = v0.y; + final float z0 = v0.z; + + final Vector3f v1 = vertexPositions[1]; + + final float x1 = v1.x; + final float y1 = v1.y; + final float z1 = v1.z; + + final Vector3f v2 = vertexPositions[2]; + + final float x2 = v2.x; + final float y2 = v2.y; + final float z2 = v2.z; + + final Vector3f v3 = vertexPositions[3]; + + final float x3 = v3.x; + final float y3 = v3.y; + final float z3 = v3.z; + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + currentNormal.set(normX, normY, normZ); + } + + private void captureQuad() { + // The four positions in vertexPositions form a quad. Find its center and axis-aligned bounds + float totalX = 0, totalY = 0, totalZ = 0; + float minX = Float.POSITIVE_INFINITY, minY = Float.POSITIVE_INFINITY, minZ = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY, maxZ = Float.NEGATIVE_INFINITY; + + for (Vector3f vertex : vertexPositions) { + totalX += vertex.x; + totalY += vertex.y; + totalZ += vertex.z; + + minX = Math.min(minX, vertex.x); + minY = Math.min(minY, vertex.y); + minZ = Math.min(minZ, vertex.z); + maxX = Math.max(maxX, vertex.x); + maxY = Math.max(maxY, vertex.y); + maxZ = Math.max(maxZ, vertex.z); + } + + float centerX = totalX / 4, centerY = totalY / 4, centerZ = totalZ / 4; + + quadCenters.add(centerX); + quadCenters.add(centerY); + quadCenters.add(centerZ); + + quadBounds.add(minX); + quadBounds.add(minY); + quadBounds.add(minZ); + quadBounds.add(maxX); + quadBounds.add(maxY); + quadBounds.add(maxZ); + + calculateNormal(); + + quadNormals.add(currentNormal.x); + quadNormals.add(currentNormal.y); + quadNormals.add(currentNormal.z); + + quadDots.add(currentNormal.x * centerX + currentNormal.y * centerY + currentNormal.z * centerZ); + + quadFacings.add((byte) QuadUtil.findNormalFace(currentNormal.x, currentNormal.y, currentNormal.z).ordinal()); + } + + public void capture(ChunkVertexEncoder.Vertex vertex) { + int i = currentVertex; + vertexPositions[i].set(vertex.x, vertex.y, vertex.z); + i++; + if(i == 4) { + captureQuad(); + i = 0; + } + currentVertex = i; + } + + public QuadSet toQuadSet() { + return new QuadSet(quadCenters.size() / 3, quadCenters.toFloatArray(), quadBounds.toFloatArray(), + quadNormals.toFloatArray(), quadDots.toFloatArray(), quadFacings.toByteArray()); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java new file mode 100644 index 000000000..f441d3633 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/sorting/TranslucentSorter.java @@ -0,0 +1,286 @@ +package org.embeddedt.embeddium.impl.render.chunk.sorting; + +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.util.sorting.MergeSort; +import org.jetbrains.annotations.Nullable; + +import java.util.BitSet; + +public final class TranslucentSorter { + /** + * How far along the shared normal the imaginary camera used by {@link #sortNormalRelative} sits. Any value + * comfortably beyond the section is equivalent, since only the ordering of the projections matters. + */ + static final int FAKE_STATIC_CAMERA_OFFSET = 1000; + + /** + * How closely two normals must agree to be treated as parallel. Only +/-1 truly imply a shared normal, but + * accepting near misses lets very slightly slanted water (the edges of underwater lakes) sort statically. + */ + private static final float PARALLEL_THRESHOLD = 0.98f; + + private TranslucentSorter() { + } + + /** + * Orders quads by their distance to the camera, farthest first. + */ + public static int[] sortByDistance(float[] centers, int quadCount, float camX, float camY, float camZ) { + float[] distances = new float[quadCount]; + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + int centerIdx = quadIdx * 3; + + float qX = centers[centerIdx] - camX; + float qY = centers[centerIdx + 1] - camY; + float qZ = centers[centerIdx + 2] - camZ; + + distances[quadIdx] = qX * qX + qY * qY + qZ * qZ; + } + + return MergeSort.mergeSort(distances); + } + + /** + * Orders quads that all share the normal {@code (nx, ny, nz)}, up to a sign given by {@code flipped}. Because + * such quads only ever occlude each other along that normal, the resulting order is correct from any camera + * position, and can be computed once during meshing. + *

    + * Distance is measured by projecting onto the shared normal from a camera placed far along it. Quads facing the + * camera are ordered back to front and are drawn before the quads facing away, which are ordered front to back. + */ + public static int[] sortNormalRelative(float[] centers, int quadCount, float nx, float ny, float nz, BitSet flipped) { + float camX = centers[0] + nx * FAKE_STATIC_CAMERA_OFFSET; + float camY = centers[1] + ny * FAKE_STATIC_CAMERA_OFFSET; + float camZ = centers[2] + nz * FAKE_STATIC_CAMERA_OFFSET; + + float[] distances = new float[quadCount]; + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + int centerIdx = quadIdx * 3; + + float qX = centers[centerIdx] - camX; + float qY = centers[centerIdx + 1] - camY; + float qZ = centers[centerIdx + 2] - camZ; + + distances[quadIdx] = (nx * qX + ny * qY + nz * qZ) * (flipped.get(quadIdx) ? 1 : -1); + } + + return MergeSort.mergeSort(distances); + } + + public static int @Nullable [] order(SortState state, float camX, float camY, float camZ) { + if (state instanceof SortState.Static staticState) { + return staticState.order(); + } + + if (state instanceof SortState.Dynamic dynamic) { + return sortByDistance(dynamic.centers(), dynamic.quadCount(), camX, camY, camZ); + } + + if (state instanceof PartitionTree tree) { + return tree.order(camX, camY, camZ); + } + + return null; + } + + /** + * Decides the cheapest sort a section's translucent geometry can get away with. First match wins: + *

      + *
    1. no quads, or none that cover any pixels
    2. + *
    3. everything in one plane
    4. + *
    5. every quad flat on the section's bounding box, facing outward
    6. + *
    7. all normals parallel, so one order works from everywhere
    8. + *
    9. otherwise the order depends on the camera
    10. + *
    + */ + public static SortState analyze(QuadSet quads) { + int quadCount = quads.count(); + + if (quadCount == 0) { + return SortState.NONE; + } + + int reference = firstNonDegenerateQuad(quads); + + if (reference < 0) { + // every quad is degenerate, so none of them cover a pixel and no order can be wrong + return SortState.NONE; + } + + if (allCoplanarWith(quads, reference)) { + // quads in one plane never occlude each other + return SortState.NONE; + } + + if (allOutwardOnBoundingBox(quads)) { + // each quad is on a different face of the section's bounding box, facing away from the inside, so no + // two of them can ever overlap on screen + return SortState.NONE; + } + + float nx = quads.normalX(reference), ny = quads.normalY(reference), nz = quads.normalZ(reference); + + BitSet flipped = new BitSet(quadCount); + boolean allParallel = true; + + for (int quadIdx = 0; quadIdx < quadCount; quadIdx++) { + if (quads.isDegenerate(quadIdx)) continue; + + float dot = quads.normalDot(quadIdx, reference); + + if (Math.abs(dot) < PARALLEL_THRESHOLD) { + allParallel = false; + break; + } + + if (dot < 0) { + // this quad faces the opposite way to the reference + flipped.set(quadIdx); + } + } + + if (allParallel) { + // parallel but spread over several planes: the order cannot change, so sort once and keep only the result + return new SortState.Static(sortNormalRelative(quads.centers(), quadCount, nx, ny, nz, flipped)); + } + + if (quadCount <= MAX_TOPO_QUADS) { + int[] order = topologicalOrder(quads); + + if (order != null) { + return new SortState.Static(order); + } + } + + PartitionTree tree = PartitionTree.build(quads); + if (tree != null) return tree; + + return new SortState.Dynamic(quads.centers()); + } + + /** + * The first quad with a non-zero normal, or -1 if every quad is degenerate + */ + private static int firstNonDegenerateQuad(QuadSet quads) { + float[] normals = quads.normals(); + + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + int normalOffset = quadIdx * 3; + + if (normals[normalOffset] != 0 || normals[normalOffset + 1] != 0 || normals[normalOffset + 2] != 0) { + return quadIdx; + } + } + + return -1; + } + + private static boolean allCoplanarWith(QuadSet quads, int reference) { + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + if (!quads.isCoplanar(reference, quadIdx)) { + return false; + } + } + + return true; + } + + /** + * Whether every quad lies flat on the outer shell of the union of all their bounds, facing outward. Faces may be + * missing (a block against an opaque neighbour), but an inward or interior face fails, because it can be seen + * through the others. + */ + private static boolean allOutwardOnBoundingBox(QuadSet quads) { + QuadSet.Bounds box = quads.union(); + + for (int quadIdx = 0; quadIdx < quads.count(); quadIdx++) { + ModelQuadFacing facing = quads.facing(quadIdx); + + if (!facing.isDirection()) { + // A slanted or degenerate quad is not flat on any face of the box + return false; + } + + float nx = facing.getStepX(), ny = facing.getStepY(), nz = facing.getStepZ(); + + // the largest projection is the far side of the box, and a quad lying in a plane has no thickness at all + float quadMin = quads.minDot(quadIdx, nx, ny, nz); + float quadMax = quads.maxDot(quadIdx, nx, ny, nz); + + if (Math.abs(quadMax - quadMin) > QuadSet.EPSILON) { + return false; + } + + if (Math.abs(quadMax - box.maxDot(nx, ny, nz)) > QuadSet.EPSILON) { + return false; + } + } + + return true; + } + + public static final int MAX_TOPO_QUADS = 2048; + + /** returns null if the relation has a cycle */ + public static int @Nullable [] topologicalOrder(QuadSet quads) { + int[] all = new int[quads.count()]; + for (int i = 0; i < all.length; i++) all[i] = i; + return topologicalOrder(quads, all); + } + + /** + * The group's quads in an order correct from every camera, or null if their visibility relation has a cycle. + * A depth-first search over implicit edges: an acyclic group costs every pair, a cyclic one only until the first + * back edge, which dense cyclic geometry produces almost immediately. + */ + static int @Nullable [] topologicalOrder(QuadSet quads, int[] group) { + int n = group.length; + + // 0 = unvisited, 1 = on the stack, 2 = finished + byte[] state = new byte[n]; + int[] stack = new int[n], next = new int[n]; + int[] out = new int[n]; + int finished = 0; + + for (int root = n - 1; root >= 0; root--) { + if (state[root] != 0) continue; + + int depth = 0; + stack[0] = root; + next[0] = n - 1; + state[root] = 1; + + while (depth >= 0) { + int current = stack[depth]; + int candidate = next[depth]; + + // advance to the next quad that must be drawn after the current one + while (candidate >= 0 && (state[candidate] == 2 || candidate == current + || !quads.isSeenThrough(group[current], group[candidate]))) { + candidate--; + } + + if (candidate < 0) { + state[current] = 2; + out[n - 1 - finished++] = group[current]; // reverse postorder: predecessors first + depth--; + continue; + } + + if (state[candidate] == 1) { + return null; // back edge: a cycle + } + + next[depth] = candidate - 1; + depth++; + stack[depth] = candidate; + next[depth] = n - 1; + state[candidate] = 1; + } + } + + return out; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java index e4dd0c449..a07083d83 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/vertex/builder/ChunkMeshBufferBuilder.java @@ -2,7 +2,8 @@ package org.embeddedt.embeddium.impl.render.chunk.vertex.builder; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; -import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; +import org.embeddedt.embeddium.impl.render.chunk.sorting.SortState; +import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadRecorder; import org.jetbrains.annotations.Nullable; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import java.nio.ByteBuffer; @@ -12,7 +13,7 @@ public class ChunkMeshBufferBuilder { private final int stride; private final int initialCapacity; - private final TranslucentQuadAnalyzer analyzer; + private final TranslucentQuadRecorder analyzer; private ByteBuffer buffer; private int count; @@ -28,7 +29,7 @@ public class ChunkMeshBufferBuilder { this.capacity = 0; this.initialCapacity = initialCapacity; - this.analyzer = collectSortState ? new TranslucentQuadAnalyzer() : null; + this.analyzer = collectSortState ? new TranslucentQuadRecorder() : null; } public void push(ChunkVertexEncoder.Vertex[] vertices, Material material) { @@ -106,7 +107,7 @@ public class ChunkMeshBufferBuilder { } @Nullable - public TranslucentQuadAnalyzer.SortState getSortState() { + public SortState getSortState() { return this.analyzer != null ? this.analyzer.getSortState() : null; } diff --git a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java index efea91f59..c90f87c14 100644 --- a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java +++ b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java @@ -145,7 +145,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask buildContext.convertVanillaDataToCeleritasData(buffers); - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java index c9967c88d..45b641bfa 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java @@ -248,7 +248,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask throw fillCrashInfo(CrashReport.forThrowable(ex, "Encountered exception while building chunk meshes"), slice, blockPos); } - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; diff --git a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java index ed881f660..2391ce402 100644 --- a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java +++ b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java @@ -168,7 +168,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask } - Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,(float)camera.x - minX, (float)camera.y - minY, (float)camera.z - minZ); + Reference2ReferenceMap meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) (camera.x - minX), (float) (camera.y - minY), (float) (camera.z - minZ)); if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true;