diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/gl/device/MultiDrawBatch.java b/common/src/main/java/org/embeddedt/embeddium/impl/gl/device/MultiDrawBatch.java index 4cdf043ae..c4f531b09 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/gl/device/MultiDrawBatch.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/gl/device/MultiDrawBatch.java @@ -17,6 +17,8 @@ public final class MultiDrawBatch { public int size; + public int maxElementCount; + public MultiDrawBatch(int capacity) { this.pElementPointer = LWJGL.nmemAlignedAlloc(32, (long) capacity * LWJGL.getPointerSize()); if (this.pElementPointer == LWJGLServiceProvider.NULL) { @@ -49,6 +51,7 @@ public final class MultiDrawBatch { public void clear() { this.size = 0; + this.maxElementCount = 0; } public void delete() { @@ -62,12 +65,6 @@ public final class MultiDrawBatch { } public int getIndexBufferSize() { - int elements = 0; - - for (var index = 0; index < this.size; index++) { - elements = Math.max(elements, LWJGL.memGetInt(this.pElementCount + ((long) index * Integer.BYTES))); - } - - return elements; + return this.maxElementCount; } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/DefaultChunkRenderer.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/DefaultChunkRenderer.java index db20d1980..ba30fb0cb 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/DefaultChunkRenderer.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/DefaultChunkRenderer.java @@ -6,24 +6,23 @@ import org.embeddedt.embeddium.impl.gl.array.GlVertexArray; import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.tessellation.*; -import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler; import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter; import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; -import org.embeddedt.embeddium.impl.util.BitwiseMath; import java.util.Iterator; public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { + private final MultiDrawBatch batch; private final MultiDrawEmitter emitter; private final Reference2ReferenceMap sharedIndexBuffers; @@ -38,6 +37,7 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration renderPassConfiguration, MultiDrawEmitter emitter) { super(device, renderPassConfiguration); + this.batch = new MultiDrawBatch(MultiDrawEmitter.MAX_COMMAND_COUNT); this.emitter = emitter; this.sharedIndexBuffers = new Reference2ReferenceOpenHashMap<>(); } @@ -91,6 +91,9 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { long timestamp = System.nanoTime(); + var batch = this.batch; + var emitter = this.emitter; + while (iterator.hasNext()) { ChunkRenderList renderList = iterator.next(); @@ -101,21 +104,22 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { continue; } - fillCommandBuffer(this.emitter, region, storage, renderList, occlusionCamera, renderPass, useBlockFaceCulling && !renderPass.isSorted()); + BatchAssembler.fillRegion(batch, region, storage, renderList, occlusionCamera, renderPass, + useBlockFaceCulling && !renderPass.isSorted()); - if (this.emitter.isEmpty()) { + if (batch.isEmpty()) { continue; } if (!renderPass.isSorted()) { - getSharedIndexBuffer(renderPassConfiguration.getPrimitiveTypeForPass(renderPass), commandList).ensureCapacity(commandList, this.emitter.getIndexBufferSize()); + getSharedIndexBuffer(renderPassConfiguration.getPrimitiveTypeForPass(renderPass), commandList).ensureCapacity(commandList, batch.getIndexBufferSize()); } var tessellation = this.prepareTessellation(commandList, region); setModelMatrixUniforms(shader, region, camera); shader.setSectionAges(timestamp, region.getSectionLoadTimes()); - this.emitter.executeBatch(commandList, tessellation, primitiveType); + emitter.executeBatch(commandList, tessellation, primitiveType, batch); } this.currentVertexFormat = null; @@ -127,120 +131,6 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { this.end(renderPass); } - private static void fillCommandBuffer(MultiDrawEmitter emitter, - RenderRegion renderRegion, - SectionRenderDataStorage renderDataStorage, - ChunkRenderList renderList, - CameraTransform camera, - TerrainRenderPass pass, - boolean useBlockFaceCulling) { - emitter.clear(); - - var iterator = renderList.sectionsWithGeometryIterator(pass.isReverseOrder()); - - if (iterator == null) { - return; - } - - int originX = renderRegion.getChunkX(); - int originY = renderRegion.getChunkY(); - int originZ = renderRegion.getChunkZ(); - - int indexPointerMask = pass.isSorted() ? 0xFFFFFFFF : 0; - - while (iterator.hasNext()) { - int sectionIndex = iterator.nextByteAsInt(); - - int chunkX = originX + LocalSectionIndex.unpackX(sectionIndex); - int chunkY = originY + LocalSectionIndex.unpackY(sectionIndex); - int chunkZ = originZ + LocalSectionIndex.unpackZ(sectionIndex); - - var pMeshData = renderDataStorage.getDataPointer(sectionIndex); - - int slices; - - if (useBlockFaceCulling) { - slices = getVisibleFaces(camera.intX, camera.intY, camera.intZ, chunkX, chunkY, chunkZ); - } else { - slices = ModelQuadFacing.ALL; - } - - slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData); - - if (slices != 0) { - emitter.addDrawCommands(pMeshData, slices, indexPointerMask); - } - } - } - - private static final int MODEL_UNASSIGNED = ModelQuadFacing.UNASSIGNED.ordinal(); - private static final int MODEL_POS_X = ModelQuadFacing.POS_X.ordinal(); - private static final int MODEL_POS_Y = ModelQuadFacing.POS_Y.ordinal(); - private static final int MODEL_POS_Z = ModelQuadFacing.POS_Z.ordinal(); - - private static final int MODEL_NEG_X = ModelQuadFacing.NEG_X.ordinal(); - private static final int MODEL_NEG_Y = ModelQuadFacing.NEG_Y.ordinal(); - private static final int MODEL_NEG_Z = ModelQuadFacing.NEG_Z.ordinal(); - - /** - * When true, block face culling checks are inverted to debug if the feature works properly. - */ - private static final boolean DEBUG_BLOCK_FACE_CULLING = false; - - private static int getVisibleFaces(int originX, int originY, int originZ, int chunkX, int chunkY, int chunkZ) { - // This is carefully written so that we can keep everything branch-less. - // - // Normally, this would be a ridiculous way to handle the problem. But the Hotspot VM's - // heuristic for generating SETcc/CMOV instructions is broken, and it will always create a - // branch even when a trivial ternary is encountered. - // - // For example, the following will never be transformed into a SETcc: - // (a > b) ? 1 : 0 - // - // So we have to instead rely on sign-bit extension and masking (which generates a ton - // of unnecessary instructions) to get this to be branch-less. - // - // To do this, we can transform the previous expression into the following. - // (b - a) >> 31 - // - // This works because if (a > b) then (b - a) will always create a negative number. We then shift the sign bit - // into the least significant bit's position (which also discards any bits following the sign bit) to get the - // output we are looking for. - // - // If you look at the output which LLVM produces for a series of ternaries, you will instantly become distraught, - // because it manages to a) correctly evaluate the cost of instructions, and b) go so far - // as to actually produce vector code. (https://godbolt.org/z/GaaEx39T9) - - int boundsMinX = (chunkX << 4), boundsMaxX = boundsMinX + 16; - int boundsMinY = (chunkY << 4), boundsMaxY = boundsMinY + 16; - int boundsMinZ = (chunkZ << 4), boundsMaxZ = boundsMinZ + 16; - - // the "unassigned" plane is always front-facing, since we can't check it - int planes = (1 << MODEL_UNASSIGNED); - - if (DEBUG_BLOCK_FACE_CULLING) { - planes |= BitwiseMath.lessThan(originX, (boundsMaxX + 3)) << MODEL_POS_X; - planes |= BitwiseMath.lessThan(originY, (boundsMaxY + 3)) << MODEL_POS_Y; - planes |= BitwiseMath.lessThan(originZ, (boundsMaxZ + 3)) << MODEL_POS_Z; - - planes |= BitwiseMath.greaterThan(originX, (boundsMinX - 3)) << MODEL_NEG_X; - planes |= BitwiseMath.greaterThan(originY, (boundsMinY - 3)) << MODEL_NEG_Y; - planes |= BitwiseMath.greaterThan(originZ, (boundsMinZ - 3)) << MODEL_NEG_Z; - } else { - planes |= BitwiseMath.greaterThan(originX, (boundsMinX - 3)) << MODEL_POS_X; - planes |= BitwiseMath.greaterThan(originY, (boundsMinY - 3)) << MODEL_POS_Y; - planes |= BitwiseMath.greaterThan(originZ, (boundsMinZ - 3)) << MODEL_POS_Z; - - planes |= BitwiseMath.lessThan(originX, (boundsMaxX + 3)) << MODEL_NEG_X; - planes |= BitwiseMath.lessThan(originY, (boundsMaxY + 3)) << MODEL_NEG_Y; - planes |= BitwiseMath.lessThan(originZ, (boundsMaxZ + 3)) << MODEL_NEG_Z; - } - - - - return planes; - } - private static void setModelMatrixUniforms(ChunkShaderInterface shader, RenderRegion region, CameraTransform camera) { float x = getCameraTranslation(region.getOriginX(), camera.intX, camera.fracX); float y = getCameraTranslation(region.getOriginY(), camera.intY, camera.fracY); @@ -290,5 +180,6 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { this.sharedIndexBuffers.values().forEach(buffer -> buffer.delete(commandList)); this.emitter.delete(); + this.batch.delete(); } } 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 51394c839..0ef83f5a3 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 @@ -215,7 +215,7 @@ public abstract class RenderSectionManager { if (!region.hasSectionsInPass(translucentPass)) { continue; } - ByteIterator sectionIterator = entry.sectionsWithGeometryIterator(false); + ByteIterator sectionIterator = entry.sectionsWithGeometryIterator(); if (sectionIterator == null) { continue; } @@ -847,7 +847,7 @@ public abstract class RenderSectionManager { for (Iterator it = this.getCurrentRenderListManager().getRenderLists().iterator(); it.hasNext(); ) { var renderList = it.next(); var region = renderList.getRegion(); - var listIter = renderList.sectionsWithGeometryIterator(false); + var listIter = renderList.sectionsWithGeometryIterator(); if(listIter != null) { while(listIter.hasNext()) { RenderSection section = region.getSection(listIter.nextByteAsInt()); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataStorage.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataStorage.java index d07b06cfe..b338aeccf 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataStorage.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataStorage.java @@ -16,11 +16,13 @@ public class SectionRenderDataStorage { private final long pMeshDataArray; private final ChunkPrimitiveType primitiveType; + private final SectionRenderDataUnsafe.Strategy storageStrategy; private int numAllocations; - public SectionRenderDataStorage(ChunkPrimitiveType primitiveType) { - this.pMeshDataArray = SectionRenderDataUnsafe.allocateHeap(RenderRegion.REGION_SIZE); + public SectionRenderDataStorage(ChunkPrimitiveType primitiveType, boolean sorted) { + this.storageStrategy = sorted ? SectionRenderDataUnsafe.Strategy.FULL : SectionRenderDataUnsafe.Strategy.COMPACT; + this.pMeshDataArray = this.storageStrategy.allocateHeap(); if (this.pMeshDataArray == 0) { throw new OutOfMemoryError("Failed to allocate mesh data array"); } @@ -31,6 +33,10 @@ public class SectionRenderDataStorage { return this.numAllocations == 0; } + public ChunkPrimitiveType getPrimitiveType() { + return this.primitiveType; + } + public void setMeshes(int localSectionIndex, GlBufferSegment allocation, @Nullable GlBufferSegment indexAllocation, Map ranges) { if (this.allocations[localSectionIndex] != null) { @@ -48,40 +54,10 @@ public class SectionRenderDataStorage { this.indexAllocations[localSectionIndex] = indexAllocation; this.numAllocations++; - var pMeshData = this.getDataPointer(localSectionIndex); - - int sliceMask = 0; int vertexOffset = allocation.getOffset(); int indexOffset = indexAllocation != null ? indexAllocation.getOffset() * 4 : 0; - int elementsPerPrimitive = primitiveType.getIndexBufferElementsPerPrimitive(); - int verticesPerPrimitive = primitiveType.getVerticesPerPrimitive(); - - for (int facingIndex = 0; facingIndex < ModelQuadFacing.COUNT; facingIndex++) { - VertexRange vertexRange = ranges.get(ModelQuadFacing.VALUES[facingIndex]); - int vertexCount; - - if (vertexRange != null) { - vertexCount = vertexRange.vertexCount(); - } else { - vertexCount = 0; - } - - int indexCount = (vertexCount / verticesPerPrimitive) * elementsPerPrimitive; - - SectionRenderDataUnsafe.setVertexOffset(pMeshData, facingIndex, vertexOffset); - SectionRenderDataUnsafe.setElementCount(pMeshData, facingIndex, indexCount); - SectionRenderDataUnsafe.setIndexOffset(pMeshData, facingIndex, indexOffset); - - if (vertexCount > 0) { - sliceMask |= 1 << facingIndex; - } - - vertexOffset += vertexCount; - indexOffset += indexCount * 4; - } - - SectionRenderDataUnsafe.setSliceMask(pMeshData, sliceMask); + this.storageStrategy.writeMeshesAndSliceMask(this.pMeshDataArray, localSectionIndex, vertexOffset, indexOffset, ranges, this.primitiveType); } public void removeMeshes(int localSectionIndex) { @@ -89,7 +65,7 @@ public class SectionRenderDataStorage { this.allocations[localSectionIndex].delete(); this.allocations[localSectionIndex] = null; - SectionRenderDataUnsafe.clear(this.getDataPointer(localSectionIndex)); + this.storageStrategy.clearRow(this.pMeshDataArray, localSectionIndex); this.numAllocations--; } @@ -113,11 +89,7 @@ public class SectionRenderDataStorage { int indexOffset = indexAllocation != null ? indexAllocation.getOffset() * 4 : 0; - for (int facingIndex = 0; facingIndex < ModelQuadFacing.COUNT; facingIndex++) { - SectionRenderDataUnsafe.setIndexOffset(pMeshData, facingIndex, indexOffset); - int indexCount = SectionRenderDataUnsafe.getElementCount(pMeshData, facingIndex); - indexOffset += indexCount * 4; - } + this.storageStrategy.writeIndexOffsets(pMeshData, indexOffset, this.primitiveType); } public void onBufferResized() { @@ -140,21 +112,26 @@ public class SectionRenderDataStorage { var data = this.getDataPointer(sectionIndex); - int elementsPerPrimitive = primitiveType.getIndexBufferElementsPerPrimitive(); - int verticesPerPrimitive = primitiveType.getVerticesPerPrimitive(); - - for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) { - SectionRenderDataUnsafe.setVertexOffset(data, facing, vertexOffset); - SectionRenderDataUnsafe.setIndexOffset(data, facing, indexOffset); - - var indexCount = SectionRenderDataUnsafe.getElementCount(data, facing); - vertexOffset += (indexCount / elementsPerPrimitive) * verticesPerPrimitive; // convert elements back into vertices - indexOffset += indexCount * 4; - } + this.storageStrategy.rebase(data, vertexOffset, indexOffset, this.primitiveType); } public long getDataPointer(int sectionIndex) { - return SectionRenderDataUnsafe.heapPointer(this.pMeshDataArray, sectionIndex); + return this.storageStrategy.heapPointer(this.pMeshDataArray, sectionIndex); + } + + /** + * {@return the base address of the mesh data array} + *

+ * Row {@code i} begins {@code i * stride} bytes in. Exposed for hot loops which already know their layout + * statically, so that they can hoist the base and stride and index the array themselves rather than dispatching + * through {@link #getDataPointer} once per section. + */ + public long getRowBasePointer() { + return this.storageStrategy.getRowBasePointer(this.pMeshDataArray); + } + + public int getSliceMask(int sectionIndex) { + return this.storageStrategy.getSliceMask(this.pMeshDataArray, sectionIndex); } public void delete() { @@ -173,8 +150,8 @@ public class SectionRenderDataStorage { Arrays.fill(this.allocations, null); Arrays.fill(this.indexAllocations, null); - SectionRenderDataUnsafe.freeHeap(this.pMeshDataArray); + this.storageStrategy.freeHeap(this.pMeshDataArray); this.numAllocations = 0; } -} \ No newline at end of file +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataUnsafe.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataUnsafe.java index 6f86c2fde..c469cdb1d 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataUnsafe.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/SectionRenderDataUnsafe.java @@ -1,5 +1,12 @@ package org.embeddedt.embeddium.impl.render.chunk.data; +import org.embeddedt.embeddium.impl.gl.util.VertexRange; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; + +import java.util.Map; + import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; // This code is a terrible hack to get around the fact that we are so incredibly memory bound, and that we @@ -14,66 +21,350 @@ import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; // // Please never try to write performance critical code in Java. This is what it will do to you. And you will still be // three times slower than the most naive solution in literally any other language that LLVM can compile. -// -// Memory layout: -// u64 slice_mask; -// u32 vertex_offset; -// u32 element_count; -// u32 index_offset; public class SectionRenderDataUnsafe { - private static final long OFFSET_SLICE_MASK = 0; - private static final long OFFSET_SLICE_RANGES = 8; + private static final int NUM_FACINGS = ModelQuadFacing.COUNT; // 6 directions + UNASSIGNED - private static final long DATA_PER_FACING_SIZE = 12; - private static final long NUM_FACINGS = 7; // 6 directions + UNASSIGNED - - private static final long STRIDE = 8 + (DATA_PER_FACING_SIZE * NUM_FACINGS); - - public static long allocateHeap(int count) { - return LWJGL.nmemCalloc(count, STRIDE); + /** + * {@return the number of index buffer elements needed to draw a span of {@code vertexSpan} vertices} + */ + public static int elementsForVertices(int vertexSpan, ChunkPrimitiveType primitiveType) { + return (vertexSpan / primitiveType.getVerticesPerPrimitive()) * primitiveType.getIndexBufferElementsPerPrimitive(); } - public static void freeHeap(long pointer) { - LWJGL.nmemFree(pointer); + /** + * The inverse of {@link #elementsForVertices}. + */ + public static int verticesForElements(int elementCount, ChunkPrimitiveType primitiveType) { + return (elementCount / primitiveType.getIndexBufferElementsPerPrimitive()) * primitiveType.getVerticesPerPrimitive(); } - public static void clear(long pointer) { - LWJGL.memSet(pointer, 0x0, STRIDE); - } + /** + * Memory layouts for a single section's mesh data. Which one a {@link SectionRenderDataStorage} uses is fixed for + * its lifetime and determined by whether its pass is translucency-sorted. + *

+ * The write side of this interface is expressed as whole operations rather than per-field setters, because the two + * layouts do not store the same fields. {@link #COMPACT} derives element counts and has no index offsets at all. + * Operations that a layout genuinely cannot express throw. + */ + public enum Strategy { + /** + * The general layout. Stores, for each facing, an explicit vertex offset, element count and index offset. + *

+         * u64 slice_mask;
+         * struct { u32 vertex_offset; u32 element_count; u32 index_offset; } facings[7];
+         * 
+ * Required for sorted passes, which have per-facing index offsets into a per-section sorted index buffer. + */ + FULL { + private static final long OFFSET_SLICE_RANGES = 8; + private static final long DATA_PER_FACING_SIZE = 12; - public static long heapPointer(long ptr, int index) { - return ptr + (index * STRIDE); - } + private static long pVertexOffset(long ptr, int facing) { + return ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 0L; + } - public static void setSliceMask(long ptr, int value) { - LWJGL.memPutInt(ptr + OFFSET_SLICE_MASK, value); - } + private static long pElementCount(long ptr, int facing) { + return ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 4L; + } - public static int getSliceMask(long ptr) { - return LWJGL.memGetInt(ptr + OFFSET_SLICE_MASK); - } + private static long pIndexOffset(long ptr, int facing) { + return ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 8L; + } - public static void setVertexOffset(long ptr, int facing, int value) { - LWJGL.memPutInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 0L, value); - } + @Override + public long getStride() { + return OFFSET_SLICE_RANGES + (DATA_PER_FACING_SIZE * NUM_FACINGS); + } - public static int getVertexOffset(long ptr, int facing) { - return LWJGL.memGetInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 0L); - } + @Override + public int getVertexOffset(long ptr, int facing) { + return LWJGL.memGetInt(pVertexOffset(ptr, facing)); + } - public static void setElementCount(long ptr, int facing, int value) { - LWJGL.memPutInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 4L, value); - } + @Override + public int getElementCount(long ptr, int facing, ChunkPrimitiveType primitiveType) { + return LWJGL.memGetInt(pElementCount(ptr, facing)); + } - public static int getElementCount(long ptr, int facing) { - return LWJGL.memGetInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 4L); - } + @Override + public int getIndexOffset(long ptr, int facing) { + return LWJGL.memGetInt(pIndexOffset(ptr, facing)); + } - public static void setIndexOffset(long ptr, int facing, int value) { - LWJGL.memPutInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 8L, value); - } + @Override + public int getRunVertexEnd(long ptr, int lastFacing, ChunkPrimitiveType primitiveType) { + return LWJGL.memGetInt(pVertexOffset(ptr, lastFacing)) + + verticesForElements(LWJGL.memGetInt(pElementCount(ptr, lastFacing)), primitiveType); + } - public static int getIndexOffset(long ptr, int facing) { - return LWJGL.memGetInt(ptr + OFFSET_SLICE_RANGES + (facing * DATA_PER_FACING_SIZE) + 8L); + @Override + public int getSliceMask(long heap, int index) { + return LWJGL.memGetInt(this.heapPointer(heap, index)); + } + + @Override + protected void setSliceMask(long heap, int index, int value) { + LWJGL.memPutInt(this.heapPointer(heap, index), value); + } + + @Override + protected int writeMeshes(long ptr, int vertexOffset, int indexOffset, + Map ranges, ChunkPrimitiveType primitiveType) { + int sliceMask = 0; + + for (int facing = 0; facing < NUM_FACINGS; facing++) { + int vertexCount = vertexCountOf(ranges, facing); + int elementCount = elementsForVertices(vertexCount, primitiveType); + + LWJGL.memPutInt(pVertexOffset(ptr, facing), vertexOffset); + LWJGL.memPutInt(pElementCount(ptr, facing), elementCount); + LWJGL.memPutInt(pIndexOffset(ptr, facing), indexOffset); + + if (vertexCount > 0) { + sliceMask |= 1 << facing; + } + + vertexOffset += vertexCount; + indexOffset += elementCount * 4; + } + + return sliceMask; + } + + @Override + public void writeIndexOffsets(long ptr, int indexOffset, ChunkPrimitiveType primitiveType) { + for (int facing = 0; facing < NUM_FACINGS; facing++) { + LWJGL.memPutInt(pIndexOffset(ptr, facing), indexOffset); + indexOffset += LWJGL.memGetInt(pElementCount(ptr, facing)) * 4; + } + } + + @Override + public void rebase(long ptr, int vertexOffset, int indexOffset, ChunkPrimitiveType primitiveType) { + for (int facing = 0; facing < NUM_FACINGS; facing++) { + LWJGL.memPutInt(pVertexOffset(ptr, facing), vertexOffset); + LWJGL.memPutInt(pIndexOffset(ptr, facing), indexOffset); + + int elementCount = LWJGL.memGetInt(pElementCount(ptr, facing)); + vertexOffset += verticesForElements(elementCount, primitiveType); + indexOffset += elementCount * 4; + } + } + }, + /** + * The "fence post" layout, valid only for unsorted passes. + *
+         * u32 posts[8];
+         * 
+ * Slice masks are stored separately in one byte per section, followed by the aligned post rows. + * It drops index offsets entirely (unnecessary for unsorted passes) and compresses vertex info by exploiting + * the fact that facing vertex ranges are always contiguous in memory (in facing order), with empty facings having + * zero-length spans. + */ + COMPACT { + private static final long DATA_OFFSET = RenderRegion.REGION_SIZE; + private static final int NUM_POSTS = NUM_FACINGS + 1; + + private static long pPost(long ptr, int post) { + return ptr + ((long) post << 2); + } + + @Override + public long getStride() { + return Integer.BYTES * (long) NUM_POSTS; + } + + @Override + protected long getHeaderSize() { + return DATA_OFFSET; + } + + @Override + public int getSliceMask(long heap, int index) { + return LWJGL.memGetByte(heap + index) & 0xFF; + } + + @Override + protected void setSliceMask(long heap, int index, int value) { + LWJGL.memPutByte(heap + index, (byte) value); + } + + @Override + public int getVertexOffset(long ptr, int facing) { + return LWJGL.memGetInt(pPost(ptr, facing)); + } + + @Override + public int getElementCount(long ptr, int facing, ChunkPrimitiveType primitiveType) { + int start = LWJGL.memGetInt(pPost(ptr, facing)); + int end = LWJGL.memGetInt(pPost(ptr, facing + 1)); + + return elementsForVertices(end - start, primitiveType); + } + + @Override + public int getIndexOffset(long ptr, int facing) { + // Unsorted passes always draw through the shared index buffer, which starts at pointer zero. + return 0; + } + + @Override + public int getRunVertexEnd(long ptr, int lastFacing, ChunkPrimitiveType primitiveType) { + return LWJGL.memGetInt(pPost(ptr, lastFacing + 1)); + } + + @Override + protected int writeMeshes(long ptr, int vertexOffset, int indexOffset, + Map ranges, ChunkPrimitiveType primitiveType) { + int sliceMask = 0; + + for (int facing = 0; facing < NUM_FACINGS; facing++) { + int vertexCount = vertexCountOf(ranges, facing); + + LWJGL.memPutInt(pPost(ptr, facing), vertexOffset); + + if (vertexCount > 0) { + sliceMask |= 1 << facing; + } + + vertexOffset += vertexCount; + } + + LWJGL.memPutInt(pPost(ptr, NUM_FACINGS), vertexOffset); + + return sliceMask; + } + + @Override + public void writeIndexOffsets(long ptr, int indexOffset, ChunkPrimitiveType primitiveType) { + throw new UnsupportedOperationException(); + } + + @Override + public void rebase(long ptr, int vertexOffset, int indexOffset, ChunkPrimitiveType primitiveType) { + int delta = vertexOffset - LWJGL.memGetInt(pPost(ptr, 0)); + + if (delta == 0) { + return; + } + + for (int post = 0; post < NUM_POSTS; post++) { + long pPost = pPost(ptr, post); + LWJGL.memPutInt(pPost, LWJGL.memGetInt(pPost) + delta); + } + } + + }; + + public abstract long getStride(); + + public abstract int getVertexOffset(long ptr, int facing); + + /** + * @param primitiveType ignored by layouts which store explicit element counts + */ + public abstract int getElementCount(long ptr, int facing, ChunkPrimitiveType primitiveType); + + /** + * {@return the byte offset of this facing's indices, or zero if the layout draws from the shared index buffer} + */ + public abstract int getIndexOffset(long ptr, int facing); + + /** + * {@return the exclusive end of facing {@code lastFacing}'s vertex range} + *

+ * Paired with {@link #getVertexOffset} on a run's first facing, this yields the run's whole vertex span in two + * loads, and leaves the caller holding the start it needs as the command's base vertex. Merging a run into one + * command is only valid under {@link #COMPACT}, whose facings all draw from the shared index buffer. + */ + public abstract int getRunVertexEnd(long ptr, int lastFacing, ChunkPrimitiveType primitiveType); + + /** + * Populates an entire row from a freshly uploaded mesh and returns its slice mask. {@code ranges} must be + * contiguous in facing order starting at zero, as produced by the chunk build buffers. + * + * @param vertexOffset the section's base offset into the vertex arena, in vertices + * @param indexOffset the section's base offset into its index buffer, in bytes; layouts which draw from the + * shared index buffer ignore this + */ + protected abstract int writeMeshes(long ptr, int vertexOffset, int indexOffset, + Map ranges, ChunkPrimitiveType primitiveType); + + /** + * Rewrites every facing's index offset against a newly allocated index buffer, preserving element counts. + * + * @throws UnsupportedOperationException if the layout does not store index offsets + */ + public abstract void writeIndexOffsets(long ptr, int indexOffset, ChunkPrimitiveType primitiveType); + + /** + * Rewrites the row against new vertex and index arena offsets, preserving the per-facing sizes. Used when an + * arena grows and existing allocations move. + */ + public abstract void rebase(long ptr, int vertexOffset, int indexOffset, ChunkPrimitiveType primitiveType); + + public abstract int getSliceMask(long heap, int index); + + protected abstract void setSliceMask(long heap, int index, int value); + + /** + * {@return the number of leading bytes reserved before the row array, or zero if rows start at the heap base} + */ + protected long getHeaderSize() { + return 0; + } + + public final long getRowBasePointer(long heap) { + return heap + this.getHeaderSize(); + } + + public final long allocateHeap() { + long size = this.getHeaderSize() + (RenderRegion.REGION_SIZE * this.getStride()); + long pointer = LWJGL.nmemAlignedAlloc(64, size); + + if (pointer != 0) { + LWJGL.memSet(pointer, 0, size); + } + + return pointer; + } + + public final void freeHeap(long pointer) { + LWJGL.nmemAlignedFree(pointer); + } + + public final long heapPointer(long ptr, int index) { + return this.getRowBasePointer(ptr) + (index * this.getStride()); + } + + /** + * Populates section {@code index}'s row from a freshly uploaded mesh and records its slice mask, keeping the + * two in sync so callers can't forget the latter. {@code ranges} must be contiguous in facing order starting + * at zero, as produced by the chunk build buffers. + * + * @param vertexOffset the section's base offset into the vertex arena, in vertices + * @param indexOffset the section's base offset into its index buffer, in bytes; layouts which draw from the + * shared index buffer ignore this + */ + public final void writeMeshesAndSliceMask(long heap, int index, int vertexOffset, int indexOffset, + Map ranges, ChunkPrimitiveType primitiveType) { + int sliceMask = this.writeMeshes(this.heapPointer(heap, index), vertexOffset, indexOffset, ranges, primitiveType); + + this.setSliceMask(heap, index, sliceMask); + } + + /** + * Clears section {@code index}'s row and resets its slice mask to zero, keeping the two in sync. + */ + public final void clearRow(long heap, int index) { + this.setSliceMask(heap, index, 0); + LWJGL.memSet(this.heapPointer(heap, index), 0x0, this.getStride()); + } + + private static int vertexCountOf(Map ranges, int facing) { + VertexRange range = ranges.get(ModelQuadFacing.VALUES[facing]); + + return range != null ? range.vertexCount() : 0; + } } -} \ No newline at end of file +} 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 05204bb1e..f94e2ed75 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 @@ -3,7 +3,6 @@ package org.embeddedt.embeddium.impl.render.chunk.lists; import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.util.iterator.ByteIterator; -import org.embeddedt.embeddium.impl.util.iterator.ReversibleByteArrayIterator; import org.embeddedt.embeddium.impl.util.iterator.ByteArrayIterator; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.jetbrains.annotations.Nullable; @@ -46,12 +45,12 @@ public class ChunkRenderList { this.sectionsWithEntitiesCount += (flags >>> RenderVisualsService.HAS_BLOCK_ENTITIES) & 1; } - public @Nullable ByteIterator sectionsWithGeometryIterator(boolean reverse) { + public @Nullable ByteIterator sectionsWithGeometryIterator() { if (this.sectionsWithGeometryCount == 0) { return null; } - return new ReversibleByteArrayIterator(this.sectionsWithGeometry, this.sectionsWithGeometryCount, reverse); + return new ByteArrayIterator(this.sectionsWithGeometry, this.sectionsWithGeometryCount); } public @Nullable ByteIterator sectionsWithSpritesIterator() { @@ -70,6 +69,17 @@ public class ChunkRenderList { return new ByteArrayIterator(this.sectionsWithEntities, this.sectionsWithEntitiesCount); } + /** + * {@return the backing array of local section indices which have block geometry} + *

+ * Only the first {@link #getSectionsWithGeometryCount()} entries are meaningful, and each index is stored narrowed + * to a byte, so mask with {@code 0xFF} before use. Exposed so that draw-command assembly can walk the list without + * allocating a {@link ByteIterator} or paying a virtual call per section. Callers must not mutate it. + */ + public byte[] getSectionsWithGeometry() { + return this.sectionsWithGeometry; + } + public int getSectionsWithGeometryCount() { return this.sectionsWithGeometryCount; } @@ -92,7 +102,7 @@ public class ChunkRenderList { @Override public String toString() { - var iterator = this.sectionsWithGeometryIterator(false); + var iterator = this.sectionsWithGeometryIterator(); if (iterator == null) { return "[]"; } 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 8f8e6367a..cce67550e 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 @@ -6,7 +6,6 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import lombok.Getter; import lombok.Setter; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; import org.embeddedt.embeddium.impl.render.chunk.occlusion.GraphDirection; import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionCuller; import org.embeddedt.embeddium.impl.render.chunk.occlusion.OcclusionNode; @@ -315,13 +314,12 @@ public class RenderListManager { for (TerrainRenderPass pass : region.getPasses()) { int numToAdd = 0; var storage = region.getStorage(pass); - var iter = Objects.requireNonNull(renderList.sectionsWithGeometryIterator(false)); + var iter = Objects.requireNonNull(renderList.sectionsWithGeometryIterator()); while (iter.hasNext()) { int sectionIndex = iter.nextByteAsInt(); - var pMeshData = storage.getDataPointer(sectionIndex); - if (SectionRenderDataUnsafe.getSliceMask(pMeshData) != 0) { + if (storage.getSliceMask(sectionIndex) != 0) { numToAdd++; } } @@ -332,7 +330,7 @@ public class RenderListManager { } if (isSorting) { - var iter = Objects.requireNonNull(renderList.sectionsWithGeometryIterator(false)); + var iter = Objects.requireNonNull(renderList.sectionsWithGeometryIterator()); while (iter.hasNext()) { int sectionIndex = iter.nextByteAsInt(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/BatchAssembler.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/BatchAssembler.java new file mode 100644 index 000000000..6e1744e21 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/BatchAssembler.java @@ -0,0 +1,417 @@ +package org.embeddedt.embeddium.impl.render.chunk.multidraw; + +import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.embeddedt.embeddium.impl.util.BitwiseMath; + +import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; + +/** + * Turns a region's visible section list into a {@link MultiDrawBatch}. + */ +public final class BatchAssembler { + /** + * Magic sentinel returned by {@link BatchAssembler#uniformCullMask} when sections in the region have differing + * cull masks. + */ + private static final int MASK_NOT_UNIFORM = -1; + + private BatchAssembler() { + } + + /** + * Assembles every draw command for one region into {@code batch}, which is cleared first. + * + * @param useBlockFaceCulling whether the caller wants face culling; already false for sorted passes + */ + public static void fillRegion(MultiDrawBatch batch, + RenderRegion region, + SectionRenderDataStorage storage, + ChunkRenderList renderList, + CameraTransform camera, + TerrainRenderPass pass, + boolean useBlockFaceCulling) { + batch.clear(); + + var sections = renderList.getSectionsWithGeometry(); + int sectionCount = renderList.getSectionsWithGeometryCount(); + + if (sectionCount == 0) { + return; + } + + boolean reverse = pass.isReverseOrder(); + var primitiveType = storage.getPrimitiveType(); + + if (pass.isSorted()) { + // Sorted passes keep the FULL layout: real per-facing index offsets, so no merging is possible, and no + // culling is applied. In practice only UNASSIGNED is ever populated. + fillSorted(batch, storage, sections, sectionCount, reverse, primitiveType); + return; + } + + if (!useBlockFaceCulling) { + // Every facing visible everywhere: one run covering the whole section. + fillSingleRun(batch, storage, sections, sectionCount, reverse, primitiveType, 0, ModelQuadFacing.COUNT - 1); + return; + } + + // Determine whether every section in the region will use the same cull mask. If so, the relevant runs + // can be precomputed at the region-level rather than once per section. + int uniformMask = uniformCullMask(region, camera); + + if (uniformMask == MASK_NOT_UNIFORM) { + fillPerSectionRuns(batch, region, storage, sections, sectionCount, reverse, primitiveType, camera); + return; + } + + long runs = packRuns(uniformMask); + int runCount = runCount(runs); + + if (runCount == 0) { + return; + } + + if (runCount == 1) { + fillSingleRun(batch, storage, sections, sectionCount, reverse, primitiveType, + runFirst(runs, 0), runLast(runs, 0)); + } else { + fillUniformRuns(batch, storage, sections, sectionCount, reverse, primitiveType, runs, runCount); + } + } + + + /** + * {@return the cull mask that every section in the region shares, or {@link #MASK_NOT_UNIFORM} if they differ} + *

+ * Testing all sections would cost more than it saves, but the two opposite corners are enough to decide it. + * Consider the POS_X bit: it is set when the camera lies past the section's lower X bound. Stepping a section along + * +X only raises that bound, so across the region the bit can flip from set to clear but never back. Every other bit + * behaves the same way on its own axis. A bit that agrees at the lowest and the highest section therefore agrees at + * every section in between, so if the two corner masks are equal, that mask is the mask of the whole region. + */ + private static int uniformCullMask(RenderRegion region, CameraTransform camera) { + int minX = region.getChunkX(), minY = region.getChunkY(), minZ = region.getChunkZ(); + int maxX = minX + RenderRegion.REGION_WIDTH - 1; + int maxY = minY + RenderRegion.REGION_HEIGHT - 1; + int maxZ = minZ + RenderRegion.REGION_LENGTH - 1; + + int atMin = getVisibleFaces(camera.intX, camera.intY, camera.intZ, minX, minY, minZ); + int atMax = getVisibleFaces(camera.intX, camera.intY, camera.intZ, maxX, maxY, maxZ); + + return atMin == atMax ? atMin : MASK_NOT_UNIFORM; + } + + // A run plan is a cull mask decomposed into maximal groups of consecutive set bits, packed into one long. + // + // bits 0..3 run 0 first facing bits 4..7 run 0 last facing + // bits 8..11 run 1 first facing bits 12..15 run 1 last facing + // ... ... + // bits 32..35 run count + // + // Run i occupies nibbles 2i and 2i+1. A 7-bit facing mask can decompose into at most 4 runs (0b1010101), + // which need two 4-bit nibbles each. At 8 bits per run, that brings us to precisely the 32 bits below the count. + private static final int RUN_COUNT_SHIFT = 32; + + /** + * Decomposes a packed cull mask of visible facings into a run plan. + */ + private static long packRuns(int mask) { + long runs = 0; + int count = 0; + + while (mask != 0) { + int first = Integer.numberOfTrailingZeros(mask); + + // Length of the run of set bits starting at `first`. Shifting the run to start at bit 0 and complementing + // turns its end into the lowest set bit, so it can be located with another NTZ. + int length = Integer.numberOfTrailingZeros(~(mask >>> first)); + int last = (first + length) - 1; + + // Identifies where to embed the run in the packed plan + int shift = count << 3; + runs |= ((long) first << shift) | ((long) last << (shift + 4)); + count++; + + mask &= ~(((1 << length) - 1) << first); + } + + return runs | ((long) count << RUN_COUNT_SHIFT); + } + + /** + * {@return the number of runs packed in this plan} + */ + private static int runCount(long runs) { + return (int) (runs >>> RUN_COUNT_SHIFT) & 0xF; + } + + /** + * {@return the first facing of run `run` in the plan} + */ + private static int runFirst(long runs, int run) { + return (int) (runs >>> (run << 3)) & 0xF; + } + + /** + * {@return the last facing of run `run` in the plan} + */ + private static int runLast(long runs, int run) { + return (int) (runs >>> ((run << 3) + 4)) & 0xF; + } + + private static final int MODEL_UNASSIGNED = ModelQuadFacing.UNASSIGNED.ordinal(); + private static final int MODEL_POS_X = ModelQuadFacing.POS_X.ordinal(); + private static final int MODEL_POS_Y = ModelQuadFacing.POS_Y.ordinal(); + private static final int MODEL_POS_Z = ModelQuadFacing.POS_Z.ordinal(); + + private static final int MODEL_NEG_X = ModelQuadFacing.NEG_X.ordinal(); + private static final int MODEL_NEG_Y = ModelQuadFacing.NEG_Y.ordinal(); + private static final int MODEL_NEG_Z = ModelQuadFacing.NEG_Z.ordinal(); + + /** + * When true, block face culling checks are inverted to debug if the feature works properly. + */ + private static final boolean DEBUG_BLOCK_FACE_CULLING = false; + + public static int getVisibleFaces(int originX, int originY, int originZ, int chunkX, int chunkY, int chunkZ) { + // This is carefully written so that we can keep everything branch-less. + // TODO: Determine if this is worth keeping branchless now that we hoist it where possible + // + // Normally, this would be a ridiculous way to handle the problem. But the Hotspot VM's + // heuristic for generating SETcc/CMOV instructions is broken, and it will always create a + // branch even when a trivial ternary is encountered. + // + // For example, the following will never be transformed into a SETcc: + // (a > b) ? 1 : 0 + // + // So we have to instead rely on sign-bit extension and masking (which generates a ton + // of unnecessary instructions) to get this to be branch-less. + // + // To do this, we can transform the previous expression into the following. + // (b - a) >> 31 + // + // This works because if (a > b) then (b - a) will always create a negative number. We then shift the sign bit + // into the least significant bit's position (which also discards any bits following the sign bit) to get the + // output we are looking for. + // + // If you look at the output which LLVM produces for a series of ternaries, you will instantly become distraught, + // because it manages to a) correctly evaluate the cost of instructions, and b) go so far + // as to actually produce vector code. (https://godbolt.org/z/GaaEx39T9) + + int boundsMinX = (chunkX << 4), boundsMaxX = boundsMinX + 16; + int boundsMinY = (chunkY << 4), boundsMaxY = boundsMinY + 16; + int boundsMinZ = (chunkZ << 4), boundsMaxZ = boundsMinZ + 16; + + // the "unassigned" plane is always front-facing, since we can't check it + int planes = (1 << MODEL_UNASSIGNED); + + if (DEBUG_BLOCK_FACE_CULLING) { + planes |= BitwiseMath.lessThan(originX, (boundsMaxX + 3)) << MODEL_POS_X; + planes |= BitwiseMath.lessThan(originY, (boundsMaxY + 3)) << MODEL_POS_Y; + planes |= BitwiseMath.lessThan(originZ, (boundsMaxZ + 3)) << MODEL_POS_Z; + + planes |= BitwiseMath.greaterThan(originX, (boundsMinX - 3)) << MODEL_NEG_X; + planes |= BitwiseMath.greaterThan(originY, (boundsMinY - 3)) << MODEL_NEG_Y; + planes |= BitwiseMath.greaterThan(originZ, (boundsMinZ - 3)) << MODEL_NEG_Z; + } else { + planes |= BitwiseMath.greaterThan(originX, (boundsMinX - 3)) << MODEL_POS_X; + planes |= BitwiseMath.greaterThan(originY, (boundsMinY - 3)) << MODEL_POS_Y; + planes |= BitwiseMath.greaterThan(originZ, (boundsMinZ - 3)) << MODEL_POS_Z; + + planes |= BitwiseMath.lessThan(originX, (boundsMaxX + 3)) << MODEL_NEG_X; + planes |= BitwiseMath.lessThan(originY, (boundsMaxY + 3)) << MODEL_NEG_Y; + planes |= BitwiseMath.lessThan(originZ, (boundsMaxZ + 3)) << MODEL_NEG_Z; + } + + return planes; + } + + // ------------------------------------------------------------------------------------------------------------ + // Specialized loops for each of the scenarios. They all use similar structure but with increasing complexity + // depending on how much changes per section/run + // ------------------------------------------------------------------------------------------------------------ + + private static void fillSingleRun(MultiDrawBatch batch, + SectionRenderDataStorage storage, + byte[] sections, int sectionCount, boolean reverse, + ChunkPrimitiveType primitiveType, + int firstFacing, int lastFacing) { + final long pBase = storage.getRowBasePointer(); + final long stride = SectionRenderDataUnsafe.Strategy.COMPACT.getStride(); + + int cursor = reverse ? sectionCount - 1 : 0; + final int step = reverse ? -1 : 1; + + for (int i = 0; i < sectionCount; i++, cursor += step) { + long pMeshData = pBase + ((sections[cursor] & 0xFF) * stride); + + int start = SectionRenderDataUnsafe.Strategy.COMPACT.getVertexOffset(pMeshData, firstFacing); + int end = SectionRenderDataUnsafe.Strategy.COMPACT.getRunVertexEnd(pMeshData, lastFacing, primitiveType); + + write(batch, start, SectionRenderDataUnsafe.elementsForVertices(end - start, primitiveType), 0L); + } + } + + /** + * Uniform cull mask, but with more than one run to emit + */ + private static void fillUniformRuns(MultiDrawBatch batch, + SectionRenderDataStorage storage, + byte[] sections, int sectionCount, boolean reverse, + ChunkPrimitiveType primitiveType, + long runs, int runCount) { + final long pBase = storage.getRowBasePointer(); + final long stride = SectionRenderDataUnsafe.Strategy.COMPACT.getStride(); + + int cursor = reverse ? sectionCount - 1 : 0; + final int step = reverse ? -1 : 1; + + for (int i = 0; i < sectionCount; i++, cursor += step) { + long pMeshData = pBase + ((sections[cursor] & 0xFF) * stride); + int sectionStart = batch.size; + int previousEnd = 0; + + for (int run = 0; run < runCount; run++) { + int firstFacing = runFirst(runs, run); + int lastFacing = runLast(runs, run); + + int start = SectionRenderDataUnsafe.Strategy.COMPACT.getVertexOffset(pMeshData, firstFacing); + int end = SectionRenderDataUnsafe.Strategy.COMPACT.getRunVertexEnd(pMeshData, lastFacing, primitiveType); + + previousEnd = writeUnsorted(batch, start, end, primitiveType, sectionStart, previousEnd); + } + } + } + + /** + * The worst case scenario, where the cull mask is not uniform across the region, and the cull mask must be + * recomputed per section. Run planning is not used here. + */ + private static void fillPerSectionRuns(MultiDrawBatch batch, + RenderRegion region, + SectionRenderDataStorage storage, + byte[] sections, int sectionCount, boolean reverse, + ChunkPrimitiveType primitiveType, + CameraTransform camera) { + final long pBase = storage.getRowBasePointer(); + final long stride = SectionRenderDataUnsafe.Strategy.COMPACT.getStride(); + + final int originX = region.getChunkX(); + final int originY = region.getChunkY(); + final int originZ = region.getChunkZ(); + + final int cameraX = camera.intX, cameraY = camera.intY, cameraZ = camera.intZ; + + int cursor = reverse ? sectionCount - 1 : 0; + final int step = reverse ? -1 : 1; + + for (int i = 0; i < sectionCount; i++, cursor += step) { + int sectionIndex = sections[cursor] & 0xFF; + + int mask = getVisibleFaces(cameraX, cameraY, cameraZ, + originX + LocalSectionIndex.unpackX(sectionIndex), + originY + LocalSectionIndex.unpackY(sectionIndex), + originZ + LocalSectionIndex.unpackZ(sectionIndex)); + + long pMeshData = pBase + (sectionIndex * stride); + int sectionStart = batch.size; + int previousEnd = 0; + + // A do-while loop is chosen because UNASSIGNED is always marked as visible by getVisibleFaces, so the mask + // is never zero and there is always an attempt to emit at least one run. + do { + int firstFacing = Integer.numberOfTrailingZeros(mask); + int lastFacing = firstFacing + Integer.numberOfTrailingZeros(~(mask >>> firstFacing)) - 1; + + int start = SectionRenderDataUnsafe.Strategy.COMPACT.getVertexOffset(pMeshData, firstFacing); + int end = SectionRenderDataUnsafe.Strategy.COMPACT.getRunVertexEnd(pMeshData, lastFacing, primitiveType); + + previousEnd = writeUnsorted(batch, start, end, primitiveType, sectionStart, previousEnd); + + // Runs are found in ascending order, so clear all bits below what we just consumed. + mask &= -1 << (lastFacing + 1); + } while (mask != 0); + } + } + + /** + * Sorted pass: FULL layout, one command per populated facing, real index offsets, no culling. + */ + private static void fillSorted(MultiDrawBatch batch, + SectionRenderDataStorage storage, + byte[] sections, int sectionCount, boolean reverse, + ChunkPrimitiveType primitiveType) { + final long pBase = storage.getRowBasePointer(); + final long stride = SectionRenderDataUnsafe.Strategy.FULL.getStride(); + + int cursor = reverse ? sectionCount - 1 : 0; + final int step = reverse ? -1 : 1; + + for (int i = 0; i < sectionCount; i++, cursor += step) { + long pMeshData = pBase + ((sections[cursor] & 0xFF) * stride); + + for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) { + // Unconditionally write(); it skips empty commands automatically. + write(batch, + SectionRenderDataUnsafe.Strategy.FULL.getVertexOffset(pMeshData, facing), + SectionRenderDataUnsafe.Strategy.FULL.getElementCount(pMeshData, facing, primitiveType), + SectionRenderDataUnsafe.Strategy.FULL.getIndexOffset(pMeshData, facing)); + } + } + } + + private static final int POINTER_SHIFT = Integer.numberOfTrailingZeros(LWJGL.getPointerSize()); + + private static int writeUnsorted(MultiDrawBatch batch, int baseVertex, int endVertex, + ChunkPrimitiveType primitiveType, int sectionStart, int previousEnd) { + int elementCount = SectionRenderDataUnsafe.elementsForVertices(endVertex - baseVertex, primitiveType); + + if (elementCount == 0) { + return previousEnd; + } + + if (batch.size > sectionStart && previousEnd == baseVertex) { + long countPointer = batch.pElementCount + ((long) (batch.size - 1) << 2); + int mergedCount = LWJGL.memGetInt(countPointer) + elementCount; + + LWJGL.memPutInt(countPointer, mergedCount); + batch.maxElementCount = Math.max(batch.maxElementCount, mergedCount); + } else { + write(batch, baseVertex, elementCount, 0L); + } + + return endVertex; + } + + /** + * Appends a command to the batch and maintains the running maximum element count that + * {@link MultiDrawBatch#getIndexBufferSize()} reports (used to size the shared quad index buffer). + *

+ * Empty commands are effectively discarded. + *

+ * There is no bounds check, since {@link MultiDrawEmitter#MAX_COMMAND_COUNT} already covers the unmerged worst case + * of every facing of every section in a region, and merging only ever reduces the count. + */ + private static void write(MultiDrawBatch batch, int baseVertex, int elementCount, long elementPointer) { + int index = batch.size; + + LWJGL.memPutInt(batch.pBaseVertex + ((long) index << 2), baseVertex); + LWJGL.memPutInt(batch.pElementCount + ((long) index << 2), elementCount); + LWJGL.memPutAddress(batch.pElementPointer + ((long) index << POINTER_SHIFT), elementPointer); + + // Element counts are never negative, so the sign bit of the negation is set iff the command is non-empty. + batch.size = index + ((-elementCount) >>> 31); + + // Safe to apply unconditionally: an empty command cannot raise the maximum. + batch.maxElementCount = Math.max(batch.maxElementCount, elementCount); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/DirectMultiDrawEmitter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/DirectMultiDrawEmitter.java index 83773847e..a1ac92b88 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/DirectMultiDrawEmitter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/DirectMultiDrawEmitter.java @@ -6,60 +6,13 @@ import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; -import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; -import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; - -public record DirectMultiDrawEmitter(MultiDrawBatch batch) implements MultiDrawEmitter { - public DirectMultiDrawEmitter() { - this(new MultiDrawBatch(MAX_COMMAND_COUNT)); - } +public record DirectMultiDrawEmitter() implements MultiDrawEmitter { @Override - @SuppressWarnings("IntegerMultiplicationImplicitCastToLong") - public void addDrawCommands(long pMeshData, int mask, int indexPointerMask) { - var batch = this.batch; - final var pBaseVertex = batch.pBaseVertex; - final var pElementCount = batch.pElementCount; - final var pElementPointer = batch.pElementPointer; - - int size = batch.size; - - for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) { - LWJGL.memPutInt(pBaseVertex + (size << 2), SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing)); - LWJGL.memPutInt(pElementCount + (size << 2), SectionRenderDataUnsafe.getElementCount(pMeshData, facing)); - LWJGL.memPutAddress(pElementPointer + (size << 3), SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask); - - size += (mask >> facing) & 1; - } - - batch.size = size; - } - - @Override - public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) { + public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, + MultiDrawBatch batch) { try (DrawCommandList drawCommandList = commandList.beginTessellating(tessellation)) { drawCommandList.multiDrawElementsBaseVertex(batch, primitiveType, GlIndexType.UNSIGNED_INT); } } - - @Override - public int getIndexBufferSize() { - return this.batch.getIndexBufferSize(); - } - - @Override - public boolean isEmpty() { - return this.batch.isEmpty(); - } - - @Override - public void clear() { - this.batch.clear(); - } - - @Override - public void delete() { - this.batch.delete(); - } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/IndirectMultiDrawEmitter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/IndirectMultiDrawEmitter.java index 946dfb53b..eac9a621d 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/IndirectMultiDrawEmitter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/IndirectMultiDrawEmitter.java @@ -5,11 +5,11 @@ import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage; import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer; import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.DrawCommandList; +import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; -import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; + import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import org.taumc.celeritas.lwjgl.LWJGLServiceProvider; @@ -28,7 +28,6 @@ public class IndirectMultiDrawEmitter implements MultiDrawEmitter { private static final int BUFFER_SIZE = MultiDrawEmitter.MAX_COMMAND_COUNT * COMMAND_SIZE; private final long indirectBuffer; - private int numCommands; private final GlMutableBuffer indirectBufferGpu; public IndirectMultiDrawEmitter() { @@ -50,28 +49,34 @@ public class IndirectMultiDrawEmitter implements MultiDrawEmitter { } } - @Override - public void addDrawCommands(long pMeshData, int facingMask, int indexPointerMask) { - int size = this.numCommands; + /** + * Copies the data out of a MultiDrawBatch assembled for direct multidraw into the indirect buffer that will + * be uploaded to the GPU. + */ + private int buildCommands(MultiDrawBatch batch) { + int numCommands = batch.size; - long basePtr = this.indirectBuffer; + long pBaseVertex = batch.pBaseVertex; + long pElementCount = batch.pElementCount; + long pElementPointer = batch.pElementPointer; - for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) { - long ptr = basePtr + (long)size * COMMAND_SIZE; - LWJGL.memPutInt(ptr + 0L, SectionRenderDataUnsafe.getElementCount(pMeshData, facing)); // count - int indexOffset = SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask; - LWJGL.memPutInt(ptr + 8L, indexOffset / 4); - LWJGL.memPutInt(ptr + 12L, SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing)); // baseVertex + long ptr = this.indirectBuffer; - size += (facingMask >> facing) & 1; + for (int i = 0; i < numCommands; i++) { + LWJGL.memPutInt(ptr + 0L, LWJGL.memGetInt(pElementCount + ((long) i * Integer.BYTES))); // count + LWJGL.memPutInt(ptr + 8L, (int) (LWJGL.memGetAddress(pElementPointer + ((long) i * 8L)) / 4L)); // firstIndex + LWJGL.memPutInt(ptr + 12L, LWJGL.memGetInt(pBaseVertex + ((long) i * Integer.BYTES))); // baseVertex + ptr += COMMAND_SIZE; } - this.numCommands = size; + return numCommands; } @Override - public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) { - commandList.uploadData(this.indirectBufferGpu, this.indirectBuffer, (long)this.numCommands * COMMAND_SIZE, + public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, MultiDrawBatch batch) { + int numCommands = this.buildCommands(batch); + + commandList.uploadData(this.indirectBufferGpu, this.indirectBuffer, (long)numCommands * COMMAND_SIZE, GlBufferUsage.STREAM_DRAW); commandList.bindBuffer(GlBufferTarget.DRAW_INDIRECT_BUFFER, this.indirectBufferGpu); @@ -81,30 +86,6 @@ public class IndirectMultiDrawEmitter implements MultiDrawEmitter { commandList.bindBuffer(GlBufferTarget.DRAW_INDIRECT_BUFFER, null); } - @Override - public boolean isEmpty() { - return this.numCommands == 0; - } - - @Override - public int getIndexBufferSize() { - int elements = 0; - - long pElementCount = this.indirectBuffer; - - for (var index = 0; index < this.numCommands; index++) { - elements = Math.max(elements, LWJGL.memGetInt(pElementCount)); - pElementCount += COMMAND_SIZE; - } - - return elements; - } - - @Override - public void clear() { - this.numCommands = 0; - } - @Override public void delete() { LWJGL.nmemAlignedFree(this.indirectBuffer); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/MultiDrawEmitter.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/MultiDrawEmitter.java index cdeabe399..aafa0aa1a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/MultiDrawEmitter.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/MultiDrawEmitter.java @@ -1,6 +1,7 @@ package org.embeddedt.embeddium.impl.render.chunk.multidraw; import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; @@ -9,10 +10,9 @@ import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; public interface MultiDrawEmitter { int MAX_COMMAND_COUNT = (ModelQuadFacing.COUNT * RenderRegion.REGION_SIZE) + 1; - void addDrawCommands(long pMeshData, int facingMask, int indexPointerMask); - void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType); - boolean isEmpty(); - int getIndexBufferSize(); - void clear(); - void delete(); + void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, MultiDrawBatch batch); + + default void delete() { + + } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java index 63309621f..ef6ca508a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/region/RenderRegion.java @@ -140,7 +140,7 @@ public class RenderRegion { var storage = this.sectionRenderData.get(pass); if (storage == null) { - this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(renderPassConfiguration.getPrimitiveTypeForPass(pass))); + this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(renderPassConfiguration.getPrimitiveTypeForPass(pass), pass.isSorted())); this.passSetUpdateCount++; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/util/iterator/ReversibleByteArrayIterator.java b/common/src/main/java/org/embeddedt/embeddium/impl/util/iterator/ReversibleByteArrayIterator.java deleted file mode 100644 index 15f6d73d9..000000000 --- a/common/src/main/java/org/embeddedt/embeddium/impl/util/iterator/ReversibleByteArrayIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.embeddedt.embeddium.impl.util.iterator; - -import java.util.NoSuchElementException; - - -public class ReversibleByteArrayIterator implements ByteIterator { - private final byte[] elements; - - private final int step; - - private int currentIndex; - private int remaining; - - public ReversibleByteArrayIterator(byte[] elements, int size, boolean reverse) { - this.elements = elements; - this.remaining = size; - - this.step = reverse ? -1 : 1; - this.currentIndex = reverse ? size - 1 : 0; - } - - @Override - public boolean hasNext() { - return this.remaining > 0; - } - - @Override - public int nextByteAsInt() { - if (!this.hasNext()) { - throw new NoSuchElementException(); - } - - int result = Byte.toUnsignedInt(this.elements[this.currentIndex]); - - this.currentIndex += this.step; - this.remaining--; - - return result; - } -}