diff --git a/dependencies.gradle b/dependencies.gradle index 08e9d5af4..b44043aef 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -71,7 +71,8 @@ dependencies { // Iris Shaders compileOnly('org.jetbrains:annotations:26.0.2') - api("com.github.GTNewHorizons:GTNHLib:0.9.6:dev") + api("com.github.GTNewHorizons:GTNHLib:0.9.9:dev") + shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-26.g5ee7d96-GTNH") { exclude module: "antlr4" // we only want to shadow the runtime module diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java b/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java index a84b19e92..4ab6110d3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java @@ -19,7 +19,7 @@ import static org.lwjgl.opengl.GL11.glEnable; import static org.lwjgl.opengl.GL11.glEnableClientState; import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER; import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; -import static org.lwjgl.opengl.GL15.glBindBuffer; +import static com.gtnewhorizons.angelica.glsm.GLStateManager.glBindBuffer; import static org.lwjgl.opengl.GL15.glBufferData; import static org.lwjgl.opengl.GL15.glGenBuffers; import static org.lwjgl.opengl.GL20.glDisableVertexAttribArray; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/AngelicaGLStateManagerService.java b/src/main/java/com/gtnewhorizons/angelica/glsm/AngelicaGLStateManagerService.java index 770f6029d..c9749dbcb 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/AngelicaGLStateManagerService.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/AngelicaGLStateManagerService.java @@ -171,7 +171,7 @@ public class AngelicaGLStateManagerService implements GLStateManagerService { @Override public void glBindBuffer(int target, int buffer) { - GL15.glBindBuffer(target, buffer); + GLStateManager.glBindBuffer(target, buffer); } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java index eed048ded..d3c86e6c1 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java @@ -1,238 +1,67 @@ package com.gtnewhorizons.angelica.glsm; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer; import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor; -import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor.BufferTransformOptimizer; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import java.util.ArrayList; -import java.util.Comparator; import java.util.List; -import java.util.Map; /** * Builds final command buffers from raw command buffers and compiled VBO data. - * Transforms are already collapsed to MultMatrix during recording; the optimizer - * tracks transform state to emit deltas when draws need a different transform. + * Bridges the gap between VBO compilation (glsm types) and buffer processing (recording types). */ public final class CommandBufferBuilder { - private static final Logger LOGGER = LogManager.getLogger("CommandBufferBuilder"); - private CommandBufferBuilder() {} - /** Build with transform delta optimization and merged draw ranges. */ - public static void buildOptimizedFromRawBuffer( + /** + * Build commands with transform collapsing optimization. + * Accumulates MODELVIEW transforms and emits MultMatrix at barriers (draws, CallList). + * Uses mergedRanges where consecutive same-transform draws are combined. + */ + public static void buildFromRawBuffer( CommandBuffer rawBuffer, - Map compiledQuadBuffers, - final CompiledLineBuffer compiledLineBuffer, - final Map compiledPrimitiveBuffers, - VertexBuffer[] ownedVbos, - int glListId, + List accumulatedDraws, CommandBuffer finalBuffer) { - // Build VBO index map for efficient lookup (no boxing) - final Object2IntMap vboIndexMap = new Object2IntOpenHashMap<>(); - vboIndexMap.defaultReturnValue(-1); - for (int i = 0; i < ownedVbos.length; i++) { - vboIndexMap.put(ownedVbos[i], i); - } - - // Collect all merged draw ranges sorted by command index - final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); - - // Buffer optimizer state - final BufferTransformOptimizer opt = new BufferTransformOptimizer(); - rawBuffer.resetRead(); int cmdIndex = 0; int rangeIndex = 0; + AccumulatedDraw draw; while (rawBuffer.hasRemaining()) { - // Emit draw ranges at this command position - while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) { - emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap); - } - // Read and process the command - final int opcode = rawBuffer.readInt(); - CommandBufferProcessor.processCommandForOptimization(opcode, rawBuffer, opt, finalBuffer); - cmdIndex++; - } - - // Emit remaining draw ranges at end of command stream - while (rangeIndex < allRanges.size()) { - emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap); - } - - // Emit residual transform if not identity - if (!opt.isIdentity()) { - opt.emitPendingTransform(finalBuffer); - } - } - - /** Debug build: no optimizations, 1:1 draw commands. */ - public static void buildUnoptimizedFromRawBuffer( - CommandBuffer rawBuffer, - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers, - VertexBuffer[] ownedVbos, - CommandBuffer finalBuffer) { - - // Build VBO index map for efficient lookup (no boxing) - final Object2IntMap vboIndexMap = new Object2IntOpenHashMap<>(); - vboIndexMap.defaultReturnValue(-1); - for (int i = 0; i < ownedVbos.length; i++) { - vboIndexMap.put(ownedVbos[i], i); - } - - // Collect per-draw ranges (no merging) sorted by command index - final List allRanges = collectDrawRangesUnoptimized(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); - - rawBuffer.resetRead(); - int cmdIndex = 0; - int rangeIndex = 0; - - while (rawBuffer.hasRemaining()) { - // Emit draw ranges at this command position - while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) { - final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++); - final int vboIdx = vboIndexMap.getInt(drb.vbo()); - if (vboIdx >= 0) { - finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness()); - DisplayListManager.trackDrawRangeSource(drb.source().toString()); - } - } - - // Copy the command directly CommandBufferProcessor.copyCommand(rawBuffer, finalBuffer); + + // Emit draw ranges at this command position + while (rangeIndex < accumulatedDraws.size() && (draw = accumulatedDraws.get(rangeIndex)).commandIndex == cmdIndex) { + emitDrawRangeToBuffer(draw, finalBuffer, rangeIndex); + rangeIndex++; + } + cmdIndex++; } - // Emit remaining draw ranges at end of command stream - while (rangeIndex < allRanges.size()) { - final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++); - final int vboIdx = vboIndexMap.getInt(drb.vbo()); - if (vboIdx >= 0) { - finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness()); - DisplayListManager.trackDrawRangeSource(drb.source().toString()); - } + while (rangeIndex < accumulatedDraws.size()) { + emitDrawRangeToBuffer(accumulatedDraws.get(rangeIndex), finalBuffer, rangeIndex); + rangeIndex++; } } - /** Collect merged draw ranges, sorted by command index. */ - static List collectDrawRanges( - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers) { - return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, true); - } - - /** Collect unmerged draw ranges for debug mode. */ - static List collectDrawRangesUnoptimized( - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers) { - return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, false); - } - - private static List collectDrawRangesInternal( - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers, - boolean useMerged) { - - final List allRanges = new ArrayList<>(); - - // Add quad ranges - final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]); - for (int b = 0; b < quadBufferArray.length; b++) { - final CompiledFormatBuffer compiledBuffer = quadBufferArray[b]; - final DrawRange[] ranges = useMerged ? compiledBuffer.mergedRanges() : compiledBuffer.perDrawRanges(); - for (int i = 0; i < ranges.length; i++) { - allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags(), - DrawRangeWithBuffer.DrawSource.TESSELLATOR_QUADS)); - } - } - - // Add immediate mode line ranges - // Lines use a minimal flags (color only, no texture/brightness/normals) - if (compiledLineBuffer != null) { - final CapturingTessellator.Flags lineFlags = new CapturingTessellator.Flags(false, false, true, false); - final DrawRange[] ranges = useMerged ? compiledLineBuffer.mergedRanges() : compiledLineBuffer.perDrawRanges(); - for (int i = 0; i < ranges.length; i++) { - allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), lineFlags, - DrawRangeWithBuffer.DrawSource.IMMEDIATE_MODE_LINES)); - } - } - - // Add tessellator primitive ranges (lines and triangles) - grouped by format - if (compiledPrimitiveBuffers != null && !compiledPrimitiveBuffers.isEmpty()) { - final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]); - for (int p = 0; p < primBufferArray.length; p++) { - final CompiledPrimitiveBuffers primBuffers = primBufferArray[p]; - final CapturingTessellator.Flags primFlags = primBuffers.flags(); - // Tessellator lines - if (primBuffers.hasLines()) { - final DrawRange[] ranges = useMerged ? primBuffers.lineMergedRanges() : primBuffers.linePerDrawRanges(); - final VertexBuffer vbo = primBuffers.lineVbo(); - for (int i = 0; i < ranges.length; i++) { - allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags, - DrawRangeWithBuffer.DrawSource.TESSELLATOR_LINES)); - } - } - // Tessellator triangles - if (primBuffers.hasTriangles()) { - final DrawRange[] ranges = useMerged ? primBuffers.triangleMergedRanges() : primBuffers.trianglePerDrawRanges(); - final VertexBuffer vbo = primBuffers.triangleVbo(); - for (int i = 0; i < ranges.length; i++) { - allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags, - DrawRangeWithBuffer.DrawSource.TESSELLATOR_TRIANGLES)); - } - } - } - } - - allRanges.sort(Comparator.comparingInt(r -> r.range().commandIndex())); - return allRanges; - } - - /** Emit draw range with delta transform. Uses writeDrawRangeRestore for immediate mode. */ + /** + * Emit a draw range to the output buffer, with transform if needed. + */ private static void emitDrawRangeToBuffer( - DrawRangeWithBuffer drb, - BufferTransformOptimizer opt, + AccumulatedDraw draw, CommandBuffer out, - Object2IntMap vboIndexMap) { + int vboIdx) { - // Emit transform to reach the draw's expected transform - opt.emitTransformTo(out, drb.range().transform()); + if (draw.restoreData != null) { + out.writeDrawRangeRestore(vboIdx, draw.restoreData); + return; + } // Write the draw range command - final int vboIdx = vboIndexMap.getInt(drb.vbo()); - if (vboIdx >= 0) { - final var restoreData = drb.range().restoreData(); - if (restoreData != null) { - // Immediate mode draw with attribute restoration - final var flags = drb.flags(); - out.writeDrawRangeRestore( - vboIdx, drb.range().startVertex(), drb.range().vertexCount(), - drb.hasBrightness(), flags.hasColor, flags.hasNormals, flags.hasTexture, - restoreData.lastColorR(), restoreData.lastColorG(), - restoreData.lastColorB(), restoreData.lastColorA(), - restoreData.lastNormalX(), restoreData.lastNormalY(), restoreData.lastNormalZ(), - restoreData.lastTexCoordS(), restoreData.lastTexCoordT() - ); - } else { - // Regular tessellator draw (no restoration needed) - out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness()); - } - DisplayListManager.trackDrawRangeSource(drb.source().toString()); - } + out.writeDrawRange(vboIdx); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java deleted file mode 100644 index a97d23012..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; - -/** - * A compiled VBO with its associated draw ranges. - * All ranges reference vertices within this single VBO. - *

- * Contains two range arrays: - *

    - *
  • mergedRanges: For optimized path - consecutive same-transform draws merged
  • - *
  • perDrawRanges: For unoptimized path - 1:1 with original draws
  • - *
- */ -@Desugar -public record CompiledFormatBuffer( - VertexBuffer vbo, - CapturingTessellator.Flags flags, - DrawRange[] mergedRanges, - DrawRange[] perDrawRanges -) {} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java deleted file mode 100644 index d5244a17c..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; - -/** - * A compiled VBO containing all line geometry with associated draw ranges. - * All ranges reference vertices within this single VBO. - *

- * Contains two range arrays: - *

    - *
  • mergedRanges: For optimized path - consecutive same-transform draws merged
  • - *
  • perDrawRanges: For unoptimized path - 1:1 with original draws
  • - *
- */ -@Desugar -public record CompiledLineBuffer( - VertexBuffer vbo, - DrawRange[] mergedRanges, - DrawRange[] perDrawRanges -) {} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java deleted file mode 100644 index 596cac9ee..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; - -/** - * Compiled VBOs containing tessellator primitives (lines and triangles) for a single vertex format. - * Separate VBOs are used for lines (GL_LINES) and triangles (GL_TRIANGLES) since they have different draw modes. - *

- * Contains range arrays for both optimized (merged) and unoptimized (per-draw) paths. - * Similar to CompiledFormatBuffer but handles primitives instead of quads. - */ -@Desugar -public record CompiledPrimitiveBuffers( - CapturingTessellator.Flags flags, - VertexBuffer lineVbo, - DrawRange[] lineMergedRanges, - DrawRange[] linePerDrawRanges, - VertexBuffer triangleVbo, - DrawRange[] triangleMergedRanges, - DrawRange[] trianglePerDrawRanges -) { - public boolean hasLines() { - return lineVbo != null; - } - - public boolean hasTriangles() { - return triangleVbo != null; - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java index c64a7dd1a..4ca3174f6 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java @@ -1,26 +1,20 @@ package com.gtnewhorizons.angelica.glsm; import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VBOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer; import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; +import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBO; +import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBOBuilder; import com.gtnewhorizons.angelica.glsm.recording.GLCommand; -import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; -import com.gtnewhorizons.angelica.glsm.recording.commands.OptimizationContext; -import com.gtnewhorizons.angelica.glsm.GLDebug; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import lombok.Getter; @@ -38,9 +32,9 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; -import java.util.HashMap; import java.util.List; -import java.util.Map; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; /** * VBO-based display list emulation with command recording, transform collapsing, and format-based batching. @@ -49,8 +43,8 @@ import java.util.Map; * emitted at barriers (draws, CallList, exit). Vertices stay canonical in VBOs. Handles nested * display lists correctly and maintains Push/Pop semantics. * - *

Format-Based Batching: Draws with same vertex format share a VBO via {@link FormatBuffer}. - * Each draw's position is tracked as a {@link DrawRange}. Consecutive same-transform draws merge. + *

Format-Based Batching: Draws with same vertex format share a VBO via {@link DisplayListVBO}. + * Consecutive same-transform draws merge. * Delta transforms handled via {@link TransformOptimizer}. */ @UtilityClass @@ -92,28 +86,16 @@ public class DisplayListManager { // Display list compilation state (current/active context) private static int glListMode = 0; private static int glListId = -1; - private static boolean tessellatorCompiling = false; // Track if we started compiling private static CommandRecorder currentRecorder = null; // Command recorder (null when not recording) private static volatile Thread recordingThread = null; // Thread that started recording (for thread-safety) private static List accumulatedDraws = null; // Accumulates quad draws for batching - private static List accumulatedLineDraws = null; // Accumulates immediate mode line draws - private static List accumulatedPrimitiveDraws = null; // Accumulates tessellator primitive draws (lines, triangles) - private static Matrix4fStack relativeTransform = null; // Tracks delta from current GL state (reset to I after each flush) - /** - * -- GETTER -- - * Get the current matrix generation (for draw batching). - */ - @Getter - private static int matrixGeneration = 0; // Increments when relativeTransform changes; used for draw batching - private static int lastFlushedGeneration = -1; // Generation at last flush; draws trigger flush when gen changes + private static Matrix4fStack relativeTransform = null; // Tracks relative transforms during compilation (with push/pop support) /** * -- GETTER -- * Get the current state generation (for draw merging). */ @Getter private static int stateGeneration = 0; // Increments at draw barriers (state commands); used for draw merging - private static Matrix4f lastFlushedTransform = null; // The transform that was flushed; consecutive same-gen draws share this - @Getter private static ImmediateModeRecorder immediateModeRecorder = null; // Records glBegin/glEnd/glVertex during compilation private static StackTraceElement[] compilationStackTrace = null; // For logging: captured at glNewList() // Debug logging: track sources of MULT_MATRIX commands and draw origins; only populated when LOG_DISPLAY_LIST_COMPILATION is true @@ -140,11 +122,7 @@ public class DisplayListManager { int listMode, CommandRecorder recorder, List draws, - List lineDraws, - List primitiveDraws, Matrix4fStack transform, - boolean wasTessellatorCompiling, - ImmediateModeRecorder immediateRecorder, StackTraceElement[] stackTrace, // Debug logging fields (only used when LOG_DISPLAY_LIST_COMPILATION) @@ -169,16 +147,19 @@ public class DisplayListManager { return glListMode == GL11.GL_COMPILE_AND_EXECUTE; } - /** Emit accumulated transform as MultMatrix if non-identity, then reset. */ - public static boolean flushMatrix() { + /** + * Emit accumulated transform as MultMatrix if non-identity, then reset. + */ + public static void flushMatrix() { if (relativeTransform == null || isIdentity(relativeTransform)) { // Clear pending ops even if we don't emit - they were no-ops (identity) if (pendingTransformOps != null) { pendingTransformOps.clear(); } - return false; + return; } + // Save pending transform ops for logging (before we clear them) if (multMatrixSources != null && pendingTransformOps != null) { if (pendingTransformOps.isEmpty()) { @@ -193,6 +174,7 @@ public class DisplayListManager { // Record the collapsed MultMatrix command (for playback) if (currentRecorder != null) { currentRecorder.recordMultMatrix(relativeTransform); + stateGeneration++; } // COMPILE_AND_EXECUTE: execute now. Bypass GLSM to avoid re-entering recording path. @@ -206,7 +188,6 @@ public class DisplayListManager { // Reset to identity - we're now synchronized with GL relativeTransform.identity(); - return true; } public static void matrixBarrier() { @@ -232,7 +213,7 @@ public class DisplayListManager { } // Draw barriers: state commands that prevent draw merging - private static void drawBarrier() { + static void drawBarrier() { stateGeneration++; } @@ -369,8 +350,6 @@ public class DisplayListManager { // Flush any pending delta, then record pop. flushMatrix(); currentRecorder.recordPopMatrix(); - // Invalidate cached transform - matrixGeneration++; } public static void recordViewport(int x, int y, int width, int height) { @@ -592,6 +571,18 @@ public class DisplayListManager { if (currentRecorder != null) currentRecorder.recordLoadIdentity(); } + public static void recordDrawArrays(int mode, int start, int count) { + if (currentRecorder != null) currentRecorder.recordDrawArrays(mode, start, count); + } + + public static void recordDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { + if (currentRecorder != null) currentRecorder.recordDrawElements(mode, indices_count, type, indices_buffer_offset); + } + + public static void recordBindVBO(int vbo) { if (currentRecorder != null) currentRecorder.recordBindVBO(vbo); } + public static void recordBindVAO(int vao) { if (currentRecorder != null) currentRecorder.recordBindVAO(vao); } + + // recordOrtho/recordFrustum removed - these now accumulate into relativeTransform // via updateRelativeTransformOrtho/updateRelativeTransformFrustum @@ -603,51 +594,13 @@ public class DisplayListManager { * an AccumulatedDraw that will be interleaved correctly with other commands * during display list playback. * - * @param result The immediate mode result containing quads, lines, and flags */ - public static void addImmediateModeDraw(ImmediateModeRecorder.Result result) { - if (accumulatedDraws == null || result == null) { - return; - } - - if (matrixGeneration != lastFlushedGeneration) { - if (lastFlushedTransform == null) { - lastFlushedTransform = new Matrix4f(); - } - lastFlushedTransform.set(relativeTransform); - flushMatrix(); - lastFlushedGeneration = matrixGeneration; - } - - final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform); - final int currentGeneration = matrixGeneration; - final int currentBatchId = stateGeneration; - final int cmdIndex = getCommandCount(); - - if (!result.quads().isEmpty()) { - final var flags = result.flags(); - final AccumulatedDraw.RestoreData restoreData; - if (flags.hasColor || flags.hasNormals || flags.hasTexture) { - restoreData = new AccumulatedDraw.RestoreData( - result.lastColorR(), result.lastColorG(), result.lastColorB(), result.lastColorA(), - result.lastNormalX(), result.lastNormalY(), result.lastNormalZ(), - result.lastTexCoordS(), result.lastTexCoordT() - ); - } else { - restoreData = null; // Position-only draw, no attributes to restore - } - final AccumulatedDraw quadDraw = new AccumulatedDraw( - result.quads(), currentTransform, flags, - cmdIndex, currentGeneration, currentBatchId, restoreData - ); - accumulatedDraws.add(quadDraw); - } - - // Add line draw if we have lines - if (!result.lines().isEmpty()) { - final AccumulatedLineDraw lineDraw = new AccumulatedLineDraw(result.lines(), currentTransform, result.flags(), getCommandCount(), currentBatchId); - accumulatedLineDraws.add(lineDraw); + public static void addImmediateModeDraw(DirectTessellator tessellator) { + if (!tessellator.isEmpty()) { + // Get relative transform (changes since glNewList, not absolute matrix state) + addAccumulatedDraw(tessellator, tessellator.getVertexFormat() != DefaultVertexFormat.POSITION); } + tessellator.reset(); } private static void applyTransformOp(Matrix4f m, float x, float y, float z, TransformOp op, Vector3f axis) { @@ -675,7 +628,6 @@ public class DisplayListManager { } applyTransformOp(relativeTransform, x, y, z, op, rotationAxis); - matrixGeneration++; if (pendingTransformOps != null) { final String log = switch (op) { @@ -716,7 +668,6 @@ public class DisplayListManager { } relativeTransform.mul(matrix); - matrixGeneration++; if (pendingTransformOps != null) { pendingTransformOps.add("glMultMatrixf(...)"); @@ -744,7 +695,6 @@ public class DisplayListManager { } relativeTransform.mul(orthoFrustumTemp); - matrixGeneration++; if (pendingTransformOps != null) { pendingTransformOps.add(String.format("glOrtho(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } @@ -768,7 +718,6 @@ public class DisplayListManager { } relativeTransform.mul(orthoFrustumTemp); - matrixGeneration++; if (pendingTransformOps != null) { pendingTransformOps.add(String.format("glFrustum(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } @@ -821,11 +770,6 @@ public class DisplayListManager { * GL_COMPILE_AND_EXECUTE: Commands are recorded AND executed (GLSM cache updated) */ public static void glNewList(int list, int mode) { - // Assert main thread for display list compilation - if (!Thread.currentThread().equals(GLStateManager.getMainThread())) { - throw new IllegalStateException("Display list compilation must happen on main thread"); - } - // Handle nested compilation - push current context onto stack final boolean isNested = glListMode > 0; @@ -833,10 +777,8 @@ public class DisplayListManager { // Nested display list compilation violates OpenGL spec, but some of our optimizations require it // Save current compilation context and start fresh for nested list final CompilationContext parentContext = new CompilationContext( - glListId, glListMode, currentRecorder, accumulatedDraws, accumulatedLineDraws, - accumulatedPrimitiveDraws, relativeTransform, - tessellatorCompiling, immediateModeRecorder, compilationStackTrace, - pendingTransformOps, multMatrixSources, drawRangeSources + glListId, glListMode, currentRecorder, accumulatedDraws, relativeTransform, + compilationStackTrace, pendingTransformOps, multMatrixSources, drawRangeSources ); compilationStack.push(parentContext); } @@ -846,15 +788,9 @@ public class DisplayListManager { glListMode = mode; recordingThread = Thread.currentThread(); // Track which thread is recording currentRecorder = new CommandRecorder(); // Create command recorder - accumulatedDraws = new ArrayList<>(64); // Fewer draws than commands typically - accumulatedLineDraws = new ArrayList<>(16); // Immediate mode line draws are less common - accumulatedPrimitiveDraws = new ArrayList<>(16); // Tessellator primitive draws are less common + accumulatedDraws = new ArrayList<>(16); // Fewer draws than commands typically relativeTransform = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH); - relativeTransform.identity(); // Delta from current GL state, starts at identity - lastFlushedGeneration = -1; // Reset so first draw triggers flush - lastFlushedTransform = null; // Will be set on first flush stateGeneration = 0; // Reset state generation for fresh list - immediateModeRecorder = new ImmediateModeRecorder(); // For glBegin/glEnd/glVertex compilationStackTrace = LOG_DISPLAY_LIST_COMPILATION ? Thread.currentThread().getStackTrace() : null; // Initialize debug logging fields (only when logging enabled) @@ -868,44 +804,12 @@ public class DisplayListManager { drawRangeSources = null; } - // Start compiling mode with per-draw callback (works for both root and nested lists now) - // Callback receives quads (GL_QUADS) and primitives (GL_TRIANGLES, GL_LINES, etc.) - TessellatorManager.setCompiling((quads, primitives, flags) -> { - final boolean hasQuads = !quads.isEmpty(); - final boolean hasPrimitives = !primitives.isEmpty(); - - // Early exit to avoid allocations when nothing to accumulate - if (!hasQuads && !hasPrimitives) { - return; - } - - if (matrixGeneration != lastFlushedGeneration) { - if (lastFlushedTransform == null) { - lastFlushedTransform = new Matrix4f(); - } - lastFlushedTransform.set(relativeTransform); - flushMatrix(); - lastFlushedGeneration = matrixGeneration; - } - - final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform); - final int currentGeneration = matrixGeneration; - final int currentBatchId = stateGeneration; - final int cmdIndex = getCommandCount(); - - // Accumulate quads for batching at glEndList() - if (hasQuads) { - accumulatedDraws.add(new AccumulatedDraw(quads, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId)); - } - - // Accumulate primitives (lines, triangles) for batching at glEndList() - if (hasPrimitives) { - accumulatedPrimitiveDraws.add(new AccumulatedPrimitiveDraw(primitives, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId)); + TessellatorManager.startCapturingDirect((tessellator) -> { + if (!tessellator.isEmpty()) { + addAccumulatedDraw(tessellator, false); } + return true; }); - tessellatorCompiling = true; - - // We hijack display list compilation completely - no GL11.glNewList() calls } /** @@ -919,44 +823,26 @@ public class DisplayListManager { final boolean isNested = !compilationStack.isEmpty(); // Stop compiling mode (works for both root and nested lists now) - if (tessellatorCompiling) { - TessellatorManager.stopCompiling(); - tessellatorCompiling = false; - } + TessellatorManager.stopCapturingDirect(); final CompiledDisplayList compiled; // Create CompiledDisplayList with both unoptimized and optimized versions - final CommandBuffer rawCommandBuffer = currentRecorder != null ? currentRecorder.getBuffer() : null; - final boolean hasCommands = rawCommandBuffer != null && rawCommandBuffer.size() > 0; + final CommandBuffer rawCommandBuffer = currentRecorder.getBuffer(); + final boolean hasCommands = !rawCommandBuffer.isEmpty(); final boolean hasDraws = accumulatedDraws != null && !accumulatedDraws.isEmpty(); - final boolean hasLineDraws = accumulatedLineDraws != null && !accumulatedLineDraws.isEmpty(); - final boolean hasPrimitiveDraws = accumulatedPrimitiveDraws != null && !accumulatedPrimitiveDraws.isEmpty(); - if (hasCommands || hasDraws || hasLineDraws || hasPrimitiveDraws) { + if (hasCommands || hasDraws) { // Phase 1: Compile format-based VBOs (shared by both optimized and unoptimized paths) - final Map compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws); - - // Phase 2: Compile immediate mode line VBO (shared by both paths) - final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws); - - // Phase 3: Compile tessellator primitive VBOs (lines, triangles) - grouped by format - final Map compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws); - - // Collect all owned VBOs (quads + immediate mode lines + tessellator primitives) - final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); + final DisplayListVBO compiledBuffers = new DisplayListVBOBuilder().addDraws(accumulatedDraws).build(); // Build to CommandBuffer - optimize raw buffer to final buffer final CommandBuffer finalBuffer = new CommandBuffer(); - if (DEBUG_DISPLAY_LISTS) { - CommandBufferBuilder.buildUnoptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, finalBuffer); - } else { - CommandBufferBuilder.buildOptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, glListId, finalBuffer); - } + CommandBufferBuilder.buildFromRawBuffer(rawCommandBuffer, accumulatedDraws, finalBuffer); // Free the recorder (and its buffer) after optimization currentRecorder.free(); - compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), ownedVbos); + compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), compiledBuffers); } else { // Free the recorder even if empty if (currentRecorder != null) { @@ -982,11 +868,7 @@ public class DisplayListManager { glListMode = parentContext.listMode; currentRecorder = parentContext.recorder; accumulatedDraws = parentContext.draws; - accumulatedLineDraws = parentContext.lineDraws; - accumulatedPrimitiveDraws = parentContext.primitiveDraws; relativeTransform = parentContext.transform; - tessellatorCompiling = parentContext.wasTessellatorCompiling; - immediateModeRecorder = parentContext.immediateRecorder; compilationStackTrace = parentContext.stackTrace; pendingTransformOps = parentContext.pendingOps; multMatrixSources = parentContext.matrixSources; @@ -999,10 +881,7 @@ public class DisplayListManager { currentRecorder = null; recordingThread = null; accumulatedDraws = null; - accumulatedLineDraws = null; - accumulatedPrimitiveDraws = null; relativeTransform = null; - immediateModeRecorder = null; compilationStackTrace = null; pendingTransformOps = null; multMatrixSources = null; @@ -1012,6 +891,31 @@ public class DisplayListManager { } } + private static void addAccumulatedDraw(DirectTessellator tessellator, boolean copyLast) { + final int cmdIndex = getCommandCount(); + matrixBarrier(); + + if (accumulatedDraws.isEmpty()) { + accumulatedDraws.add( + new AccumulatedDraw( + tessellator, cmdIndex, stateGeneration, copyLast + ) + ); + return; + } + + // Merge the previous draw call if possible + final AccumulatedDraw previous = accumulatedDraws.get(accumulatedDraws.size() - 1); + if (previous.format == tessellator.getVertexFormat() && previous.stateGeneration == stateGeneration) { + previous.mergeDraw(tessellator, copyLast); + return; + } + + accumulatedDraws.add( + new AccumulatedDraw(tessellator, cmdIndex, stateGeneration, copyLast) + ); + } + /** * Execute a compiled display list. */ @@ -1067,326 +971,19 @@ public class DisplayListManager { CompiledDisplayList compiled = displayListCache.remove(i); if (compiled != null) { compiled.delete(); + } else { + GL11.glDeleteLists(i, 1); } } - // Also call legacy glDeleteLists for any lists we didn't handle - GL11.glDeleteLists(list, range); - } - - /** - * Compile format-based VBOs from accumulated draws. - * Groups draws by vertex format and compiles each format's geometry into a single VBO. - * Both optimized and unoptimized paths share these VBOs. - * - * @param accumulatedDraws The accumulated draws to compile - * @return Map from format flags to compiled buffers (VBO + ranges) - */ - private static Map compileFormatBasedVBOs( - List accumulatedDraws) { - if (accumulatedDraws == null || accumulatedDraws.isEmpty()) { - return Collections.emptyMap(); - } - - // Group draws by vertex format - final Map formatBuffers = new HashMap<>(); - for (AccumulatedDraw draw : accumulatedDraws) { - formatBuffers.computeIfAbsent(draw.flags, FormatBuffer::new).addDraw(draw); - } - - // Compile each format's geometry into a single VBO - final Map compiled = new HashMap<>(); - for (var entry : formatBuffers.entrySet()) { - compiled.put(entry.getKey(), entry.getValue().finish()); - } - return compiled; - } - - /** - * Compile line draws into a shared VBO. - * - * @param lineDraws The accumulated line draws - * @return Compiled line buffer, or null if no lines - */ - private static CompiledLineBuffer compileLineBuffer(List lineDraws) { - if (lineDraws == null || lineDraws.isEmpty()) { - return null; - } - - final LineBuffer buffer = new LineBuffer(); - for (AccumulatedLineDraw draw : lineDraws) { - buffer.addDraw(draw); - } - return buffer.finish(); - } - - /** - * Extract owned VBOs from compiled buffers (quads + lines). - * These VBOs are shared by both optimized and unoptimized paths. - * - * @param compiledQuadBuffers The compiled quad format buffers - * @param compiledLineBuffer The compiled line buffer (may be null) - * @return Array of VBOs that need to be deleted when the display list is deleted - */ - private static VertexBuffer[] extractOwnedVbos( - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers) { - final List vbos = new ArrayList<>(); - - // Add quad VBOs - final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]); - for (int i = 0; i < quadBufferArray.length; i++) { - vbos.add(quadBufferArray[i].vbo()); - } - - // Add immediate mode line VBO if present - if (compiledLineBuffer != null) { - vbos.add(compiledLineBuffer.vbo()); - } - - // Add tessellator primitive VBOs if present (one per format, separate for lines/triangles) - if (!compiledPrimitiveBuffers.isEmpty()) { - final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]); - for (int i = 0; i < primBufferArray.length; i++) { - final CompiledPrimitiveBuffers primBuffers = primBufferArray[i]; - if (primBuffers.hasLines()) { - vbos.add(primBuffers.lineVbo()); - } - if (primBuffers.hasTriangles()) { - vbos.add(primBuffers.triangleVbo()); - } - } - } - - return vbos.toArray(new VertexBuffer[0]); - } - - /** - * Compile tessellator primitives (lines, triangles) into format-based VBOs. - * Groups draws by vertex format for optimal memory usage. - * - * @param primitiveDraws The accumulated primitive draws from tessellator callback - * @return Map of flags to compiled primitive buffers, empty map if no primitives - */ - private static Map compilePrimitiveBuffers( - List primitiveDraws) { - if (primitiveDraws == null || primitiveDraws.isEmpty()) { - return Collections.emptyMap(); - } - - // Group draws by vertex format - final Map formatBuffers = new HashMap<>(); - final int size = primitiveDraws.size(); - for (int i = 0; i < size; i++) { - final AccumulatedPrimitiveDraw draw = primitiveDraws.get(i); - formatBuffers.computeIfAbsent(draw.flags, TessellatorPrimitiveBuffer::new).addDraw(draw); - } - - // Compile each format's geometry into VBOs - final Map compiled = new HashMap<>(); - @SuppressWarnings("unchecked") - final Map.Entry[] entries = - formatBuffers.entrySet().toArray(new Map.Entry[0]); - for (int i = 0; i < entries.length; i++) { - final Map.Entry entry = entries[i]; - final CompiledPrimitiveBuffers result = entry.getValue().finish(); - if (result != null) { - compiled.put(entry.getKey(), result); - } - } - return compiled; - } - - // ==================== Buffer-to-Buffer Optimization ==================== - /** - * Build optimized command list using pre-compiled VBOs. - * Uses mergedRanges (consecutive same-transform draws combined) and collapses MODELVIEW transforms. - * (Package-private for testing) - * - * @param currentCommands Original matrix/state commands - * @param compiledQuadBuffers Pre-compiled format-based quad VBOs - * @param compiledLineBuffer Pre-compiled line VBO (may be null) - * @param glListId Display list ID for logging - * @return Optimized command array - */ - static DisplayListCommand[] buildOptimizedCommands( - List currentCommands, - Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, - Map compiledPrimitiveBuffers, - int glListId) { - - final List optimized = new ArrayList<>(); - final TransformOptimizer transformOpt = new TransformOptimizer(glListId); - - // Collect all merged draw ranges (quads + lines + primitives) sorted by command index - final List allRanges = CommandBufferBuilder.collectDrawRanges( - compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); - - // Process command stream with interleaved draws - final OptimizationContextImpl ctx = new OptimizationContextImpl(transformOpt, optimized); - - int rangeIndex = 0; - for (int i = 0; i < currentCommands.size(); i++) { - // Emit draw ranges (quads and lines) at this command position - while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == i) { - emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized); - } - - // Process the original command - final DisplayListCommand cmd = currentCommands.get(i); - if (cmd.handleOptimization(ctx)) { - optimized.add(cmd); - } - } - - // Emit remaining draw ranges at end of command stream - while (rangeIndex < allRanges.size()) { - emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized); - } - - // Emit residual transform to match expected GL state - if (!transformOpt.isIdentity()) { - transformOpt.emitPendingTransform(optimized); - } - - return optimized.toArray(new DisplayListCommand[0]); - } - - /** - * Build optimized display list: batches draws with same flags, collapses MODELVIEW transforms. - * Instead of baking transforms into vertices, we emit collapsed MultMatrix commands at barriers. - * This properly handles nested display lists (CallList) which need GL state to be correct. - * - *

Transform collapsing strategy: - *

    - *
  • Track accumulated MODELVIEW transform during command stream analysis
  • - *
  • At barriers (Draw, CallList), emit a single MultMatrix if transform changed
  • - *
  • Push/Pop maintain proper stack semantics
  • - *
  • Vertices stay canonical (untransformed) in VBOs
  • - *
- */ - // Package-private for testing - static OptimizedListResult buildOptimizedDisplayList( - List currentCommands, - List accumulatedDraws, - List accumulatedPrimitiveDraws, - int glListId) { - // Compile quad VBOs - final Map compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws); - - // Compile tessellator primitive VBOs (lines, triangles) - grouped by format - final Map compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws); - - // Extract owned VBOs (quads + primitives, no immediate mode lines in test path) - final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, null, compiledPrimitiveBuffers); - - // Build optimized commands using the new unified path - final DisplayListCommand[] optimized = buildOptimizedCommands(currentCommands, compiledQuadBuffers, null, compiledPrimitiveBuffers, glListId); - - return new OptimizedListResult(optimized, ownedVbos); - } - - /** - * Emit a draw range command for the legacy path (testing). - * Uses delta-based transform emission via TransformOptimizer. - */ - private static void emitDrawRangeLegacy(DrawRangeWithBuffer drwb, TransformOptimizer transformOpt, - List output) { - final DrawRange range = drwb.range(); - - // Delta-based: only emit MultMatrix if transform differs from last emitted - if (transformOpt.needsTransformForDraw(range.transform())) { - transformOpt.emitTransformTo(output, range.transform()); - } - - output.add(new com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd( - drwb.vbo(), - range.startVertex(), - range.vertexCount(), - drwb.hasBrightness() - )); - } - - /** - * Implementation of OptimizationContext that wraps transform optimizer. - */ - @Desugar - private record OptimizationContextImpl( - TransformOptimizer transformOpt, - List output - ) implements OptimizationContext { - @Override public Matrix4f getAccumulatedTransform() { return transformOpt.getAccumulated(); } - @Override public void loadIdentity() { transformOpt.loadIdentity(); } - @Override public void pushTransform() { transformOpt.pushTransform(); } - @Override public void popTransform() { transformOpt.popTransform(); } - @Override public void emitPendingTransform() { transformOpt.emitPendingTransform(output); } - @Override public void emitTransformTo(Matrix4f target) { transformOpt.emitTransformTo(output, target); } - @Override public void emit(DisplayListCommand cmd) { output.add(cmd); } - @Override public void markAbsoluteMatrix() { transformOpt.markAbsoluteMatrix(); } - @Override public boolean checkAndClearAbsoluteMatrix() { return transformOpt.checkAndClearAbsoluteMatrix(); } - } - - - /** - * Selects the optimal VertexFormat from GTNHLib defaults based on actual attribute usage. - * This reduces memory usage by excluding unused attributes. - */ - static VertexFormat selectOptimalFormat(CapturingTessellator.Flags flags) { - final boolean hasColor = flags.hasColor; - final boolean hasTexture = flags.hasTexture; - final boolean hasBrightness = flags.hasBrightness; - final boolean hasNormals = flags.hasNormals; - - final VertexFormat format; - - // Map flags to GTNHLib formats, ordered by guess at frequency/likelihood - if (!hasColor && hasTexture && !hasBrightness && !hasNormals) { - format = DefaultVertexFormat.POSITION_TEXTURE; // Entity models, common - } else if (!hasColor && !hasTexture && !hasBrightness && !hasNormals) { - format = DefaultVertexFormat.POSITION; // Sky rendering, simple geometry - } else if (hasColor && hasTexture && !hasBrightness && !hasNormals) { - format = DefaultVertexFormat.POSITION_COLOR_TEXTURE; // Colored blocks/UI - } else if (!hasColor && hasTexture && hasBrightness && hasNormals) { - format = DefaultVertexFormat.POSITION_TEXTURE_LIGHT_NORMAL; // BuildCraft fluids - } else if (!hasColor && hasTexture && !hasBrightness && hasNormals) { - format = DefaultVertexFormat.POSITION_TEXTURE_NORMAL; // Lit geometry with normals - } else if (hasColor && hasTexture && hasBrightness && !hasNormals) { - format = DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP; // Colored lit blocks - } else if (hasColor && !hasTexture && !hasBrightness && !hasNormals) { - format = DefaultVertexFormat.POSITION_COLOR; // Colored lines/particles - } else { - format = DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL; // Full format fallback - } - - return format; - } - - /** - * Compile captured Tessellator quads into a VertexBuffer (VAO or VBO). - * Uses VertexBuffer for proper compatibility with fixed-function pipeline. - * - * @param quads The quads to compile - * @param flags The vertex attribute flags - * @return The uploaded VertexBuffer - */ - static VertexBuffer compileQuads(List quads, CapturingTessellator.Flags flags) { - // Select optimal predefined format from GTNHLib - final VertexFormat format = selectOptimalFormat(flags); - - // Use VAOManager to create VAO with optimal format (falls back to VBO if unsupported) - final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_QUADS); - - final ByteBuffer buffer = CapturingTessellator.quadsToBuffer(quads, format); - - vao.upload(buffer); - - return vao; } // ==================== DEBUG LOGGING ==================== - private static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) { + public static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) { + LOGGER.debug(getCompiledDisplayListString(listId, compiled, stackTrace)); + } + + public static String getCompiledDisplayListString(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) { final StringBuilder sb = new StringBuilder(); sb.append("\n========== Display List Compiled: ID=").append(listId).append(" ==========\n"); @@ -1402,7 +999,7 @@ public class DisplayListManager { sb.append("Contents: No commands\n"); } else { sb.append("Commands (").append(buffer.limit()).append(" bytes):\n"); - dumpCommandBuffer(buffer, compiled.getComplexObjects(), compiled.getOwnedVbos(), sb); + dumpCommandBuffer(buffer, compiled.getComplexObjects(), sb); } } @@ -1417,7 +1014,7 @@ public class DisplayListManager { } sb.append("========== End Display List ").append(listId).append(" ==========\n"); - LOGGER.debug(sb.toString()); + return sb.toString(); } private static String identifySourceFromStackTrace(StackTraceElement[] stackTrace) { @@ -1498,143 +1095,97 @@ public class DisplayListManager { return className; } - private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos, StringBuilder sb) { + private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, StringBuilder sb) { if (buffer == null) return; - final long basePtr = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress(buffer); + final long basePtr = memAddress(buffer); long ptr = basePtr; final long end = basePtr + buffer.limit(); int cmdNum = 0; - int multMatrixIdx = 0; // Index into multMatrixSources for source tracking int drawRangeIdx = 0; // Index into drawRangeSources for source tracking while (ptr < end) { - final int opcode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr); + final int opcode = memGetInt(ptr); final String cmdName = GLCommand.getName(opcode); sb.append(" ").append(cmdNum++).append(": ").append(cmdName); // Add command-specific details switch (opcode) { case GLCommand.ENABLE, GLCommand.DISABLE -> { - final int cap = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); + final int cap = memGetInt(ptr + 4); sb.append("(").append(GLDebug.getCapabilityName(cap)).append(")"); - ptr += 8; } case GLCommand.BIND_TEXTURE -> { - final int target = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); - final int texture = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8); + final int target = memGetInt(ptr + 4); + final int texture = memGetInt(ptr + 8); sb.append("(target=").append(target).append(", texture=").append(texture).append(")"); - ptr += 12; } case GLCommand.DRAW_RANGE -> { - final int vboIdx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); - final int start = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8); - final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12); - final int brightness = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16); - sb.append("(vbo=").append(vboIdx).append(", start=").append(start) - .append(", count=").append(count).append(", brightness=").append(brightness != 0).append(")"); + final int vboIdx = memGetInt(ptr + 4); + sb.append("(vbo=").append(vboIdx).append(")"); + // Show draw source if available + if (drawRangeSources != null && drawRangeIdx < drawRangeSources.size()) { + sb.append(" [from: ").append(drawRangeSources.get(drawRangeIdx)).append("]"); + } + drawRangeIdx++; + } + case GLCommand.DRAW_RANGE_RESTORE -> { + final int vboIdx = memGetInt(ptr + 4); + final int start = memGetInt(ptr + 8); + final int count = memGetInt(ptr + 12); + final int brightness = memGetInt(ptr + 16); + sb.append("(vbo=").append(vboIdx).append(", start=").append(start) + .append(", count=").append(count).append(", brightness=").append(brightness != 0).append(")"); // Show draw source if available if (drawRangeSources != null && drawRangeIdx < drawRangeSources.size()) { sb.append(" [from: ").append(drawRangeSources.get(drawRangeIdx)).append("]"); } drawRangeIdx++; - ptr += 20; } case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> { - // Show source ops if available (only for MULT_MATRIX from recording phase) - if (opcode == GLCommand.MULT_MATRIX && multMatrixSources != null && multMatrixIdx < multMatrixSources.size()) { - final List sources = multMatrixSources.get(multMatrixIdx); - sb.append(" [from: ").append(String.join(" -> ", sources)).append("]"); + sb.append("("); + for (int i = 0; i < 16; i++) { + float value = MemoryUtilities.memGetFloat(ptr + 4 + i * 4); + sb.append(i == 0 ? value : ", " + value); } - multMatrixIdx++; - ptr += 68; // cmd + 16 floats + sb.append(")"); } case GLCommand.COLOR -> { - final float r = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4)); - final float g = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8)); - final float b = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12)); - final float a = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16)); + final float r = Float.intBitsToFloat(memGetInt(ptr + 4)); + final float g = Float.intBitsToFloat(memGetInt(ptr + 8)); + final float b = Float.intBitsToFloat(memGetInt(ptr + 12)); + final float a = Float.intBitsToFloat(memGetInt(ptr + 16)); sb.append("(").append(r).append(", ").append(g).append(", ").append(b).append(", ").append(a).append(")"); - ptr += 20; } case GLCommand.DEPTH_MASK -> { - final int flag = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); + final int flag = memGetInt(ptr + 4); sb.append("(").append(flag != 0).append(")"); - ptr += 8; } case GLCommand.BLEND_FUNC -> { - final int srcRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); - final int dstRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8); - final int srcAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12); - final int dstAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16); + final int srcRgb = memGetInt(ptr + 4); + final int dstRgb = memGetInt(ptr + 8); + final int srcAlpha = memGetInt(ptr + 12); + final int dstAlpha = memGetInt(ptr + 16); sb.append("(srcRgb=").append(srcRgb).append(", dstRgb=").append(dstRgb) .append(", srcAlpha=").append(srcAlpha).append(", dstAlpha=").append(dstAlpha).append(")"); - ptr += 20; } case GLCommand.CALL_LIST -> { - final int calledList = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); + final int calledList = memGetInt(ptr + 4); sb.append("(").append(calledList).append(")"); - ptr += 8; } case GLCommand.MATRIX_MODE -> { - final int mode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); + final int mode = memGetInt(ptr + 4); sb.append("(").append(mode == GL11.GL_MODELVIEW ? "MODELVIEW" : mode == GL11.GL_PROJECTION ? "PROJECTION" : mode).append(")"); - ptr += 8; } - case GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.LOAD_IDENTITY -> ptr += 4; case GLCommand.COMPLEX_REF -> { - final int idx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4); + final int idx = memGetInt(ptr + 4); final Object obj = complexObjects != null && idx < complexObjects.length ? complexObjects[idx] : null; sb.append("(idx=").append(idx).append(", type=").append(obj != null ? obj.getClass().getSimpleName() : "null").append(")"); - ptr += 8; - } - default -> { - // Skip based on command size (from CompiledDisplayList.getCommandSize logic) - ptr += getCommandSize(opcode, ptr); } } + ptr += GLCommand.getCommandSize(opcode, ptr); sb.append("\n"); } } - /** - * Get the size of a command in bytes for buffer iteration. - */ - private static int getCommandSize(int cmd, long ptr) { - return switch (cmd) { - case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4; - case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL, - GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP, - GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM, - GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK, - GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, - GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_BUFFER -> 8; - case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL, - GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI, - GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, - GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI, GLCommand.CLEAR_DEPTH -> 12; - case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI, - GLCommand.LIGHTF, GLCommand.LIGHTI, GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF, - GLCommand.NORMAL -> 16; - case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK, - GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE, - GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR, - GLCommand.DRAW_RANGE -> 20; - case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; - case GLCommand.ROTATE -> 36; - case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; - case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; - case GLCommand.FOG, GLCommand.LIGHT_MODEL -> { - final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8); - yield 12 + count * 4; - } - case GLCommand.LIGHT, GLCommand.MATERIAL -> { - final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12); - yield 16 + count * 4; - } - case GLCommand.DRAW_BUFFERS -> 40; - default -> 8; // Default to 8 bytes to avoid infinite loop - }; - } - } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRange.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRange.java deleted file mode 100644 index 504affc81..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRange.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import org.joml.Matrix4f; - -/** - * Represents a vertex range within a shared VBO, along with its transform. - * Used during format-based batching to track where each draw's vertices are stored. - * - *

The restoreData field holds last vertex attributes for GL state restoration - * after VBO rendering (immediate mode draws only). Null for tessellator draws. - */ -@Desugar -public record DrawRange( - int startVertex, - int vertexCount, - Matrix4f transform, - int commandIndex, - AccumulatedDraw.RestoreData restoreData -) { - DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) { - this(startVertex, vertexCount, transform, commandIndex, null); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRangeWithBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRangeWithBuffer.java deleted file mode 100644 index 86941e015..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRangeWithBuffer.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; - -/** - * Helper record pairing a DrawRange with its VBO and vertex format flags. - * Used for sorting ranges by command index while retaining VBO reference. - * Works for both quad ranges (from CompiledFormatBuffer) and line ranges (from CompiledLineBuffer). - */ -@Desugar -record DrawRangeWithBuffer( - DrawRange range, - VertexBuffer vbo, - CapturingTessellator.Flags flags, - DrawSource source -) { - boolean hasBrightness() { - return flags != null && flags.hasBrightness; - } - - /** - * Source of a draw command for debug logging. - */ - enum DrawSource { - TESSELLATOR_QUADS("tessellator quads"), - TESSELLATOR_LINES("tessellator lines"), - TESSELLATOR_TRIANGLES("tessellator triangles"), - IMMEDIATE_MODE_LINES("immediate mode lines"); - - private final String description; - - DrawSource(String description) { - this.description = description; - } - - @Override - public String toString() { - return description; - } - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/FormatBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/FormatBuffer.java deleted file mode 100644 index 4ace6129c..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/FormatBuffer.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import org.joml.Matrix4f; - -import java.util.ArrayList; -import java.util.List; - -/** - * Accumulates geometry for a single vertex format during display list compilation. - * Tracks merged ranges (same-transform draws combined) and per-draw ranges (1:1). - */ -class FormatBuffer { - final CapturingTessellator.Flags flags; - final List allQuads = new ArrayList<>(); - - // Merged ranges for optimized path (consecutive same-transform draws combined) - final List mergedRanges = new ArrayList<>(); - - // Per-draw ranges for unoptimized path (1:1 with input draws) - final List perDrawRanges = new ArrayList<>(); - - int currentVertexOffset = 0; - - // Track the current range being built for merging consecutive same-transform draws - private int pendingStartVertex = -1; - private int pendingVertexCount = 0; - private Matrix4f pendingTransform = null; - private int pendingCommandIndex = -1; - private int pendingGeneration = -1; - private int pendingStateGen = -1; - // Track last restore data for merged draws (uses the LAST draw's data) - private AccumulatedDraw.RestoreData pendingRestoreData = null; - - FormatBuffer(CapturingTessellator.Flags flags) { - this.flags = flags; - } - - /** Add a draw, tracking both merged and per-draw ranges. */ - void addDraw(AccumulatedDraw draw) { - final int vertexCount = draw.quads.size() * 4; // 4 vertices per quad - - // Always track per-draw range for unoptimized path (includes restoreData) - perDrawRanges.add(new DrawRange( - currentVertexOffset, vertexCount, draw.transform, draw.commandIndex, draw.restoreData - )); - - // Merge logic for optimized path: - // - same matrixGeneration = same matrix transform context - // - same stateGeneration = no state commands (draw barriers) between draws - boolean canMerge = pendingGeneration != -1 - && pendingGeneration == draw.matrixGeneration - && pendingStateGen == draw.stateGeneration; - - if (canMerge) { - // Extend the pending range - pendingVertexCount += vertexCount; - // Update restoreData to the LAST draw's data (used after merged draw completes) - pendingRestoreData = draw.restoreData; - } else { - // Flush pending range if any - flushPendingRange(); - - // Start new pending range - pendingStartVertex = currentVertexOffset; - pendingVertexCount = vertexCount; - pendingTransform = new Matrix4f(draw.transform); - pendingCommandIndex = draw.commandIndex; - pendingGeneration = draw.matrixGeneration; - pendingStateGen = draw.stateGeneration; - pendingRestoreData = draw.restoreData; - } - - allQuads.addAll(draw.quads); - currentVertexOffset += vertexCount; - } - - private void flushPendingRange() { - if (pendingGeneration != -1) { - mergedRanges.add(new DrawRange( - pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex, pendingRestoreData - )); - pendingTransform = null; - pendingGeneration = -1; - pendingStateGen = -1; - pendingRestoreData = null; - } - } - - /** Compile accumulated quads into a VBO. */ - CompiledFormatBuffer finish() { - // Flush any remaining pending range - flushPendingRange(); - - VertexBuffer vbo = DisplayListManager.compileQuads(allQuads, flags); - return new CompiledFormatBuffer( - vbo, - flags, - mergedRanges.toArray(new DrawRange[0]), - perDrawRanges.toArray(new DrawRange[0]) - ); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index 5d73d5446..7fc378c0c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -1,8 +1,10 @@ package com.gtnewhorizons.angelica.glsm; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode; +import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import com.gtnewhorizons.angelica.glsm.recording.commands.TexImage2DCmd; @@ -23,7 +25,6 @@ import com.gtnewhorizons.angelica.glsm.stacks.MatrixModeStack; import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack; import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack; import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack; -import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack; import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack; import com.gtnewhorizons.angelica.glsm.states.ClientArrayState; import com.gtnewhorizons.angelica.glsm.states.Color4; @@ -57,14 +58,17 @@ import org.joml.Vector3d; import org.joml.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; +import org.lwjgl.opengl.APPLEVertexArrayObject; import org.lwjgl.opengl.ARBMultitexture; import org.lwjgl.opengl.ContextCapabilities; +import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Drawable; import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.Display; @@ -89,6 +93,8 @@ import static com.gtnewhorizons.angelica.glsm.Vendor.MESA; import static com.gtnewhorizons.angelica.glsm.Vendor.NVIDIA; import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; +import static com.gtnewhorizon.gtnhlib.client.opengl.GLCaps.*; + /** * OpenGL State Manager - Provides cached state tracking and management for OpenGL operations. * @@ -331,6 +337,9 @@ public class GLStateManager { @Getter protected static int activeProgram = 0; @Getter protected static int listBase = 0; + @Getter protected static int boundVBO; + @Getter protected static int boundVAO; + public static void reset() { runningSplash = true; while(!attribs.isEmpty()) { @@ -812,15 +821,21 @@ public class GLStateManager { case GL11.GL_MATRIX_MODE -> matrixMode.getMode(); case GL11.GL_SHADE_MODEL -> shadeModelState.getValue(); case GL11.GL_TEXTURE_BINDING_2D -> getBoundTextureForServerState(); + case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue(); + case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue(); + case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix); + case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix); + case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha(); case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb(); case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha(); case GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb(); - case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue(); - case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue(); + + case GL15.GL_ARRAY_BUFFER_BINDING -> boundVBO; + case GL20.GL_CURRENT_PROGRAM -> activeProgram; - case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix); - case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix); + + case GL30.GL_VERTEX_ARRAY_BINDING -> boundVAO; default -> GL11.glGetInteger(pname); }; @@ -1064,42 +1079,34 @@ public class GLStateManager { throw new UnsupportedOperationException("Not yet implemented (" + name + ")"); } } + + // Records glBegin/glEnd/glVertex and compiles them to a VBO + // Currently only used inside of display lists + public static void glNormal3b(byte nx, byte ny, byte nz) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setNormal(b2f(nx), b2f(ny), b2f(nz)); - } + ImmediateModeRecorder.setNormal(b2f(nx), b2f(ny), b2f(nz)); return; } GL11.glNormal3b(nx, ny, nz); } public static void glNormal3d(double nx, double ny, double nz) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setNormal((float) nx, (float) ny, (float) nz); - } + ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz); return; } GL11.glNormal3d(nx, ny, nz); } public static void glNormal3f(float nx, float ny, float nz) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setNormal(nx, ny, nz); - } + ImmediateModeRecorder.setNormal(nx, ny, nz); return; } GL11.glNormal3f(nx, ny, nz); } public static void glNormal3i(int nx, int ny, int nz) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setNormal((float) nx, (float) ny, (float) nz); - } + ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz); return; } GL11.glNormal3i(nx, ny, nz); @@ -1535,80 +1542,56 @@ public class GLStateManager { public static void glTexCoord1f(float s) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord(s, 0.0f); - } + ImmediateModeRecorder.setTexCoord(s, 0.0f); return; } GL11.glTexCoord1f(s); } public static void glTexCoord1d(double s) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord((float) s, 0.0f); - } + ImmediateModeRecorder.setTexCoord((float) s, 0.0f); return; } GL11.glTexCoord1d(s); } public static void glTexCoord2f(float s, float t) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord(s, t); - } + ImmediateModeRecorder.setTexCoord(s, t); return; } GL11.glTexCoord2f(s, t); } public static void glTexCoord2d(double s, double t) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord((float) s, (float) t); - } + ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } GL11.glTexCoord2d(s, t); } public static void glTexCoord3f(float s, float t, float r) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord(s, t); // Only track s,t for 2D textures - } + ImmediateModeRecorder.setTexCoord(s, t); // Only track s,t for 2D textures return; } GL11.glTexCoord3f(s, t, r); } public static void glTexCoord3d(double s, double t, double r) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord((float) s, (float) t); - } + ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } GL11.glTexCoord3d(s, t, r); } public static void glTexCoord4f(float s, float t, float r, float q) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord(s, t); - } + ImmediateModeRecorder.setTexCoord(s, t); return; } GL11.glTexCoord4f(s, t, r, q); } public static void glTexCoord4d(double s, double t, double r, double q) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.setTexCoord((float) s, (float) t); - } + ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } GL11.glTexCoord4d(s, t, r, q); @@ -1748,10 +1731,7 @@ public class GLStateManager { public static void glBegin(int mode) { if (DisplayListManager.isRecording()) { // Record to immediate mode recorder - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.begin(mode); - } + ImmediateModeRecorder.begin(mode); return; // Don't call actual GL during recording } GL11.glBegin(mode); @@ -1760,14 +1740,10 @@ public class GLStateManager { public static void glEnd() { if (DisplayListManager.isRecording()) { // Record to immediate mode recorder and flush geometry immediately - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - // end() returns quads immediately (like tessellator callback) - final ImmediateModeRecorder.Result result = recorder.end(); - if (result != null) { - // Add draw at current command position for correct interleaving - DisplayListManager.addImmediateModeDraw(result); - } + final DirectTessellator result = ImmediateModeRecorder.end(); + if (result != null) { + // Add draw at current command position for correct interleaving + DisplayListManager.addImmediateModeDraw(result); } return; // Don't call actual GL during recording } @@ -1779,10 +1755,7 @@ public class GLStateManager { public static void glVertex2f(float x, float y) { final boolean recording = DisplayListManager.isRecording(); if (recording) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.vertex(x, y, 0.0f); - } + ImmediateModeRecorder.vertex(x, y, 0.0f); return; } GL11.glVertex2f(x, y); @@ -1790,10 +1763,7 @@ public class GLStateManager { public static void glVertex2d(double x, double y) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.vertex((float) x, (float) y, 0.0f); - } + ImmediateModeRecorder.vertex((float) x, (float) y, 0.0f); return; } GL11.glVertex2d(x, y); @@ -1801,10 +1771,7 @@ public class GLStateManager { public static void glVertex3f(float x, float y, float z) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.vertex(x, y, z); - } + ImmediateModeRecorder.vertex(x, y, z); return; } GL11.glVertex3f(x, y, z); @@ -1812,10 +1779,7 @@ public class GLStateManager { public static void glVertex3d(double x, double y, double z) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - recorder.vertex((float) x, (float) y, (float) z); - } + ImmediateModeRecorder.vertex((float) x, (float) y, (float) z); return; } GL11.glVertex3d(x, y, z); @@ -1841,13 +1805,6 @@ public class GLStateManager { GL11.glDrawElements(mode, indices); } - public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); - } - GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset); - } - public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); @@ -1855,6 +1812,21 @@ public class GLStateManager { GL11.glDrawElements(mode, count, type, indices); } + public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { + if (isVAOBound()) { + DisplayListManager.recordDrawElements(mode, indices_count, type, indices_buffer_offset); + } else { + throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); + } + if (recordMode == RecordMode.COMPILE) { + return; + } + } + GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset); + } + public static void glDrawBuffer(int mode) { final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -1868,12 +1840,13 @@ public class GLStateManager { public static void glDrawArrays(int mode, int first, int count) { if (DisplayListManager.isRecording()) { - final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder(); - if (recorder != null) { - final ImmediateModeRecorder.Result result = recorder.processDrawArrays(mode, first, count); - if (result != null) { - DisplayListManager.addImmediateModeDraw(result); - } + if (isVAOBound() || isVBOBound()) { // TODO VBO rendering needs to be replaced with proper VAO compilation + DisplayListManager.recordDrawArrays(mode, first, count); + return; + } + final DirectTessellator result = ImmediateModeRecorder.processDrawArrays(mode, first, count); + if (result != null) { + DisplayListManager.addImmediateModeDraw(result); } return; } @@ -1884,52 +1857,70 @@ public class GLStateManager { // State is tracked globally in clientArrayState, which ImmediateModeRecorder reads from directly. public static void glVertexPointer(int size, int stride, FloatBuffer pointer) { - clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer); + if (!isVAOBound()) { + clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer); + } GL11.glVertexPointer(size, stride, pointer); } public static void glVertexPointer(int size, int type, int stride, ByteBuffer pointer) { - clientArrayState.setVertexPointer(size, type, stride, pointer); + if (!isVAOBound()) { + clientArrayState.setVertexPointer(size, type, stride, pointer); + } GL11.glVertexPointer(size, type, stride, pointer); } public static void glVertexPointer(int size, int type, int stride, long pointer_buffer_offset) { - // VBO offset - can't track buffer reference, clear it - clientArrayState.setVertexPointer(size, type, stride, null); + if (!isVAOBound()) { + // VBO offset - can't track buffer reference, clear it + clientArrayState.setVertexPointer(size, type, stride, null); + } GL11.glVertexPointer(size, type, stride, pointer_buffer_offset); } public static void glColorPointer(int size, int stride, FloatBuffer pointer) { - clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer); + if (!isVAOBound()) { + clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer); + } GL11.glColorPointer(size, stride, pointer); } public static void glColorPointer(int size, int type, int stride, ByteBuffer pointer) { - clientArrayState.setColorPointer(size, type, stride, pointer); + if (!isVAOBound()) { + clientArrayState.setColorPointer(size, type, stride, pointer); + } GL11.glColorPointer(size, type, stride, pointer); } public static void glColorPointer(int size, boolean unsigned, int stride, ByteBuffer pointer) { - final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE; - clientArrayState.setColorPointer(size, type, stride, pointer); + if (!isVAOBound()) { + final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE; + clientArrayState.setColorPointer(size, type, stride, pointer); + } GL11.glColorPointer(size, unsigned, stride, pointer); } public static void glColorPointer(int size, int type, int stride, long pointer_buffer_offset) { - // VBO offset - can't track buffer reference, clear it - clientArrayState.setColorPointer(size, type, stride, null); + if (!isVAOBound()) { + // VBO offset - can't track buffer reference, clear it + clientArrayState.setColorPointer(size, type, stride, null); + } GL11.glColorPointer(size, type, stride, pointer_buffer_offset); } public static void glEnableClientState(int cap) { - if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true); - else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true); + if (!isVAOBound()) { + if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true); + else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true); + } GL11.glEnableClientState(cap); } public static void glDisableClientState(int cap) { - if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false); - else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false); + if (!isVAOBound()) { + if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false); + else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false); + } GL11.glDisableClientState(cap); } @@ -2816,7 +2807,7 @@ public class GLStateManager { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexParameteri called during display list recording with no cached TextureInfo for texture %d. " + - "Cannot query OpenGL state during compilation!", texture)); + "Cannot query OpenGL state during compilation!", texture)); } return defaultSupplier.getAsInt(); } @@ -2832,7 +2823,7 @@ public class GLStateManager { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexParameteri called during display list recording with uncached pname 0x%s for texture %d. " + - "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture)); + "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture)); } yield defaultSupplier.getAsInt(); } @@ -3771,6 +3762,46 @@ public class GLStateManager { } } + public static void glBindBuffer(int target, int buffer) { + if (target == GL15.GL_ARRAY_BUFFER) { + // if (boundVBO == buffer) return; TODO figure out why this breaks switching async occlusion mode + boundVBO = buffer; + } + GL15.glBindBuffer(target, buffer); + } + + public static void glBindVertexArray(int array) { + if (DisplayListManager.isRecording()) { + DisplayListManager.recordBindVAO(array); + // Since the vao needs to be bound to do stuff like state setup & data upload, it'll still execute the bind call. + // This is technically wrong, but I'm not sure if there's a better solution here. + } + if (boundVAO != array) { + boundVAO = array; + GL30.glBindVertexArray(array); + } + } + + public static void glBindVertexArrayAPPLE(int array) { + if (DisplayListManager.isRecording()) { + DisplayListManager.recordBindVAO(array); + // Since the vao needs to be bound to do stuff like state setup & data upload, it'll still execute the bind call. + // This is technically wrong, but I'm not sure if there's a better solution here. + } + if (boundVAO != array) { + boundVAO = array; + APPLEVertexArrayObject.glBindVertexArrayAPPLE(array); + } + } + + public static boolean isVBOBound() { + return boundVBO != 0; + } + + public static boolean isVAOBound() { + return boundVAO != 0; + } + public static boolean vendorIsAMD() { return VENDOR == AMD; } @@ -3835,6 +3866,12 @@ public class GLStateManager { } } + private static void checkMismatch(int cap) { + if (GLStateManager.glGetInteger(cap) != GL11.glGetInteger(cap)) { + throw new IllegalStateException("GLSM Mismatch! Cached: " + GLStateManager.glGetInteger(cap) + ", actual: " + GL11.glGetInteger(cap)); + } + } + public static boolean isFramebufferEnabled() { return OpenGlHelper.framebufferSupported && Minecraft.getMinecraft().gameSettings.fboEnable; } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java deleted file mode 100644 index 3228fbdbe..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw; -import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -/** - * Accumulates line geometry during display list compilation. - * All line draws are collected here, then compiled into a single VBO. - *

- * Lines all use the same format (POSITION_COLOR), so no format-based grouping needed. - *

- * Tracks two types of ranges: - *

    - *
  • mergedRanges: Consecutive same-transform draws merged for optimized path
  • - *
  • perDrawRanges: One range per input draw for unoptimized path (1:1 with addDraw calls)
  • - *
- */ -class LineBuffer { - final List allVertices = new ArrayList<>(); - - // Merged ranges for optimized path (consecutive same-transform draws combined) - final List mergedRanges = new ArrayList<>(); - - // Per-draw ranges for unoptimized path (1:1 with input draws) - final List perDrawRanges = new ArrayList<>(); - - int currentVertexOffset = 0; - - // Track the current range being built for merging consecutive same-transform draws - private int pendingStartVertex = -1; - private int pendingVertexCount = 0; - private Matrix4f pendingTransform = null; - private int pendingCommandIndex = -1; - private int pendingStateGen = -1; - - /** - * Add a line draw to this buffer. - * Tracks both merged (for optimized) and per-draw (for unoptimized) ranges. - */ - void addDraw(AccumulatedLineDraw draw) { - int vertexCount = draw.lines.size(); // Each LineVertex is one vertex, lines come in pairs - - // Always track per-draw range for unoptimized path - perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex)); - - // Merge logic for optimized path: - // - same transform - // - same stateGeneration = no state commands (draw barriers) between draws - boolean canMerge = pendingTransform != null - && pendingTransform.equals(draw.transform) - && pendingStateGen == draw.stateGeneration; - - if (canMerge) { - // Extend the pending range - pendingVertexCount += vertexCount; - } else { - // Flush pending range if any - flushPendingRange(); - - // Start new pending range - pendingStartVertex = currentVertexOffset; - pendingVertexCount = vertexCount; - pendingTransform = new Matrix4f(draw.transform); - pendingCommandIndex = draw.commandIndex; - pendingStateGen = draw.stateGeneration; - } - - allVertices.addAll(draw.lines); - currentVertexOffset += vertexCount; - } - - private void flushPendingRange() { - if (pendingTransform != null) { - mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex)); - pendingTransform = null; - pendingStateGen = -1; - } - } - - /** - * Compile all accumulated line vertices into a single VBO. - * @return The compiled buffer with VBO and both range types, or null if empty - */ - CompiledLineBuffer finish() { - if (allVertices.isEmpty()) { - return null; - } - - // Flush any remaining pending range - flushPendingRange(); - - VertexBuffer vbo = compileLinesToVBO(allVertices); - return new CompiledLineBuffer( - vbo, - mergedRanges.toArray(new DrawRange[0]), - perDrawRanges.toArray(new DrawRange[0]) - ); - } - - /** - * Compile line vertices into a VertexBuffer (VAO or VBO). - * Lines use POSITION_COLOR format (x, y, z, color). - */ - private static VertexBuffer compileLinesToVBO(List lines) { - final VertexFormat format = DefaultVertexFormat.POSITION_COLOR; - final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_LINES); - - // POSITION_COLOR format: 3 floats (12 bytes) + 4 bytes color = 16 bytes per vertex - final int vertexSize = format.getVertexSize(); - final ByteBuffer buffer = org.lwjgl.BufferUtils.createByteBuffer(vertexSize * lines.size()); - - for (ImmediateModeRecorder.LineVertex v : lines) { - buffer.putFloat(v.x); - buffer.putFloat(v.y); - buffer.putFloat(v.z); - buffer.putInt(v.color); - } - buffer.flip(); - - vao.upload(buffer); - - return vao; - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/OptimizedListResult.java b/src/main/java/com/gtnewhorizons/angelica/glsm/OptimizedListResult.java deleted file mode 100644 index f001fb653..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/OptimizedListResult.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; - -/** - * Result of building an optimized display list. - * Contains both the commands and the shared VBOs that need lifecycle management. - */ -@Desugar -record OptimizedListResult(DisplayListCommand[] commands, VertexBuffer[] ownedVbos) {} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java b/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java index 5a2bef0ac..ef060bdfd 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java @@ -332,7 +332,7 @@ public class RenderSystem { } public static void bindBuffer(int target, int buffer) { - GL15.glBindBuffer(target, buffer); + GLStateManager.glBindBuffer(target, buffer); } public static void memoryBarrier(int barriers) { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java deleted file mode 100644 index 5e2c64500..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; -import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; -import org.joml.Matrix4f; -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -/** - * Accumulates tessellator primitives (lines, triangles) for a single vertex format during display list compilation. - * Similar to FormatBuffer but handles ModelPrimitiveView instances instead of quads. - *

- * Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color), - * this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size. - *

- * Primitives are separated by draw mode (GL_LINES, GL_TRIANGLES) into separate VBOs. - */ -class TessellatorPrimitiveBuffer { - final CapturingTessellator.Flags flags; - - // Accumulated primitives separated by type - final List allLines = new ArrayList<>(); - final List allTriangles = new ArrayList<>(); - - // Ranges for lines - final List lineMergedRanges = new ArrayList<>(); - final List linePerDrawRanges = new ArrayList<>(); - int currentLineVertexOffset = 0; - private int pendingLineStartVertex = -1; - private int pendingLineVertexCount = 0; - private Matrix4f pendingLineTransform = null; - private int pendingLineCommandIndex = -1; - private int pendingLineStateGen = -1; - - // Ranges for triangles - final List triangleMergedRanges = new ArrayList<>(); - final List trianglePerDrawRanges = new ArrayList<>(); - int currentTriangleVertexOffset = 0; - private int pendingTriangleStartVertex = -1; - private int pendingTriangleVertexCount = 0; - private Matrix4f pendingTriangleTransform = null; - private int pendingTriangleCommandIndex = -1; - private int pendingTriangleStateGen = -1; - - TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) { - this.flags = flags; - } - - /** - * Add a primitive draw to this buffer. - * Separates lines and triangles, tracking ranges for both merged and per-draw paths. - */ - void addDraw(AccumulatedPrimitiveDraw draw) { - final List primitives = draw.primitives; - final int size = primitives.size(); - - // Single pass: count and collect primitives by type - int lineCount = 0; - int triangleCount = 0; - for (int i = 0; i < size; i++) { - final ModelPrimitiveView prim = primitives.get(i); - if (prim instanceof ModelLine ml) { - allLines.add(ml); - lineCount++; - } else if (prim instanceof ModelTriangle mt) { - allTriangles.add(mt); - triangleCount++; - } - } - - // Process lines - if (lineCount > 0) { - final int lineVertexCount = lineCount * 2; // 2 vertices per line - linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex)); - - // Merge logic for optimized path: - // - same transform - // - same stateGeneration = no state commands (draw barriers) between draws - boolean canMerge = pendingLineTransform != null - && pendingLineTransform.equals(draw.transform) - && pendingLineStateGen == draw.stateGeneration; - - if (canMerge) { - pendingLineVertexCount += lineVertexCount; - } else { - flushPendingLineRange(); - pendingLineStartVertex = currentLineVertexOffset; - pendingLineVertexCount = lineVertexCount; - pendingLineTransform = new Matrix4f(draw.transform); - pendingLineCommandIndex = draw.commandIndex; - pendingLineStateGen = draw.stateGeneration; - } - currentLineVertexOffset += lineVertexCount; - } - - // Process triangles - if (triangleCount > 0) { - final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle - trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex)); - - // Merge logic for optimized path: - // - same transform - // - same stateGeneration = no state commands (draw barriers) between draws - boolean canMerge = pendingTriangleTransform != null - && pendingTriangleTransform.equals(draw.transform) - && pendingTriangleStateGen == draw.stateGeneration; - - if (canMerge) { - pendingTriangleVertexCount += triangleVertexCount; - } else { - flushPendingTriangleRange(); - pendingTriangleStartVertex = currentTriangleVertexOffset; - pendingTriangleVertexCount = triangleVertexCount; - pendingTriangleTransform = new Matrix4f(draw.transform); - pendingTriangleCommandIndex = draw.commandIndex; - pendingTriangleStateGen = draw.stateGeneration; - } - currentTriangleVertexOffset += triangleVertexCount; - } - } - - private void flushPendingLineRange() { - if (pendingLineTransform != null) { - lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex)); - pendingLineTransform = null; - pendingLineStateGen = -1; - } - } - - private void flushPendingTriangleRange() { - if (pendingTriangleTransform != null) { - triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex)); - pendingTriangleTransform = null; - pendingTriangleStateGen = -1; - } - } - - /** - * Compile all accumulated primitives into VBOs using optimal vertex format. - * @return The compiled buffers with separate VBOs for lines and triangles, or null if empty - */ - CompiledPrimitiveBuffers finish() { - flushPendingLineRange(); - flushPendingTriangleRange(); - - if (allLines.isEmpty() && allTriangles.isEmpty()) { - return null; - } - - // Use optimal format based on flags (same logic as quads) - final VertexFormat format = DisplayListManager.selectOptimalFormat(flags); - - final VertexBuffer lineVbo = allLines.isEmpty() ? null : compileLinesToVBO(format); - final VertexBuffer triangleVbo = allTriangles.isEmpty() ? null : compileTrianglesToVBO(format); - - return new CompiledPrimitiveBuffers( - flags, - lineVbo, - lineMergedRanges.toArray(new DrawRange[0]), - linePerDrawRanges.toArray(new DrawRange[0]), - triangleVbo, - triangleMergedRanges.toArray(new DrawRange[0]), - trianglePerDrawRanges.toArray(new DrawRange[0]) - ); - } - - private VertexBuffer compileLinesToVBO(VertexFormat format) { - final int vertexSize = format.getVertexSize(); - final int size = allLines.size(); - final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 2); - - for (int i = 0; i < size; i++) { - writePrimitiveToBuffer(allLines.get(i), buffer); - } - buffer.flip(); - - final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_LINES); - vbo.upload(buffer); - return vbo; - } - - private VertexBuffer compileTrianglesToVBO(VertexFormat format) { - final int vertexSize = format.getVertexSize(); - final int size = allTriangles.size(); - final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 3); - - for (int i = 0; i < size; i++) { - writePrimitiveToBuffer(allTriangles.get(i), buffer); - } - buffer.flip(); - - final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_TRIANGLES); - vbo.upload(buffer); - return vbo; - } - - /** - * Write a primitive's vertices to the buffer using the format specified by flags. - * Only writes attributes that are present in the format. - */ - private void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer) { - final int vertexCount = prim.getVertexCount(); - final boolean hasTexture = flags.hasTexture; - final boolean hasBrightness = flags.hasBrightness; - final boolean hasColor = flags.hasColor; - final boolean hasNormals = flags.hasNormals; - - for (int i = 0; i < vertexCount; i++) { - // Position (always present) - 12 bytes - buffer.putFloat(prim.getX(i)); - buffer.putFloat(prim.getY(i)); - buffer.putFloat(prim.getZ(i)); - - // Color (4 bytes, ABGR) - if present - if (hasColor) { - buffer.putInt(prim.getColor(i)); - } - - // Texture (2 floats = 8 bytes) - if present - if (hasTexture) { - buffer.putFloat(prim.getTexU(i)); - buffer.putFloat(prim.getTexV(i)); - } - - // Light/Brightness (4 bytes, packed) - if present - if (hasBrightness) { - buffer.putInt(prim.getLight(i)); - } - - // Normal (4 bytes, packed) - if present - if (hasNormals) { - buffer.putInt(prim.getForgeNormal(i)); - } - } - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java index 582b82633..79821dcc3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java @@ -124,9 +124,9 @@ public class DSAUnsupported implements DSAAccess { @Override public int bufferStorage(int target, FloatBuffer data, int usage) { final int buffer = GL15.glGenBuffers(); - GL15.glBindBuffer(target, buffer); + GLStateManager.glBindBuffer(target, buffer); RenderSystem.bufferData(target, data, usage); - GL15.glBindBuffer(target, 0); + GLStateManager.glBindBuffer(target, 0); return buffer; } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java index b028b4db3..ecf2f44a9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java @@ -1,11 +1,10 @@ package com.gtnewhorizons.angelica.glsm.recording; -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; -import org.joml.Matrix4f; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import java.nio.ByteBuffer; +import java.util.ArrayList; import java.util.List; /** @@ -13,54 +12,53 @@ import java.util.List; * Matrix-as-Data Architecture: Stores untransformed vertices + captured matrix. * The matrix will be applied at runtime, not baked into vertices. */ -public class AccumulatedDraw { - public final List quads; - public final Matrix4f transform; - public final CapturingTessellator.Flags flags; +public final class AccumulatedDraw { + public final VertexFormat format; + public final List drawBuffers; + public final int drawMode; public final int commandIndex; // Position in command list for state tracking - public final int matrixGeneration; // For batching: same generation = same transform context - public final int stateGeneration; // Same value = no state commands between draws, can merge + public final int stateGeneration; // Position in command list for state tracking + public RestoreData restoreData; - /** - * Last vertex restoration data for immediate mode draws. - * Null for tessellator draws (no restoration needed). - */ - public final RestoreData restoreData; + public AccumulatedDraw(DirectTessellator tessellator, int commandIndex, int stateGeneration, boolean copyLast) { + this.format = tessellator.getVertexFormat(); + this.drawMode = tessellator.drawMode; + this.drawBuffers = new ArrayList<>(); + this.drawBuffers.add(tessellator.allocateBufferCopy()); + this.commandIndex = commandIndex; + this.stateGeneration = stateGeneration; + + if (copyLast) { + this.restoreData = new RestoreData(tessellator); + } + } + + + public void mergeDraw(DirectTessellator tessellator, boolean copyLast) { + this.drawBuffers.add(tessellator.allocateBufferCopy()); + + if (copyLast) { + this.restoreData = new RestoreData(tessellator); + } + } /** * Holds last vertex attribute values for GL state restoration after VBO draw. * Used to sync GLSM cache with actual GL state after VBO rendering. */ - @Desugar - public record RestoreData( - float lastColorR, float lastColorG, float lastColorB, float lastColorA, - float lastNormalX, float lastNormalY, float lastNormalZ, - float lastTexCoordS, float lastTexCoordT) {} + public static final class RestoreData { + public final int lastColor; + public final int lastNormal; + public final float lastTexCoordU; + public final float lastTexCoordV; + public final int flags; - public AccumulatedDraw(List quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) { - this(quads, transform, flags, commandIndex, matrixGeneration, 0, null); - } - - public AccumulatedDraw(List quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) { - this(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration, null); - } - - public AccumulatedDraw(List quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration, RestoreData restoreData) { - // Deep copy quads - pooled quads are reused after callback - this.quads = ModelQuadUtil.deepCopyQuads(quads); - - this.transform = new Matrix4f(transform); // Snapshot for runtime application - this.flags = flags; - this.commandIndex = commandIndex; - this.matrixGeneration = matrixGeneration; - this.stateGeneration = stateGeneration; - this.restoreData = restoreData; - } - - @Override - public String toString() { - return String.format("AccumulatedDraw[quads=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, flags=C%dT%dL%dN%d, restore=%s]", - quads.size(), commandIndex, matrixGeneration, stateGeneration, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0, - restoreData != null ? "yes" : "no"); + public RestoreData(DirectTessellator tessellator) { + this.lastColor = tessellator.getPackedColor(); + this.lastNormal = tessellator.getPackedNormal(); + this.lastTexCoordU = (float) tessellator.getLastTextureU(); + this.lastTexCoordV = (float) tessellator.getLastTextureV(); + this.flags = tessellator.getVertexFormat().getVertexFlags(); + } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java deleted file mode 100644 index f3c80a0ab..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording; - -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import org.joml.Matrix4f; - -import java.util.ArrayList; -import java.util.List; - -/** - * Represents an accumulated line draw call during display list compilation. - * Similar to AccumulatedDraw but for line primitives. - * Stores untransformed line vertices + captured matrix. - */ -public class AccumulatedLineDraw { - public final List lines; - public final Matrix4f transform; - public final CapturingTessellator.Flags flags; - public final int commandIndex; // Position in command list for state tracking - public final int stateGeneration; // Same value = no state commands between draws, can merge - - public AccumulatedLineDraw(List lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { - this(lines, transform, flags, commandIndex, 0); - } - - public AccumulatedLineDraw(List lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int stateGeneration) { - // Copy lines - the source list may be cleared - this.lines = new ArrayList<>(lines); - this.transform = new Matrix4f(transform); // Snapshot for runtime application - this.flags = flags; - this.commandIndex = commandIndex; - this.stateGeneration = stateGeneration; - } - - @Override - public String toString() { - return String.format("AccumulatedLineDraw[lines=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]", - lines.size() / 2, commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java deleted file mode 100644 index 8d29bb58e..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording; - -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; -import org.joml.Matrix4f; - -import java.util.ArrayList; -import java.util.List; - -/** - * Represents an accumulated primitive draw call during display list compilation. - * Stores primitives (lines, triangles) from tessellator callback with their transform. - *

- * Unlike AccumulatedLineDraw which stores ImmediateModeRecorder.LineVertex (16-byte: pos+color), - * this stores ModelPrimitiveView (32-byte: pos+color+tex+light+normal) from the tessellator. - */ -public class AccumulatedPrimitiveDraw { - public final List primitives; - public final Matrix4f transform; - public final CapturingTessellator.Flags flags; - public final int commandIndex; - public final int matrixGeneration; // For batching: same generation = same transform context - public final int stateGeneration; // Same value = no state commands between draws, can merge - - public AccumulatedPrimitiveDraw(List primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) { - this(primitives, transform, flags, commandIndex, matrixGeneration, 0); - } - - public AccumulatedPrimitiveDraw(List primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) { - // Deep copy primitives - pooled primitives are reused after callback - this.primitives = deepCopyPrimitives(primitives); - this.transform = new Matrix4f(transform); - this.flags = flags; - this.commandIndex = commandIndex; - this.matrixGeneration = matrixGeneration; - this.stateGeneration = stateGeneration; - } - - /** - * Creates deep copies of all primitives in the list. - * Required because CapturingTessellator pools and reuses primitive objects. - */ - private static List deepCopyPrimitives(List source) { - final int size = source.size(); - final List copies = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - final ModelPrimitiveView prim = source.get(i); - if (prim instanceof ModelLine ml) { - copies.add(new ModelLine().copyFrom(ml)); - } else if (prim instanceof ModelTriangle mt) { - copies.add(new ModelTriangle().copyFrom(mt)); - } - } - return copies; - } - - @Override - public String toString() { - return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, mode=%d, flags=C%dT%dL%dN%d]", - primitives.size(), commandIndex, matrixGeneration, stateGeneration, flags.drawMode, - flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, - flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java index 1405242b5..4b3e22b85 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java @@ -14,12 +14,6 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; public final class CommandBuffer { private static final int DEFAULT_CAPACITY = 4096; // Guess at typical display list size - // Flag bits for DRAW_RANGE_RESTORE command - public static final int FLAG_HAS_BRIGHTNESS = 1 << 0; - public static final int FLAG_HAS_COLOR = 1 << 1; - public static final int FLAG_HAS_NORMALS = 1 << 2; - public static final int FLAG_HAS_TEXTURE = 1 << 3; - private ByteBuffer buffer; private long basePointer; private long writePointer; @@ -42,6 +36,11 @@ public final class CommandBuffer { writePointer += 4; } + private void writeLong(long value) { + memPutLong(writePointer, value); + writePointer += 8; + } + private void writeFloat(float value) { memPutFloat(writePointer, value); writePointer += 4; @@ -548,13 +547,10 @@ public final class CommandBuffer { // === Draw commands === - public void writeDrawRange(int vboIndex, int startVertex, int vertexCount, boolean hasBrightness) { - ensureCapacity(20); + public void writeDrawRange(int vboIndex) { + ensureCapacity(8); writeInt(GLCommand.DRAW_RANGE); writeInt(vboIndex); - writeInt(startVertex); - writeInt(vertexCount); - writeInt(hasBrightness ? 1 : 0); } /** @@ -562,51 +558,21 @@ public final class CommandBuffer { * Used for immediate mode VBOs to restore GL_CURRENT_COLOR, GL_CURRENT_NORMAL, GL_CURRENT_TEXTURE_COORDS. * * @param vboIndex Index into ownedVbos array - * @param startVertex First vertex to draw - * @param vertexCount Number of vertices to draw - * @param hasBrightness True if VBO has brightness/lightmap data - * @param hasColor True if color should be restored after draw - * @param hasNormals True if normal should be restored after draw - * @param hasTexture True if texcoord should be restored after draw - * @param lastColorR Last vertex's red color component - * @param lastColorG Last vertex's green color component - * @param lastColorB Last vertex's blue color component - * @param lastColorA Last vertex's alpha color component - * @param lastNormalX Last vertex's normal X - * @param lastNormalY Last vertex's normal Y - * @param lastNormalZ Last vertex's normal Z - * @param lastTexS Last vertex's texture S coordinate - * @param lastTexT Last vertex's texture T coordinate */ public void writeDrawRangeRestore( - int vboIndex, int startVertex, int vertexCount, - boolean hasBrightness, boolean hasColor, boolean hasNormals, boolean hasTexture, - float lastColorR, float lastColorG, float lastColorB, float lastColorA, - float lastNormalX, float lastNormalY, float lastNormalZ, - float lastTexS, float lastTexT + int vboIndex, AccumulatedDraw.RestoreData restoreData ) { - ensureCapacity(56); + ensureCapacity(28); writeInt(GLCommand.DRAW_RANGE_RESTORE); writeInt(vboIndex); - writeInt(startVertex); - writeInt(vertexCount); - int flags = (hasBrightness ? FLAG_HAS_BRIGHTNESS : 0) - | (hasColor ? FLAG_HAS_COLOR : 0) - | (hasNormals ? FLAG_HAS_NORMALS : 0) - | (hasTexture ? FLAG_HAS_TEXTURE : 0); - writeInt(flags); - // Last color (4 floats = 16 bytes) - writeFloat(lastColorR); - writeFloat(lastColorG); - writeFloat(lastColorB); - writeFloat(lastColorA); - // Last normal (3 floats = 12 bytes) - writeFloat(lastNormalX); - writeFloat(lastNormalY); - writeFloat(lastNormalZ); + writeInt(restoreData.flags); + // Last color (4 bytes) + writeInt(restoreData.lastColor); + // Last normal (4 bytes) + writeInt(restoreData.lastNormal); // Last texcoord (2 floats = 8 bytes) - writeFloat(lastTexS); - writeFloat(lastTexT); + writeFloat(restoreData.lastTexCoordU); + writeFloat(restoreData.lastTexCoordV); } public void writeCallList(int listId) { @@ -615,6 +581,35 @@ public final class CommandBuffer { writeInt(listId); } + public void writeDrawArrays(int mode, int start, int count) { + ensureCapacity(16); + writeInt(GLCommand.DRAW_ARRAYS); + writeInt(mode); + writeInt(start); + writeInt(count); + } + + public void writeDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { + ensureCapacity(24); + writeInt(GLCommand.DRAW_ELEMENTS); + writeInt(mode); + writeInt(indices_count); + writeInt(type); + writeLong(indices_buffer_offset); + } + + public void writeBindVBO(int vbo) { + ensureCapacity(8); + writeInt(GLCommand.BIND_VBO); + writeInt(vbo); + } + + public void writeBindVAO(int vao) { + ensureCapacity(8); + writeInt(GLCommand.BIND_VAO); + writeInt(vao); + } + public void writeDrawBuffer(int mode) { ensureCapacity(8); writeInt(GLCommand.DRAW_BUFFER); @@ -685,6 +680,12 @@ public final class CommandBuffer { return value; } + public long readLong() { + final long value = memGetLong(readPointer); + readPointer += 8; + return value; + } + /** * Read a float from the current position. */ diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java index a24dafec5..f75eaafbc 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java @@ -1,17 +1,19 @@ package com.gtnewhorizons.angelica.glsm.recording; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; -import static com.gtnewhorizons.angelica.glsm.recording.CommandBuffer.*; /** * Executes commands from a CommandBuffer @@ -34,7 +36,7 @@ public final class CommandBufferExecutor { * @param complexObjects Array of complex objects (TexImage2DCmd, etc.) * @param ownedVbos Array of VBOs owned by the display list (indexed by DrawRange commands) */ - public static void execute(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos) { + public static void execute(ByteBuffer buffer, Object[] complexObjects, DisplayListVBO ownedVbos) { long ptr = memAddress(buffer); final long end = ptr + buffer.limit(); @@ -450,48 +452,39 @@ public final class CommandBufferExecutor { // === Draw commands === case GLCommand.DRAW_RANGE -> { final int vboIndex = memGetInt(ptr); - final int start = memGetInt(ptr + 4); - final int count = memGetInt(ptr + 8); - final boolean hasBrightness = memGetInt(ptr + 12) != 0; - ptr += 16; - final VertexBuffer vbo = ownedVbos[vboIndex]; - vbo.setupState(); - vbo.draw(start, count); - vbo.cleanupState(); + ptr += 4; + ownedVbos.render(vboIndex); } case GLCommand.DRAW_RANGE_RESTORE -> { // Draw VBO range then restore GL current state from last vertex attributes final int vboIndex = memGetInt(ptr); - final int start = memGetInt(ptr + 4); - final int count = memGetInt(ptr + 8); - final int flags = memGetInt(ptr + 12); + final int flags = memGetInt(ptr + 4); // Draw the VBO - final VertexBuffer vbo = ownedVbos[vboIndex]; - vbo.setupState(); - vbo.draw(start, count); - vbo.cleanupState(); + ownedVbos.render(vboIndex); // Restore attributes based on flags - if ((flags & FLAG_HAS_COLOR) != 0) { - final float r = memGetFloat(ptr + 16); - final float g = memGetFloat(ptr + 20); - final float b = memGetFloat(ptr + 24); - final float a = memGetFloat(ptr + 28); - GLStateManager.glColor4f(r, g, b, a); + if ((flags & VertexFlags.COLOR_BIT) != 0) { + final int color = memGetInt(ptr + 8); + byte a = (byte) ((color >> 24) & 0xFF); + byte r = (byte) ((color >> 16) & 0xFF); + byte g = (byte) ((color >> 8) & 0xFF); + byte b = (byte) ((color & 0xFF)); + GLStateManager.glColor4ub(r, g, b, a); } - if ((flags & FLAG_HAS_NORMALS) != 0) { - final float nx = memGetFloat(ptr + 32); - final float ny = memGetFloat(ptr + 36); - final float nz = memGetFloat(ptr + 40); + if ((flags & VertexFlags.NORMAL_BIT) != 0) { + final int normal = memGetInt(ptr + 12); + float nx = (byte)(normal) / 127.0f; + float ny = (byte)(normal >> 8) / 127.0f; + float nz = (byte)(normal >> 16) / 127.0f; GLStateManager.glNormal3f(nx, ny, nz); } - if ((flags & FLAG_HAS_TEXTURE) != 0) { - final float s = memGetFloat(ptr + 44); - final float t = memGetFloat(ptr + 48); + if ((flags & VertexFlags.TEXTURE_BIT) != 0) { + final float s = memGetFloat(ptr + 16); + final float t = memGetFloat(ptr + 20); GLStateManager.glTexCoord2f(s, t); } - ptr += 52; // Skip full command size (56 - 4 for cmd already read) + ptr += 24; // Skip full command size (28 - 4 for cmd already read) } case GLCommand.CALL_LIST -> { final int listId = memGetInt(ptr); @@ -513,6 +506,22 @@ public final class CommandBufferExecutor { ptr += 4 * MAX_DRAW_BUFFERS; GLStateManager.glDrawBuffers(DRAW_BUFFERS_BUFFER); } + case GLCommand.DRAW_ARRAYS -> { + GLStateManager.glDrawArrays(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8)); + ptr += 12; + } + case GLCommand.DRAW_ELEMENTS -> { + GLStateManager.glDrawElements(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8), memGetLong(ptr + 12)); + ptr += 20; + } + case GLCommand.BIND_VBO -> { + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, memGetInt(ptr)); + ptr += 4; + } + case GLCommand.BIND_VAO -> { + VAOManager.VAO.glBindVertexArray(memGetInt(ptr)); + ptr += 4; + } // === Complex object reference === case GLCommand.COMPLEX_REF -> { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java index f2453f762..da05de4b2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java @@ -17,73 +17,6 @@ public final class CommandBufferProcessor { private CommandBufferProcessor() {} - public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) { - switch (opcode) { - // === MultMatrix - already collapsed transforms from flushMatrix() === - case GLCommand.MULT_MATRIX -> { - raw.readMatrix4f(tempMatrix); - opt.multMatrix(tempMatrix); // accumulated = accumulated * tempMatrix - out.writeMultMatrix(tempMatrix); // Copy to output - opt.markLastEmittedAsAccumulated(); // lastEmitted = accumulated (what GL now has) - } - - // === Load commands - flush pending, emit, reset accumulator === - case GLCommand.LOAD_IDENTITY -> { - opt.emitPendingTransform(out); // Emit any pending transforms first - out.writeLoadIdentity(); // Always emit LoadIdentity - opt.loadIdentity(); // Reset accumulated to identity - opt.resetLastEmitted(); // Reset lastEmitted to identity - opt.checkAndClearAbsoluteMatrix(); // Clear the flag if set - } - case GLCommand.LOAD_MATRIX -> { - raw.readMatrix4f(tempMatrix); - opt.emitPendingTransform(out); - out.writeLoadMatrix(tempMatrix); - opt.loadIdentity(); - opt.resetLastEmitted(); // Reset lastEmitted to identity - opt.markAbsoluteMatrix(); - } - - // === Stack operations - flush/update optimizer state and copy === - case GLCommand.PUSH_MATRIX -> { - opt.emitPendingTransform(out); - opt.push(); - // Reset accumulated/lastEmitted to identity after push. - opt.loadIdentity(); - opt.resetLastEmitted(); - out.writePushMatrix(); - } - case GLCommand.POP_MATRIX -> { - opt.pop(); - out.writePopMatrix(); - } - - // === Barriers - emit pending transform before copying === - case GLCommand.MATRIX_MODE -> { - final int mode = raw.readInt(); - opt.emitPendingTransform(out); // Pending transforms apply to OLD mode - out.writeMatrixMode(mode); - opt.loadIdentity(); // Reset accumulated for new mode - opt.resetLastEmitted(); // Reset lastEmitted for new mode - } - case GLCommand.CALL_LIST -> { - final int listId = raw.readInt(); - opt.emitPendingTransform(out); - out.writeCallList(listId); - } - case GLCommand.PUSH_ATTRIB -> { - final int mask = raw.readInt(); - if ((mask & GL11.GL_TRANSFORM_BIT) != 0) { - opt.emitPendingTransform(out); - } - out.writePushAttrib(mask); - } - - // === All other commands - just copy === - default -> copyCommandData(opcode, raw, out); - } - } - /** * Copy a complete command (opcode already read) from raw to final buffer. */ @@ -210,8 +143,12 @@ public final class CommandBufferProcessor { } // Draw/call commands - case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt() != 0); + case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt()); case GLCommand.CALL_LIST -> out.writeCallList(raw.readInt()); + case GLCommand.DRAW_ARRAYS -> out.writeDrawArrays(raw.readInt(), raw.readInt(), raw.readInt()); + case GLCommand.DRAW_ELEMENTS -> out.writeDrawElements(raw.readInt(), raw.readInt(), raw.readInt(), raw.readLong()); + case GLCommand.BIND_VBO -> out.writeBindVBO(raw.readInt()); + case GLCommand.BIND_VAO -> out.writeBindVAO(raw.readInt()); // Complex object reference - transfer the object to output buffer case GLCommand.COMPLEX_REF -> { @@ -223,94 +160,4 @@ public final class CommandBufferProcessor { default -> LOGGER.warn("[CommandBufferProcessor] Unknown opcode in buffer copy: {}", opcode); } } - - /** - * Lightweight transform optimizer for buffer-to-buffer processing. - * Tracks accumulated transform (mode-agnostic) and emits MultMatrix commands when needed. - * - *

This optimizer processes raw transform commands (TRANSLATE, ROTATE, SCALE) and - * collapses them into single MultMatrix commands at barriers. It must stay synchronized - * with the relativeTransform tracking in DisplayListManager - both systems must reset - * at the same barriers (MatrixMode, LoadIdentity, LoadMatrix, Push/Pop).

- */ - public static class BufferTransformOptimizer { - private final Matrix4f accumulated = new Matrix4f(); - private final Matrix4f lastEmitted = new Matrix4f(); - private final Matrix4f delta = new Matrix4f(); // Reused for delta computation - private final Deque stack = new ArrayDeque<>(); - private boolean absoluteMatrixFlag = false; - - public BufferTransformOptimizer() { - accumulated.identity(); - lastEmitted.identity(); - } - - public void multMatrix(Matrix4f m) { - accumulated.mul(m); - } - - public void loadIdentity() { - accumulated.identity(); - } - - public void push() { - stack.push(new Matrix4f(accumulated)); - } - - public void pop() { - if (!stack.isEmpty()) { - accumulated.set(stack.pop()); - lastEmitted.set(accumulated); - } else { - accumulated.identity(); - lastEmitted.identity(); - } - } - - public boolean isIdentity() { - return DisplayListManager.isIdentity(accumulated); - } - - public void markAbsoluteMatrix() { - absoluteMatrixFlag = true; - } - - public boolean checkAndClearAbsoluteMatrix() { - final boolean was = absoluteMatrixFlag; - absoluteMatrixFlag = false; - return was; - } - - public void resetLastEmitted() { - lastEmitted.identity(); - } - - public void setLastEmitted(Matrix4f m) { - lastEmitted.set(m); - } - - public void markLastEmittedAsAccumulated() { - lastEmitted.set(accumulated); - } - - public void emitPendingTransform(CommandBuffer out) { - if (!accumulated.equals(lastEmitted)) { - emitTransformTo(out, accumulated); - } - } - - public void emitTransformTo(CommandBuffer out, Matrix4f target) { - if (target.equals(lastEmitted)) { - return; - } - - if (DisplayListManager.isIdentity(lastEmitted)) { - out.writeMultMatrix(target); - } else { - delta.set(lastEmitted).invert().mul(target); - out.writeMultMatrix(delta); - } - lastEmitted.set(target); - } - } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java index d8e706674..b79c1f65e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java @@ -9,7 +9,7 @@ import java.nio.IntBuffer; /** * Records GL commands to a CommandBuffer during display list compilation. */ -public class CommandRecorder { +public final class CommandRecorder { private final CommandBuffer buffer; private int commandCount; @@ -337,6 +337,26 @@ public class CommandRecorder { commandCount++; } + public void recordDrawArrays(int mode, int start, int count) { + buffer.writeDrawArrays(mode, start, count); + commandCount++; + } + + public void recordDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { + buffer.writeDrawElements(mode, indices_count, type, indices_buffer_offset); + commandCount++; + } + + public void recordBindVBO(int vbo) { + buffer.writeBindVBO(vbo); + commandCount++; + } + + public void recordBindVAO(int vao) { + buffer.writeBindVAO(vao); + commandCount++; + } + public void recordComplexCommand(DisplayListCommand cmd) { buffer.writeComplexRef(cmd); commandCount++; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java index 68cac09aa..9ddc2d1ef 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java @@ -1,6 +1,6 @@ package com.gtnewhorizons.angelica.glsm.recording; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; @@ -30,9 +30,9 @@ public final class CompiledDisplayList { private final ByteBuffer commandBuffer; // Off-heap command storage, must be freed private final Object[] complexObjects; // Complex commands (TexImage2D, etc.) - private final VertexBuffer[] ownedVbos; // GPU resources referenced by index + private final DisplayListVBO ownedVbos; // GPU resources referenced by index - public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, VertexBuffer[] ownedVbos) { + public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, DisplayListVBO ownedVbos) { this.commandBuffer = commandBuffer; this.complexObjects = complexObjects; this.ownedVbos = ownedVbos; @@ -62,11 +62,7 @@ public final class CompiledDisplayList { // Close VBOs if (ownedVbos != null) { - for (VertexBuffer vbo : ownedVbos) { - if (vbo != null) { - vbo.close(); - } - } + ownedVbos.delete(); } // Free the command buffer (off-heap memory) @@ -89,10 +85,7 @@ public final class CompiledDisplayList { return complexObjects; } - /** - * Get owned VBOs for inlining into another display list. - */ - public VertexBuffer[] getOwnedVbos() { + public DisplayListVBO getOwnedVbos() { return ownedVbos; } @@ -112,7 +105,7 @@ public final class CompiledDisplayList { while (ptr < end) { final int cmd = memGetInt(ptr); counts.mergeInt(cmd, 1, Integer::sum); - ptr += getCommandSize(cmd, ptr); + ptr += GLCommand.getCommandSize(cmd, ptr); } return counts; } @@ -131,74 +124,13 @@ public final class CompiledDisplayList { while (ptr < end) { final int cmd = memGetInt(ptr); opcodes.add(cmd); - ptr += getCommandSize(cmd, ptr); + ptr += GLCommand.getCommandSize(cmd, ptr); } return opcodes; } - /** - * Get size of a command in bytes (including the opcode). - */ - private static int getCommandSize(int cmd, long ptr) { - return switch (cmd) { - // Opcode-only commands (4 bytes) - case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4; - - // Single int commands (8 bytes) - case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL, - GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP, - GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM, - GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK, - GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, - GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8; - - // Two int commands (12 bytes) - case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL, - GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI, - GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, - GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12; - - // Three int commands (16 bytes) - case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI, - GLCommand.LIGHTF, GLCommand.LIGHTI, - GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16; - - // Four int commands (20 bytes) - case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK, - GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE, - GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR, - GLCommand.DRAW_RANGE -> 20; - - // DRAW_RANGE_RESTORE: 56 bytes - // [cmd:4][vboIndex:4][start:4][count:4][flags:4][color:16f][normal:12f][texcoord:8f] - case GLCommand.DRAW_RANGE_RESTORE -> 56; - - // DRAW_BUFFER: 8 bytes [cmd:4][mode:4] - case GLCommand.DRAW_BUFFER -> 8; - - // DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8] - case GLCommand.DRAW_BUFFERS -> 40; - - // Double commands - case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles - case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double - case GLCommand.ROTATE -> 36; // cmd + 4 doubles - case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles - - // Matrix commands - case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats - - // Buffer commands (variable, read count) - case GLCommand.FOG, GLCommand.LIGHT_MODEL -> { - final int count = memGetInt(ptr + 8); // pname at +4, count at +8 - yield 12 + count * 4; - } - case GLCommand.LIGHT, GLCommand.MATERIAL -> { - final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12 - yield 16 + count * 4; - } - - default -> throw new IllegalStateException("Unknown command: " + cmd); - }; + @Override + public String toString() { + return DisplayListManager.getCompiledDisplayListString(0, this, null); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java new file mode 100644 index 000000000..87a539641 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java @@ -0,0 +1,60 @@ +package com.gtnewhorizons.angelica.glsm.recording; + +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; +import org.lwjgl.opengl.GL15; + +/** + * A class that stores multiple vertex formats & their corresponding buffers. + */ +public final class DisplayListVBO { + + private final SubVBO[] vbos; + + DisplayListVBO(SubVBO[] vbos) { + this.vbos = vbos; + } + + public void delete() { + for (SubVBO vbo : vbos) { + vbo.delete(); + } + } + + public SubVBO[] getVBOs() { + return vbos; + } + + public void render(int index) { + vbos[index].render(); + } + + public static final class SubVBO { + + private final IVertexArrayObject vao; + private final int drawMode; + private final int start; + private final int count; + + public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count) { + this.vao = vao; + this.drawMode = drawMode; + this.start = start; + this.count = count; + } + + public void delete() { + vao.delete(); + } + + public void render() { + vao.bind(); + vao.draw(drawMode, start, count); + vao.unbind(); + } + + public IVertexArrayObject getVAO() { + return vao; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java new file mode 100644 index 000000000..b30cacdbe --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java @@ -0,0 +1,127 @@ +package com.gtnewhorizons.angelica.glsm.recording; + +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import org.lwjgl.opengl.GL11; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; + +/** + * Compiles multiple ByteBuffers of the same Vertex format into a VBO. Any buffer added to the builder will be freed afterward. + */ +public final class DisplayListVBOBuilder { + + // Removes the need for a HashMap. Since it's only an array of 16 values, this should be faster + private final List[] formats = new List[VertexFlags.BITSET_SIZE]; + private int count; + + public DisplayListVBOBuilder addDraw(VertexFormat format, int drawMode, List buffers) { + List data = formats[format.getVertexFlags()]; + if (data == null) { + data = new ArrayList<>(); + formats[format.getVertexFlags()] = data; + } + data.add(new FormatData(buffers, drawMode, count)); + count++; + return this; + } + + public DisplayListVBOBuilder addDraws(List draws) { + for (AccumulatedDraw draw : draws) { + addDraw(draw.format, draw.drawMode, draw.drawBuffers); + } + return this; + } + + public DisplayListVBO build() { + final DisplayListVBO.SubVBO[] vbos = new DisplayListVBO.SubVBO[count]; + final ArrayList allBuffers = new ArrayList<>(); + for (int i = 0; i < VertexFlags.BITSET_SIZE; i++) { + List formatData = formats[i]; + if (formatData == null) continue; + final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[i]; + int start = 0; + final IVertexArrayObject vao = VAOManager.createStorageVAO(format, -1, 0); // drawMode will be ignored + final IVertexBuffer vbo = vao.getVBO(); + for (FormatData data : formatData) { + int vertexCount; + final List drawBuffers = data.buffers; + if (drawBuffers.size() == 1) { + final ByteBuffer buffer = drawBuffers.get(0); + allBuffers.add(buffer); + vertexCount = format.getVertexCount(buffer); + } else { + allBuffers.addAll(drawBuffers); + int size = 0; + for (ByteBuffer buffer : drawBuffers) { + size += buffer.remaining(); + } + vertexCount = format.getVertexCount(size); + } + if (data.drawMode == GL11.GL_QUADS) { + IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount)); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6); + } else { + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount); + } + + + start += vertexCount; + } + ByteBuffer bigBuffer = mergeAndDelete(allBuffers); + vbo.allocate(bigBuffer, start); + memFree(bigBuffer); + + allBuffers.clear(); + } + return new DisplayListVBO(vbos); + } + + private static ByteBuffer mergeAndDelete(List buffers) { + if (buffers.size() == 1) { + return buffers.get(0); + } + int needed = 0; + for (ByteBuffer buffer : buffers) { + needed += buffer.remaining(); + } + + ByteBuffer out = memAlloc(needed); + long dst = memAddress0(out); + + for (ByteBuffer buffer : buffers) { + final int len = buffer.limit(); + final long address = memAddress0(buffer); + memCopy(address, dst, len); + dst += len; + + nmemFree(address); + } + + out.limit(needed); + return out; + } + + private static final class FormatData { + + private final List buffers; + private final int drawMode; + private final int drawIndex; + + public FormatData(List buffers, int drawMode, int drawIndex) { + this.buffers = buffers; + this.drawMode = drawMode; + this.drawIndex = drawIndex; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java index 8a89449bb..d9d4ed29f 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica.glsm.recording; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; + /** * Command opcodes for ByteBuffer-based display list serialization. * Each command has a fixed layout described in comments. @@ -88,16 +90,24 @@ public final class GLCommand { public static final int MATERIAL = 93; // [cmd:4][face:4][pname:4][count:4][params:16f] = 32 bytes // === Draw commands === - public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4][start:4][count:4][hasBrightness:4] = 20 bytes - public static final int CALL_LIST = 101; // [cmd:4][listId:4] = 8 bytes - public static final int DRAW_BUFFER = 102; // [cmd:4][mode:4] = 8 bytes - public static final int DRAW_BUFFERS = 103; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers) + public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4] = 8 bytes + public static final int DRAW_RANGE_RESTORE = 101; // [cmd:4][vboIndex:4][flags:4][color:4][normal:4][lastTexCoord:8f] = 28 bytes + public static final int CALL_LIST = 102; // [cmd:4][listId:4] = 8 bytes + + + public static final int DRAW_ARRAYS = 110; // [cmd:4][drawMode:4][start:4][count:4] = 20 bytes + public static final int DRAW_ELEMENTS = 111; // [cmd:4][mode:4][indices_count:4][type:4][indices_buffer_offset:8] = 28 bytes + public static final int DRAW_BUFFER = 112; // [cmd:4][mode:4] = 8 bytes + public static final int DRAW_BUFFERS = 113; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers) /** * Draw VBO range with attribute restoration after draw. * Used for immediate mode VBOs to restore GL current state (color, normal, texcoord). */ - public static final int DRAW_RANGE_RESTORE = 104; // [cmd:4][vboIndex:4][start:4][count:4][flags:4] - // [lastColor:16f][lastNormal:12f][lastTexCoord:8f] = 56 bytes + + + // === Bind commands === + public static final int BIND_VBO = 120; + public static final int BIND_VAO = 121; // === Complex object reference === public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes @@ -171,9 +181,78 @@ public final class GLCommand { case CALL_LIST -> "CALL_LIST"; case DRAW_BUFFER -> "DRAW_BUFFER"; case DRAW_BUFFERS -> "DRAW_BUFFERS"; - case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE"; case COMPLEX_REF -> "COMPLEX_REF"; + case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE"; + case BIND_VAO -> "BIND_VAO"; + case BIND_VBO -> "BIND_VBO"; default -> "UNKNOWN(" + opcode + ")"; }; } + + /** + * Get size of a command in bytes (including the opcode). + */ + public static int getCommandSize(int cmd, long ptr) { + return switch (cmd) { + // Opcode-only commands (4 bytes) + case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4; + + // Single int commands (8 bytes) + case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL, + GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP, + GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM, + GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK, + GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, + GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_RANGE, GLCommand.BIND_VBO, + GLCommand.BIND_VAO -> 8; + + // Two int commands (12 bytes) + case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL, + GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI, + GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, + GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12; + + // Three int commands (16 bytes) + case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI, + GLCommand.LIGHTF, GLCommand.LIGHTI, + GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF, GLCommand.DRAW_ARRAYS -> 16; + + // Four int commands (20 bytes) + case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK, + GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE, + GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR -> 20; + + case GLCommand.DRAW_ELEMENTS -> 24; + + // DRAW_RANGE_RESTORE: 28 bytes + case GLCommand.DRAW_RANGE_RESTORE -> 28; + + // DRAW_BUFFER: 8 bytes [cmd:4][mode:4] + case GLCommand.DRAW_BUFFER -> 8; + + // DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8] + case GLCommand.DRAW_BUFFERS -> 40; + + // Double commands + case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles + case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double + case GLCommand.ROTATE -> 36; // cmd + 4 doubles + case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles + + // Matrix commands + case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats + + // Buffer commands (variable, read count) + case GLCommand.FOG, GLCommand.LIGHT_MODEL -> { + final int count = memGetInt(ptr + 8); // pname at +4, count at +8 + yield 12 + count * 4; + } + case GLCommand.LIGHT, GLCommand.MATERIAL -> { + final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12 + yield 16 + count * 4; + } + + default -> throw new IllegalStateException("Unknown command: " + cmd); + }; + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java index cccd1bc87..fb9bf85c1 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java @@ -1,156 +1,58 @@ package com.gtnewhorizons.angelica.glsm.recording; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import com.gtnewhorizons.angelica.glsm.states.ClientArrayState; +import net.minecraft.client.renderer.Tessellator; +import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; +import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; -import java.util.ArrayList; -import java.util.List; /** * Records immediate mode GL calls (glBegin/glEnd/glVertex) during display list compilation. - * Converts immediate mode geometry to ModelQuad format for VBO compilation. - * - *

Tracks current immediate mode state: - *

    - *
  • TexCoord: Set by glTexCoord* calls
  • - *
  • Normal: Set by glNormal* calls
  • - *
  • Color: Read from GLStateManager.getColor() at vertex emission time
  • - *
- * - *

Supported primitive types: - *

    - *
  • GL_QUADS: 4 vertices per quad (native support)
  • - *
  • GL_TRIANGLES: 3 vertices per triangle (converted to degenerate quad)
  • - *
  • GL_TRIANGLE_FAN: Fan of triangles (converted to individual quads)
  • - *
  • GL_TRIANGLE_STRIP: Strip of triangles (converted to individual quads)
  • - *
  • GL_QUAD_STRIP: Strip of quads (converted to individual quads)
  • - *
  • GL_POLYGON: Polygon (treated as triangle fan)
  • - *
- * - *

Unsupported primitive types (logged warning, geometry discarded): - *

    - *
  • GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP: Line primitives
  • - *
  • GL_POINTS: Point primitives
  • - *
+ * Converts immediate mode geometry to ByteBuffer directly via {@link DirectTessellator} + *

+ * Currently only used for display list compilation, should be perfectly usable outside of display lists too though. */ -public class ImmediateModeRecorder { - private static final Logger LOGGER = LogManager.getLogger("ImmediateModeRecorder"); +public final class ImmediateModeRecorder { + private static final DirectTessellator tessellator = new DirectTessellator(TessellatorManager.DEFAULT_BUFFER_SIZE); - // Accumulated quads from completed primitives - private final List quads = new ArrayList<>(); + private ImmediateModeRecorder() { - // Accumulated line vertices (pairs of vertices for GL_LINES) - private final List lineVertices = new ArrayList<>(); - - // Current primitive state - private int currentPrimitiveType = -1; - private boolean inPrimitive = false; - - // Vertices for current primitive (cleared on glEnd) - private final List currentVertices = new ArrayList<>(); - - // Current immediate mode state (set by glTexCoord*, glNormal*) - private float texCoordS = 0.0f; - private float texCoordT = 0.0f; - private float normalX = 0.0f; - private float normalY = 0.0f; - private float normalZ = 1.0f; // Default normal points +Z - - // Track which attributes have been set (for flags) - private boolean hasTexCoord = false; - private boolean hasNormal = false; - private boolean hasColor = false; - - /** - * Represents a single vertex captured during immediate mode. - */ - private static class ImmediateVertex { - float x, y, z; // Position - int color; // Packed ABGR color - float texU, texV; // Texture coordinates - int normal; // Packed normal - - ImmediateVertex(float x, float y, float z, int color, float texU, float texV, int normal) { - this.x = x; - this.y = y; - this.z = z; - this.color = color; - this.texU = texU; - this.texV = texV; - this.normal = normal; - } } - /** - * Represents a vertex for line primitives. - * Simpler than ImmediateVertex - just position and color. - */ - public static class LineVertex { - public final float x, y, z; - public final int color; // Packed ABGR color - - public LineVertex(float x, float y, float z, int color) { - this.x = x; - this.y = y; - this.z = z; - this.color = color; - } - } - - public ImmediateModeRecorder() { - // Recorder is ready to capture geometry + public static DirectTessellator getInternalTessellator() { + return tessellator; } /** * Set the current texture coordinate. * Called by GLStateManager.glTexCoord*. */ - public void setTexCoord(float s, float t) { - this.texCoordS = s; - this.texCoordT = t; - this.hasTexCoord = true; + public static void setTexCoord(float s, float t) { + tessellator.setTextureUV(s, t); } /** * Set the current normal vector. * Called by GLStateManager.glNormal*. */ - public void setNormal(float x, float y, float z) { - this.normalX = x; - this.normalY = y; - this.normalZ = z; - this.hasNormal = true; - } - - /** - * Check if currently in a primitive (between glBegin and glEnd). - */ - public boolean isInPrimitive() { - return inPrimitive; + public static void setNormal(float x, float y, float z) { + tessellator.setNormal(x, y, z); } /** * Start recording a new primitive. */ - public void begin(int primitiveType) { - if (inPrimitive) { - throw new IllegalStateException("glBegin called while already in primitive"); - } - this.currentPrimitiveType = primitiveType; - this.currentVertices.clear(); - this.inPrimitive = true; + public static void begin(int primitiveType) { + tessellator.startDrawing(primitiveType); } /** @@ -159,346 +61,27 @@ public class ImmediateModeRecorder { * * @return Result containing quads, lines, and flags, or null if no geometry was produced */ - public Result end() { - if (!inPrimitive) { + public static DirectTessellator end() { + if (!tessellator.isDrawing) { throw new IllegalStateException("glEnd called without glBegin"); } - // Capture last vertex attributes BEFORE clearing currentVertices - // These will be used to restore GL current state after VBO playback - float lastColorR = 1.0f, lastColorG = 1.0f, lastColorB = 1.0f, lastColorA = 1.0f; - float lastNormalX = 0.0f, lastNormalY = 0.0f, lastNormalZ = 1.0f; - float lastTexS = 0.0f, lastTexT = 0.0f; + tessellator.isDrawing = false; - if (!currentVertices.isEmpty()) { - ImmediateVertex last = currentVertices.get(currentVertices.size() - 1); + if (tessellator.isEmpty()) return null; - // Unpack color from ABGR format - lastColorR = (last.color & 0xFF) / 255.0f; - lastColorG = ((last.color >> 8) & 0xFF) / 255.0f; - lastColorB = ((last.color >> 16) & 0xFF) / 255.0f; - lastColorA = ((last.color >> 24) & 0xFF) / 255.0f; - - // Unpack normal from NormI8 format (signed bytes packed into int) - lastNormalX = NormI8.unpackX(last.normal); - lastNormalY = NormI8.unpackY(last.normal); - lastNormalZ = NormI8.unpackZ(last.normal); - - // Texture coords are stored directly as floats - lastTexS = last.texU; - lastTexT = last.texV; - } - - // Convert this primitive's vertices to quads or lines - convertPrimitiveToQuads(); - this.currentVertices.clear(); - this.inPrimitive = false; - - // Return geometry from this primitive immediately (don't accumulate) - if (quads.isEmpty() && lineVertices.isEmpty()) { - return null; - } - - // Copy geometry and create flags - List resultQuads = new ArrayList<>(quads); - List resultLines = new ArrayList<>(lineVertices); - CapturingTessellator.Flags flags = new CapturingTessellator.Flags( - hasTexCoord, // hasTexture - false, // hasBrightness - immediate mode doesn't typically use lightmap - hasColor, // hasColor - hasNormal // hasNormals - ); - - // Clear for next primitive (but keep attribute tracking state) - quads.clear(); - lineVertices.clear(); - - return new Result(resultQuads, resultLines, flags, - lastColorR, lastColorG, lastColorB, lastColorA, - lastNormalX, lastNormalY, lastNormalZ, - lastTexS, lastTexT); + return tessellator; } /** * Record a vertex with current attributes. * Color is read from GLStateManager at call time. */ - public void vertex(float x, float y, float z) { - if (!inPrimitive) { + public static void vertex(float x, float y, float z) { + if (!tessellator.isDrawing) { throw new IllegalStateException("glVertex called outside glBegin/glEnd"); } - - // Get current color from GLStateManager - int packedColor = packColor( - GLStateManager.getColor().getRed(), - GLStateManager.getColor().getGreen(), - GLStateManager.getColor().getBlue(), - GLStateManager.getColor().getAlpha() - ); - if (packedColor != 0xFFFFFFFF) { - hasColor = true; - } - - // Pack normal - int packedNormal = NormI8.pack(normalX, normalY, normalZ); - - currentVertices.add(new ImmediateVertex( - x, y, z, - packedColor, - texCoordS, texCoordT, - packedNormal - )); - } - - /** - * Pack RGBA floats (0-1) into ABGR int format used by ModelQuad. - */ - private static int packColor(float r, float g, float b, float a) { - int ri = (int) (r * 255.0f) & 0xFF; - int gi = (int) (g * 255.0f) & 0xFF; - int bi = (int) (b * 255.0f) & 0xFF; - int ai = (int) (a * 255.0f) & 0xFF; - // ABGR format (little-endian: stored as RGBA bytes) - return (ai << 24) | (bi << 16) | (gi << 8) | ri; - } - - /** - * Convert the current primitive vertices to quads. - * Handles different primitive types. - */ - private void convertPrimitiveToQuads() { - int vertexCount = currentVertices.size(); - if (vertexCount == 0) { - return; - } - - switch (currentPrimitiveType) { - case GL11.GL_QUADS -> convertQuads(); - case GL11.GL_TRIANGLES -> convertTriangles(); - case GL11.GL_TRIANGLE_FAN, GL11.GL_POLYGON -> convertTriangleFan(); - case GL11.GL_TRIANGLE_STRIP -> convertTriangleStrip(); - case GL11.GL_QUAD_STRIP -> convertQuadStrip(); - case GL11.GL_LINES -> convertLines(); - case GL11.GL_LINE_STRIP -> convertLineStripToLines(); - case GL11.GL_LINE_LOOP -> convertLineLoopToLines(); - case GL11.GL_POINTS -> { - LOGGER.warn("[ImmediateModeRecorder] Point primitives not supported, discarding {} vertices", vertexCount); - } - default -> { - LOGGER.warn("[ImmediateModeRecorder] Unknown primitive type {}, discarding {} vertices", - currentPrimitiveType, vertexCount); - } - } - } - - /** - * Convert GL_QUADS vertices to ModelQuads (4 vertices per quad). - */ - private void convertQuads() { - int vertexCount = currentVertices.size(); - int fullQuads = vertexCount / 4; - - for (int i = 0; i < fullQuads; i++) { - int base = i * 4; - addQuad( - currentVertices.get(base), - currentVertices.get(base + 1), - currentVertices.get(base + 2), - currentVertices.get(base + 3) - ); - } - - int remaining = vertexCount % 4; - if (remaining > 0) { - LOGGER.warn("[ImmediateModeRecorder] GL_QUADS: Incomplete quad, discarding {} vertices", remaining); - } - } - - /** - * Convert GL_TRIANGLES vertices to degenerate quads (3 vertices per triangle, duplicate last). - */ - private void convertTriangles() { - int vertexCount = currentVertices.size(); - int fullTriangles = vertexCount / 3; - - for (int i = 0; i < fullTriangles; i++) { - int base = i * 3; - ImmediateVertex v0 = currentVertices.get(base); - ImmediateVertex v1 = currentVertices.get(base + 1); - ImmediateVertex v2 = currentVertices.get(base + 2); - // Degenerate quad: duplicate third vertex - addQuad(v0, v1, v2, v2); - } - - int remaining = vertexCount % 3; - if (remaining > 0) { - LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLES: Incomplete triangle, discarding {} vertices", remaining); - } - } - - /** - * Convert GL_TRIANGLE_FAN vertices to triangles then to degenerate quads. - * First vertex is center, subsequent vertices form fan. - */ - private void convertTriangleFan() { - int vertexCount = currentVertices.size(); - if (vertexCount < 3) { - LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_FAN: Need at least 3 vertices, got {}", vertexCount); - return; - } - - ImmediateVertex center = currentVertices.get(0); - for (int i = 1; i < vertexCount - 1; i++) { - ImmediateVertex v1 = currentVertices.get(i); - ImmediateVertex v2 = currentVertices.get(i + 1); - // Triangle: center, v1, v2 -> degenerate quad - addQuad(center, v1, v2, v2); - } - } - - /** - * Convert GL_TRIANGLE_STRIP vertices to triangles then to degenerate quads. - */ - private void convertTriangleStrip() { - int vertexCount = currentVertices.size(); - if (vertexCount < 3) { - LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_STRIP: Need at least 3 vertices, got {}", vertexCount); - return; - } - - for (int i = 0; i < vertexCount - 2; i++) { - ImmediateVertex v0, v1, v2; - if ((i & 1) == 0) { - // Even triangle: v[i], v[i+1], v[i+2] - v0 = currentVertices.get(i); - v1 = currentVertices.get(i + 1); - v2 = currentVertices.get(i + 2); - } else { - // Odd triangle: v[i+1], v[i], v[i+2] (reverse winding) - v0 = currentVertices.get(i + 1); - v1 = currentVertices.get(i); - v2 = currentVertices.get(i + 2); - } - addQuad(v0, v1, v2, v2); - } - } - - /** - * Convert GL_QUAD_STRIP vertices to quads. - * Vertices come in pairs: (v0,v1), (v2,v3), (v4,v5)... - * Each quad uses 4 consecutive vertices in pattern: v[2i], v[2i+1], v[2i+3], v[2i+2] - */ - private void convertQuadStrip() { - int vertexCount = currentVertices.size(); - if (vertexCount < 4) { - LOGGER.warn("[ImmediateModeRecorder] GL_QUAD_STRIP: Need at least 4 vertices, got {}", vertexCount); - return; - } - - int numQuads = (vertexCount - 2) / 2; - for (int i = 0; i < numQuads; i++) { - int base = i * 2; - // Quad strip winding: v[0], v[1], v[3], v[2] - addQuad( - currentVertices.get(base), - currentVertices.get(base + 1), - currentVertices.get(base + 3), - currentVertices.get(base + 2) - ); - } - } - - /** - * Convert GL_LINES vertices to line segments (pairs of vertices). - */ - private void convertLines() { - int vertexCount = currentVertices.size(); - int fullLines = vertexCount / 2; - - for (int i = 0; i < fullLines; i++) { - int base = i * 2; - ImmediateVertex v0 = currentVertices.get(base); - ImmediateVertex v1 = currentVertices.get(base + 1); - lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color)); - lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color)); - } - - int remaining = vertexCount % 2; - if (remaining > 0) { - LOGGER.warn("[ImmediateModeRecorder] GL_LINES: Incomplete line, discarding {} vertices", remaining); - } - } - - /** - * Convert GL_LINE_STRIP to individual line segments. - * Vertices 0-1-2-3 become lines: 0-1, 1-2, 2-3 - */ - private void convertLineStripToLines() { - int vertexCount = currentVertices.size(); - if (vertexCount < 2) { - LOGGER.warn("[ImmediateModeRecorder] GL_LINE_STRIP: Need at least 2 vertices, got {}", vertexCount); - return; - } - - for (int i = 0; i < vertexCount - 1; i++) { - ImmediateVertex v0 = currentVertices.get(i); - ImmediateVertex v1 = currentVertices.get(i + 1); - lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color)); - lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color)); - } - } - - /** - * Convert GL_LINE_LOOP to individual line segments. - * Like LINE_STRIP but also closes the loop from last to first vertex. - */ - private void convertLineLoopToLines() { - int vertexCount = currentVertices.size(); - if (vertexCount < 2) { - LOGGER.warn("[ImmediateModeRecorder] GL_LINE_LOOP: Need at least 2 vertices, got {}", vertexCount); - return; - } - - // Convert as strip first - convertLineStripToLines(); - - // Close the loop: add last-to-first segment - ImmediateVertex vLast = currentVertices.get(vertexCount - 1); - ImmediateVertex vFirst = currentVertices.get(0); - lineVertices.add(new LineVertex(vLast.x, vLast.y, vLast.z, vLast.color)); - lineVertices.add(new LineVertex(vFirst.x, vFirst.y, vFirst.z, vFirst.color)); - } - - /** - * Create a ModelQuad from 4 ImmediateVertex objects. - */ - private void addQuad(ImmediateVertex v0, ImmediateVertex v1, ImmediateVertex v2, ImmediateVertex v3) { - ModelQuad quad = new ModelQuad(); - - setVertex(quad, 0, v0); - setVertex(quad, 1, v1); - setVertex(quad, 2, v2); - setVertex(quad, 3, v3); - - // Set light face based on computed normal - quad.setLightFace(ModelQuadUtil.findLightFace(quad.getComputedFaceNormal())); - - quads.add(quad); - } - - /** - * Set a single vertex in a ModelQuad. - */ - private void setVertex(ModelQuad quad, int idx, ImmediateVertex v) { - quad.setX(idx, v.x); - quad.setY(idx, v.y); - quad.setZ(idx, v.z); - quad.setColor(idx, v.color); - quad.setTexU(idx, v.texU); - quad.setTexV(idx, v.texV); - quad.setForgeNormal(idx, v.normal); - // Light defaults to full brightness (no lightmap for immediate mode typically) - quad.setLight(idx, ModelQuadUtil.DEFAULT_LIGHTMAP); + tessellator.addVertex(x, y, z); } /** @@ -508,87 +91,16 @@ public class ImmediateModeRecorder { * is returned from end() immediately. This method is kept for edge cases * where primitives might fail to convert (e.g., incomplete quads). */ - public boolean hasGeometry() { - return !quads.isEmpty() || !lineVertices.isEmpty(); + public static boolean hasGeometry() { + return tessellator.vertexCount != 0; } - /** - * Get any remaining accumulated geometry and clear the recorder. - * - *

Note: With immediate flush mode, this will typically return null as geometry - * is returned from end() immediately. This method is kept for cleanup and - * edge cases where geometry might remain (e.g., if end() was never called). - * - * @return Result containing remaining quads, lines, and flags, or null if no geometry - */ - public Result getQuadsAndClear() { - if (inPrimitive) { - throw new IllegalStateException("Cannot get geometry while in primitive (missing glEnd)"); - } - - if (quads.isEmpty() && lineVertices.isEmpty()) { - return null; - } - - // Copy geometry and create flags - List resultQuads = new ArrayList<>(quads); - List resultLines = new ArrayList<>(lineVertices); - CapturingTessellator.Flags flags = new CapturingTessellator.Flags( - hasTexCoord, // hasTexture - false, // hasBrightness - immediate mode doesn't typically use lightmap - hasColor, // hasColor - hasNormal // hasNormals - ); - - // Clear state for reuse - quads.clear(); - lineVertices.clear(); - hasColor = false; - hasTexCoord = false; - hasNormal = false; - // Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec - - // For getQuadsAndClear, we don't have last vertex data (it was cleared in end()) - // Use default values - this method is for edge cases/cleanup anyway - return new Result(resultQuads, resultLines, flags, - 1.0f, 1.0f, 1.0f, 1.0f, // Default white color - 0.0f, 0.0f, 1.0f, // Default +Z normal - 0.0f, 0.0f); // Default (0,0) texcoord - } - - /** - * Result of immediate mode recording: quads, lines, attribute flags, and last vertex state. - * The last vertex state is used to restore GL_CURRENT_COLOR etc. after VBO playback. - */ - @com.github.bsideup.jabel.Desugar - public record Result( - List quads, - List lines, - CapturingTessellator.Flags flags, - // Last vertex attributes for restoration after VBO draw - float lastColorR, float lastColorG, float lastColorB, float lastColorA, - float lastNormalX, float lastNormalY, float lastNormalZ, - float lastTexCoordS, float lastTexCoordT - ) {} - /** * Reset all state including current texcoord/normal. * Called when starting a new display list. */ - public void reset() { - quads.clear(); - lineVertices.clear(); - currentVertices.clear(); - inPrimitive = false; - currentPrimitiveType = -1; - texCoordS = 0.0f; - texCoordT = 0.0f; - normalX = 0.0f; - normalY = 0.0f; - normalZ = 1.0f; - hasColor = false; - hasTexCoord = false; - hasNormal = false; + public static void reset() { + tessellator.reset(); } /** @@ -600,10 +112,10 @@ public class ImmediateModeRecorder { * @param count Number of vertices * @return Result containing converted geometry, or null if no geometry produced */ - public Result processDrawArrays(int mode, int first, int count) { - final var cas = GLStateManager.getClientArrayState(); - final var vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null; - final var colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null; + public static DirectTessellator processDrawArrays(int mode, int first, int count) { + final ClientArrayState cas = GLStateManager.getClientArrayState(); + final Buffer vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null; + final Buffer colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null; return convertClientArrays( mode, first, count, @@ -632,7 +144,7 @@ public class ImmediateModeRecorder { * @param colorStride Stride in bytes (0 for tightly packed) * @return Result containing converted geometry, or null if no geometry produced */ - public Result convertClientArrays( + public static DirectTessellator convertClientArrays( int mode, int first, int count, java.nio.Buffer vertexPointer, int vertexType, int vertexSize, int vertexStride, java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride @@ -645,12 +157,10 @@ public class ImmediateModeRecorder { // Determine color reader (hoisted out of loop) final ColorReader colorReader; - final int colorEffectiveStride; if (colorPointer == null) { colorReader = null; - colorEffectiveStride = 0; } else if (colorType == GL11.GL_FLOAT && colorPointer instanceof FloatBuffer fb) { - colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride; + final int colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride; final int strideInFloats = colorEffectiveStride / 4; colorReader = (idx) -> { final int offset = idx * strideInFloats; @@ -661,7 +171,7 @@ public class ImmediateModeRecorder { GLStateManager.glColor4f(r, g, b, a); }; } else if ((colorType == GL11.GL_UNSIGNED_BYTE || colorType == GL11.GL_BYTE) && colorPointer instanceof ByteBuffer bb) { - colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride; + final int colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride; colorReader = (idx) -> { final int offset = idx * colorEffectiveStride; final float r = (bb.get(offset) & 0xFF) / 255.0f; @@ -672,7 +182,6 @@ public class ImmediateModeRecorder { }; } else { // Unsupported color type - use white - colorEffectiveStride = 0; colorReader = (idx) -> GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } @@ -738,6 +247,8 @@ public class ImmediateModeRecorder { return end(); } + + @FunctionalInterface private interface ColorReader { void read(int index); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DisplayListCommand.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DisplayListCommand.java index 7d96f08b9..05622ef85 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DisplayListCommand.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DisplayListCommand.java @@ -17,22 +17,4 @@ public interface DisplayListCommand { default void delete() { // Most commands don't hold resources } - - /** - * Handle this command during display list optimization. - * - *

Commands override this to implement their optimization behavior: - *

    - *
  • Matrix transforms: accumulate into the optimizer, return false
  • - *
  • Push/Pop: update stack, return true to emit
  • - *
  • Barriers: emit pending transforms, return true to emit
  • - *
  • State changes: return true to emit
  • - *
- * - * @param ctx The optimization context providing access to transform state - * @return true if this command should be added to output, false if handled internally - */ - default boolean handleOptimization(OptimizationContext ctx) { - return true; - } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawCommand.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawCommand.java deleted file mode 100644 index 88be7bdfc..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawCommand.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; - -/** - * Represents a single draw call within a compiled display list. - * Each DrawCommand corresponds to one glBegin/glEnd block. - */ -@Desugar -public record DrawCommand( - int firstVertex, - int vertexCount, - int primitiveType -) {} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawRangeCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawRangeCmd.java deleted file mode 100644 index 2815272d5..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/DrawRangeCmd.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import org.jetbrains.annotations.NotNull; - -/** - * Command: Draw a range of vertices from a shared VBO. - *

- * DrawRangeCmd references a shared VBO owned by CompiledDisplayList.ownedVbos. - * Multiple DrawRangeCmds can reference different ranges within the same VBO, - * enabling format-based batching where all draws with the same vertex format - * share a single VBO. - *

- * Transform is NOT stored here - handled by TransformOptimizer emitting - * MultMatrixCmd before this command during optimization. - */ -@Desugar -public record DrawRangeCmd( - VertexBuffer sharedVbo, - int startVertex, - int vertexCount, - boolean hasBrightness -) implements DisplayListCommand { - - @Override - public void execute() { - sharedVbo.setupState(); - sharedVbo.draw(startVertex, vertexCount); - sharedVbo.cleanupState(); - } - - @Override - public void delete() { - // No-op: VBO lifetime is managed by CompiledDisplayList.ownedVbos - } - - @Override - public @NotNull String toString() { - return "DrawRange(start=" + startVertex + ", count=" + vertexCount + ", hasBrightness=" + hasBrightness + ")"; - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/MultMatrixCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/MultMatrixCmd.java index b68beba49..da2e43e81 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/MultMatrixCmd.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/MultMatrixCmd.java @@ -5,7 +5,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.jetbrains.annotations.NotNull; import org.joml.Matrix4f; import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/OptimizationContext.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/OptimizationContext.java deleted file mode 100644 index 5f957e4d5..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/OptimizationContext.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import org.joml.Matrix4f; - -/** - * Context provided to commands during display list optimization. - * Allows commands to interact with the transform optimizer and draw batcher. - */ -public interface OptimizationContext { - /** Get the accumulated MODELVIEW transform matrix. */ - Matrix4f getAccumulatedTransform(); - - /** Reset accumulated transform to identity. */ - void loadIdentity(); - - /** Push current accumulated transform onto stack. */ - void pushTransform(); - - /** Pop transform from stack, restoring previous accumulated value. */ - void popTransform(); - - /** Emit a MultMatrix command if accumulated differs from last emitted. */ - void emitPendingTransform(); - - /** Emit a MultMatrix command to reach the target transform. */ - void emitTransformTo(Matrix4f target); - - /** Add a command to the output list. */ - void emit(DisplayListCommand cmd); - - /** - * Mark that the GL matrix is at an absolute value (after LoadMatrix). - * Subsequent LoadIdentity commands must be emitted to reset to identity. - */ - void markAbsoluteMatrix(); - - /** - * Check if the GL matrix is at an absolute value and clear the flag. - * @return true if LoadMatrix was called and not yet reset by LoadIdentity - */ - boolean checkAndClearAbsoluteMatrix(); -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java index 030926d5e..10cb8b397 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java @@ -1,8 +1,9 @@ package com.gtnewhorizons.angelica.glsm.states; -import java.nio.Buffer; import org.lwjgl.opengl.GL11; +import java.nio.Buffer; + /** * Tracks OpenGL client array state (glVertexPointer, glColorPointer, etc.) * This state is NOT part of the server attribute stack (push/pop attrib), diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java index 1a868a63c..59a247004 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java @@ -1,8 +1,8 @@ package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack; import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack; +import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack; import lombok.Getter; import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/com/gtnewhorizons/angelica/hudcaching/HUDCaching.java b/src/main/java/com/gtnewhorizons/angelica/hudcaching/HUDCaching.java index 694acbef0..f183dbe93 100644 --- a/src/main/java/com/gtnewhorizons/angelica/hudcaching/HUDCaching.java +++ b/src/main/java/com/gtnewhorizons/angelica/hudcaching/HUDCaching.java @@ -1,11 +1,12 @@ package com.gtnewhorizons.angelica.hudcaching; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.CustomFramebuffer; import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.SharedDepthFramebuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexArrayBuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.holoinventory.HoloInventoryReflectionCompat; @@ -35,7 +36,7 @@ public class HUDCaching { private static boolean dirty = true; private static long nextHudRefresh; - private static VertexBuffer quadVAO; + private static IVertexArrayObject quadVAO; private static float quadWidth; private static float quadHeight; @@ -188,14 +189,19 @@ public class HUDCaching { private static void rebuildVAO(float width, float height) { - final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet(); + final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(DefaultVertexFormat.POSITION_TEXTURE); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(0, height, 0.0, 0, 0); tessellator.addVertexWithUV(width, height, 0.0, 1, 0); tessellator.addVertexWithUV(width, 0, 0.0, 1, 1); tessellator.addVertexWithUV(0, 0, 0.0, 0, 1); tessellator.draw(); - quadVAO = TessellatorManager.stopCapturingToVAO(quadVAO, DefaultVertexFormat.POSITION_TEXTURE); + if (quadVAO == null) { + quadVAO = tessellator.uploadToVBO(VertexBufferType.MUTABLE); + } else { + tessellator.updateToVBO(quadVAO.getVBO()); + } + TessellatorManager.stopCapturingDirect(); } public static void disableHoloInventory() { diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java index af2f6f86b..2f3450e37 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java @@ -45,8 +45,11 @@ public final class AngelicaRedirector { private static final String GL12 = "org/lwjgl/opengl/GL12"; private static final String GL13 = "org/lwjgl/opengl/GL13"; private static final String GL14 = "org/lwjgl/opengl/GL14"; + private static final String GL15 = "org/lwjgl/opengl/GL15"; private static final String GL20 = "org/lwjgl/opengl/GL20"; private static final String GL30 = "org/lwjgl/opengl/GL30"; + private static final String ARBVertexArrayObject = "org/lwjgl/opengl/ARBVertexArrayObject"; + private static final String APPLEVertexArrayObject = "org/lwjgl/opengl/APPLEVertexArrayObject"; private static final String Project = "org/lwjgl/util/glu/Project"; private static final String OpenGlHelper = "net/minecraft/client/renderer/OpenGlHelper"; private static final String EXTBlendFunc = "org/lwjgl/opengl/EXTBlendFuncSeparate"; @@ -225,6 +228,9 @@ public final class AngelicaRedirector { .add("glBlendColor") .add("glBlendEquation") ); + methodRedirects.put(GL15, RedirectMap.newMap() + .add("glBindBuffer") + ); methodRedirects.put(GL20, RedirectMap.newMap() .add("glBlendEquationSeparate") .add("glDrawBuffers") @@ -234,8 +240,11 @@ public final class AngelicaRedirector { .add("glUseProgram") ); methodRedirects.put(GL30, RedirectMap.newMap() + .add("glBindVertexArray") .add("glBindFramebuffer") ); + + // MINECRAFT methodRedirects.put(OpenGlHelper, RedirectMap.newMap() .add("glBlendFunc", "tryBlendFuncSeparate") .add("func_148821_a", "tryBlendFuncSeparate") @@ -249,7 +258,22 @@ public final class AngelicaRedirector { .add("isFramebufferEnabled") ); methodRedirects.put(EXTBlendFunc, RedirectMap.newMap().add("glBlendFuncSeparateEXT", "tryBlendFuncSeparate")); - methodRedirects.put(ARBMultiTexture, RedirectMap.newMap().add("glActiveTextureARB")); + + // ARB + methodRedirects.put(ARBMultiTexture, RedirectMap.newMap() + .add("glActiveTextureARB") + ); + methodRedirects.put(ARBVertexArrayObject, RedirectMap.newMap() + .add("glBindVertexArray") + ); + + + // APPLE + methodRedirects.put(APPLEVertexArrayObject, RedirectMap.newMap() + .add("glBindVertexArrayAPPLE") + ); + + // OTHER methodRedirects.put(Project, RedirectMap.newMap().add("gluPerspective")); final String glPrefix = "org/lwjgl/opengl/GL"; @@ -354,7 +378,7 @@ public final class AngelicaRedirector { return changed; } - private static class RedirectMap extends HashMap { + private static final class RedirectMap extends HashMap { public static RedirectMap newMap() { return new RedirectMap<>(); diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java index 484333090..82f9d196e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java @@ -21,16 +21,18 @@ package com.gtnewhorizons.angelica.render; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; -import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import jss.notfine.core.Settings; import jss.notfine.gui.options.named.GraphicsQualityOff; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourceManager; @@ -46,7 +48,6 @@ public class CloudRenderer implements IResourceManagerReloadListener { private static final float PX_SIZE = 1 / 256F; // Building constants. - private static final VertexFormat FORMAT = DefaultVertexFormat.POSITION_TEXTURE_COLOR; private static final int TOP_SECTIONS = 12; // Number of slices a top face will span. private static final int HEIGHT = 4; private static final float INSET = 0.001F; @@ -59,7 +60,7 @@ public class CloudRenderer implements IResourceManagerReloadListener { private final Minecraft mc = Minecraft.getMinecraft(); private final ResourceLocation texture = new ResourceLocation("textures/environment/clouds.png"); - private VertexBuffer vbo; + private IVertexArrayObject vao; private int cloudMode = -1; private int renderDistance = -1; private int cloudElevation = -1; @@ -92,7 +93,7 @@ public class CloudRenderer implements IResourceManagerReloadListener { return (float)Math.ceil(value / scale) * scale; } - private void vertices(CapturingTessellator tessellator) { + private void vertices(Tessellator tessellator) { GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore(); boolean fancy = cloudGraphicsQuality == GraphicsQualityOff.FANCY || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics; @@ -133,18 +134,20 @@ public class CloudRenderer implements IResourceManagerReloadListener { float v1 = sectZ1 * sectPx; // Bottom - tessellator.pos(sectX0, 0, sectZ0).tex(u0, v0).color(bCol, bCol, bCol, ALPHA).endVertex(); - tessellator.pos(sectX1, 0, sectZ0).tex(u1, v0).color(bCol, bCol, bCol, ALPHA).endVertex(); - tessellator.pos(sectX1, 0, sectZ1).tex(u1, v1).color(bCol, bCol, bCol, ALPHA).endVertex(); - tessellator.pos(sectX0, 0, sectZ1).tex(u0, v1).color(bCol, bCol, bCol, ALPHA).endVertex(); + tessellator.setColorRGBA_F(bCol, bCol, bCol, ALPHA); + tessellator.addVertexWithUV(sectX0, 0, sectZ0, u0, v0); + tessellator.addVertexWithUV(sectX1, 0, sectZ0, u1, v0); + tessellator.addVertexWithUV(sectX1, 0, sectZ1, u1, v1); + tessellator.addVertexWithUV(sectX0, 0, sectZ1, u0, v1); if (fancy) { final int height = HEIGHT * scaleMult; // Top - tessellator.pos(sectX0, height, sectZ0).tex(u0, v0).color(1, 1, 1, ALPHA).endVertex(); - tessellator.pos(sectX0, height, sectZ1).tex(u0, v1).color(1, 1, 1, ALPHA).endVertex(); - tessellator.pos(sectX1, height, sectZ1).tex(u1, v1).color(1, 1, 1, ALPHA).endVertex(); - tessellator.pos(sectX1, height, sectZ0).tex(u1, v0).color(1, 1, 1, ALPHA).endVertex(); + tessellator.setColorRGBA_F(1, 1, 1, ALPHA); + tessellator.addVertexWithUV(sectX0, height, sectZ0, u0, v0); + tessellator.addVertexWithUV(sectX0, height, sectZ1, u0, v1); + tessellator.addVertexWithUV(sectX1, height, sectZ1, u1, v1); + tessellator.addVertexWithUV(sectX1, height, sectZ0, u1, v0); float slice; float sliceCoord0; @@ -157,10 +160,11 @@ public class CloudRenderer implements IResourceManagerReloadListener { // X sides if (slice > -CULL_DIST) { slice += INSET; - tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); + tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA); + tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1); + tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1); + tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0); + tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0); slice -= INSET; } @@ -168,10 +172,11 @@ public class CloudRenderer implements IResourceManagerReloadListener { if (slice <= CULL_DIST) { slice -= INSET; - tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); - tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex(); + tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA); + tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0); + tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0); + tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1); + tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1); slice += INSET; } } @@ -183,10 +188,11 @@ public class CloudRenderer implements IResourceManagerReloadListener { // Z sides if (slice > -CULL_DIST) { slice += INSET; - tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); + tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA); + tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0); + tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1); + tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1); + tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0); slice -= INSET; } @@ -194,10 +200,11 @@ public class CloudRenderer implements IResourceManagerReloadListener { if (slice <= CULL_DIST) { slice -= INSET; - tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); - tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex(); + tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA); + tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0); + tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1); + tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1); + tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0); slice += INSET; } } @@ -211,18 +218,16 @@ public class CloudRenderer implements IResourceManagerReloadListener { } private void dispose() { - if (vbo != null) { - vbo.close(); - vbo = null; + if (vao != null) { + vao.delete(); + vao = null; } } private void build() { - CapturingTessellator tess = TessellatorManager.startCapturingAndGet(); - - vertices(tess); - - this.vbo = TessellatorManager.stopCapturingToVAO(FORMAT); + final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(); + this.vertices(tessellator); + this.vao = DirectTessellator.stopCapturingToVBO(VertexBufferType.IMMUTABLE); } private int fullCoord(double coord, int scale) { // Corrects misalignment of UV offset when on negative coords. @@ -230,7 +235,7 @@ public class CloudRenderer implements IResourceManagerReloadListener { } private boolean isBuilt() { - return vbo != null; + return vao != null; } public void checkSettings() { @@ -345,12 +350,12 @@ public class CloudRenderer implements IResourceManagerReloadListener { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); mc.renderEngine.bindTexture(texture); - vbo.setupState(); + vao.bind(); // Depth pass to prevent insides rendering from the outside. GLStateManager.glColorMask(false, false, false, false); - vbo.draw(); + vao.draw(); // Full render. if (!mc.gameSettings.anaglyph) { @@ -373,15 +378,15 @@ public class CloudRenderer implements IResourceManagerReloadListener { GLStateManager.disableTexture(); GLStateManager.glDepthMask(false); GLStateManager.disableFog(); - vbo.draw(); + vao.draw(); GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL); GLStateManager.glDepthMask(true); GLStateManager.enableTexture(); GLStateManager.enableFog(); } - vbo.draw(); - vbo.cleanupState(); // Unbind buffer and disable pointers. + vao.draw(); + vao.unbind(); // Unbind buffer. // Disable our coloring. GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java b/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java index 99e3c16d1..2f069dfca 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java @@ -25,38 +25,32 @@ package com.gtnewhorizons.angelica.rendering; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.config.AngelicaConfig; -import it.unimi.dsi.fastutil.HashCommon; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import java.nio.ByteBuffer; import lombok.Data; import lombok.NoArgsConstructor; import net.minecraft.client.Minecraft; -import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; public class ItemRenderListManager { // Least used element is at position 0. This is in theory slightly faster. private static final Object2ObjectLinkedOpenHashMap vboCache = new Object2ObjectLinkedOpenHashMap<>(64); - // Formula: (widthSubdivisions * 2 + heightSubdivisions * 2 + 2) * 4 * vertexSize - // Using 256 as both variables due to enchants, to prevent later re-allocations. - private static ByteBuffer quadBuffer = BufferUtils.createByteBuffer( - (1026 * DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize()) << 2 - ); - // 1 minute private static final int EXPIRY_TICKS = 1_200; private static int smallestExpiry; private static final ItemProp prop = new ItemProp(); - public static VertexBuffer pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { + public static CachedVBO pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { prop.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); if (!vboCache.isEmpty()) { @@ -92,42 +86,35 @@ public class ItemRenderListManager { vbo.expiry = getElapsedTicks() + EXPIRY_TICKS; - TessellatorManager.startCapturing(); - - return vbo.vertexBuffer; + return vbo; } - public static void post(CapturingTessellator tessellator, VertexBuffer vbo) { - final var quads = TessellatorManager.stopCapturingToPooledQuads(); - final int size = quads.size(); - - final int needed = (DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize() * size) << 2; - if (quadBuffer.capacity() < needed) { - quadBuffer = BufferUtils.createByteBuffer(HashCommon.nextPowerOfTwo(needed)); - } - - for (int i = 0; i < size; i++) { - DefaultVertexFormat.POSITION_TEXTURE_NORMAL.writeQuad(quads.get(i), quadBuffer); - } - - quadBuffer.flip(); - vbo.upload(quadBuffer); - quadBuffer.clear(); - - tessellator.clearQuads(); - vbo.render(); + public static void post(DirectTessellator tessellator, CachedVBO vbo) { + vbo.allocate(tessellator); + TessellatorManager.stopCapturingDirect(); + vbo.vertexBuffer.render(); } private static int getElapsedTicks() { return Minecraft.getMinecraft().thePlayer.ticksExisted; } - private static final class CachedVBO { - private VertexBuffer vertexBuffer; + public static final class CachedVBO { + private final IVertexArrayObject vertexBuffer; + private final IndexBuffer ebo; private int expiry; public CachedVBO() { - this.vertexBuffer = VAOManager.createVAO(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_QUADS); + this.ebo = new IndexBuffer(); + this.vertexBuffer = VAOManager.createMutableVAO( + DefaultVertexFormat.POSITION_TEXTURE_NORMAL, + GL11.GL_TRIANGLES, + ebo + ); + } + + private void allocate(DirectTessellator tessellator) { + tessellator.allocateToVBO(vertexBuffer, ebo); } private void render(int elapsedTicks) { @@ -136,8 +123,8 @@ public class ItemRenderListManager { } private void delete() { - vertexBuffer.close(); - vertexBuffer = null; + vertexBuffer.delete(); + // EBO gets deleted by vertexBuffer.delete() } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java index d5a573499..3ce7a4374 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice; import org.lwjgl.opengl.GL15; import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; @@ -10,7 +11,7 @@ public class CeleritasSetup { public static void ensureInitialized() { if (!initialized && AngelicaConfig.enableCeleritas) { - GLRenderDevice.VANILLA_STATE_RESETTER = () -> GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLRenderDevice.VANILLA_STATE_RESETTER = () -> GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); LOGGER.debug("Celeritas init"); initialized = true; } diff --git a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java b/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java index e89772d2f..dd4f03821 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java @@ -1,8 +1,10 @@ package net.coderbot.iris.pipeline; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import net.minecraft.client.Minecraft; @@ -42,7 +44,7 @@ public class HorizonRenderer { * Sine of 22.5 degrees. */ private static final double SIN_22_5 = Math.sin(Math.toRadians(22.5)); - private VertexBuffer vertexBuffer; + private IVertexArrayObject vao; private int currentRenderDistance; public HorizonRenderer() { @@ -52,13 +54,17 @@ public class HorizonRenderer { } private void rebuildBuffer() { - final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet(); + if (this.vao != null) { + this.vao.delete(); + } + + final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(DefaultVertexFormat.POSITION); // Build the horizon quads into a buffer tessellator.startDrawingQuads(); //(GL11.GL_QUADS, DefaultVertexFormat.POSITION); buildHorizon(currentRenderDistance * 16, tessellator); - this.vertexBuffer = TessellatorManager.stopCapturingToVAO(vertexBuffer, DefaultVertexFormat.POSITION); + this.vao = DirectTessellator.stopCapturingToVBO(VertexBufferType.IMMUTABLE); } private void buildQuad(Tessellator consumer, double x1, double z1, double x2, double z2) { @@ -145,18 +151,24 @@ public class HorizonRenderer { buildBottomPlane(consumer, 384); } - public void renderHorizon(FloatBuffer floatBuffer) { + public void renderHorizon(FloatBuffer matrix) { if (currentRenderDistance != Minecraft.getMinecraft().gameSettings.renderDistanceChunks) { currentRenderDistance = Minecraft.getMinecraft().gameSettings.renderDistanceChunks; rebuildBuffer(); } - vertexBuffer.setupState(); - vertexBuffer.draw(floatBuffer); - vertexBuffer.cleanupState(); + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + GL11.glMultMatrix(matrix); + + vao.bind(); + vao.draw(); + vao.unbind(); + + GL11.glPopMatrix(); } public void destroy() { - vertexBuffer.close(); + vao.delete(); } } diff --git a/src/main/resources/META-INF/angelica_at.cfg b/src/main/resources/META-INF/angelica_at.cfg index f648f0be2..934c97465 100644 --- a/src/main/resources/META-INF/angelica_at.cfg +++ b/src/main/resources/META-INF/angelica_at.cfg @@ -30,9 +30,12 @@ public net.minecraft.client.renderer.Tessellator field_78408_v # xOffset public net.minecraft.client.renderer.Tessellator field_78407_w # yOffset public net.minecraft.client.renderer.Tessellator field_78417_x # zOffset public net.minecraft.client.renderer.Tessellator field_78415_z # isDrawing -public net.minecraft.client.renderer.Tessellator field_78388_E # bufferSize +public net.minecraft.client.renderer.Tessellator field_78388_E # rawBufferSize +public net.minecraft.client.renderer.Tessellator field_78416_y # normal +public net.minecraft.client.renderer.Tessellator rawBufferSize # rawBufferSize public net.minecraft.client.renderer.Tessellator field_78410_t # isColorDisabled public net.minecraft.client.renderer.Tessellator func_78379_d()V # void reset() +public net.minecraft.client.renderer.Tessellator field_78394_d # byteBuffer public net.minecraft.client.model.ModelRenderer field_78812_q # compiled public net.minecraft.client.model.ModelRenderer field_78811_r # displayList diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/itemrenderer/MixinItemRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/itemrenderer/MixinItemRenderer.java index cb3b15420..5d507c02e 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/itemrenderer/MixinItemRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/itemrenderer/MixinItemRenderer.java @@ -25,8 +25,9 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.itemrenderer; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizons.angelica.rendering.ItemRenderListManager; import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod; @@ -44,9 +45,9 @@ public abstract class MixinItemRenderer { @WrapMethod(method = "renderItemIn2D") private static void angelica$cacheItem(Tessellator tessellator, float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness, Operation original) { - final VertexBuffer vbo = ItemRenderListManager.pre(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); + final ItemRenderListManager.CachedVBO vbo = ItemRenderListManager.pre(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); if (vbo != null) { - final CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); + final DirectTessellator tess = TessellatorManager.startCapturingDirect(); original.call(tess, minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); ItemRenderListManager.post(tess, vbo); } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java index 68eb4a5f3..f00b4dc96 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java @@ -1,18 +1,11 @@ package com.gtnewhorizons.angelica.glsm; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; -import org.joml.Matrix4f; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; +import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; +import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Helper class for building test data for display list batching tests. @@ -22,398 +15,51 @@ public final class DisplayListTestHelper { private DisplayListTestHelper() {} - // ==================== Quad Builders ==================== - - /** - * Create a quad from 4 vertex positions. - * @param vertices 4 vertices, each as [x, y, z] - */ - public static ModelQuad createQuad(float[][] vertices) { - if (vertices.length != 4) { - throw new IllegalArgumentException("Quad requires exactly 4 vertices"); - } - - ModelQuad quad = new ModelQuad(); - for (int i = 0; i < 4; i++) { - quad.setX(i, vertices[i][0]); - quad.setY(i, vertices[i][1]); - quad.setZ(i, vertices[i][2]); - // Set default color (white, fully opaque) - quad.setColor(i, 0xFFFFFFFF); - // Set default UVs - quad.setTexU(i, i == 1 || i == 2 ? 1.0f : 0.0f); - quad.setTexV(i, i >= 2 ? 1.0f : 0.0f); - } - return quad; + public static void createSimpleDraw() { + final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator(); + // Record a single quad using immediate mode + recorder.startDrawing(GL11.GL_QUADS); + recorder.addVertex(0, 0, 0); + recorder.addVertex(1, 0, 0); + recorder.addVertex(1, 1, 0); + recorder.addVertex(0, 1, 0); + DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end()); } - /** - * Create a simple unit quad at origin (0,0,0) to (1,1,0). - */ - public static ModelQuad createSimpleQuad() { - return createQuad(new float[][] { - {0, 0, 0}, - {1, 0, 0}, - {1, 1, 0}, - {0, 1, 0} - }); + public static void createTextureDraw() { + final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator(); + // Record a single quad using immediate mode + recorder.startDrawing(GL11.GL_QUADS); + recorder.setTextureUV(0, 0); + recorder.addVertex(0, 0, 0); + recorder.setTextureUV(1, 0); + recorder.addVertex(1, 0, 0); + recorder.setTextureUV(1, 1); + recorder.addVertex(1, 1, 0); + recorder.setTextureUV(0, 1); + recorder.addVertex(0, 1, 0); + DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end()); } - /** - * Create a quad at a specific position (offset from origin). - */ - public static ModelQuad createQuadAt(float x, float y, float z) { - return createQuad(new float[][] { - {x, y, z}, - {x + 1, y, z}, - {x + 1, y + 1, z}, - {x, y + 1, z} - }); + public static void createColorDraw() { + final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator(); + // Record a single quad using immediate mode + recorder.startDrawing(GL11.GL_QUADS); + recorder.setColorRGBA(255, 255, 255, 255); + recorder.addVertex(0, 0, 0); + recorder.addVertex(1, 0, 0); + recorder.addVertex(1, 1, 0); + recorder.addVertex(0, 1, 0); + DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end()); } - /** - * Create multiple simple quads. - */ - public static List createQuads(int count) { - List quads = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - quads.add(createSimpleQuad()); - } - return quads; - } - - // ==================== AccumulatedDraw Builders ==================== - - /** - * Create an AccumulatedDraw with specified parameters. - */ - public static AccumulatedDraw createDraw( - List quads, - Matrix4f transform, - CapturingTessellator.Flags flags, - int commandIndex) { - return new AccumulatedDraw(quads, transform, flags, commandIndex, 0); - } - - public static AccumulatedDraw createDraw( - List quads, - Matrix4f transform, - CapturingTessellator.Flags flags, - int commandIndex, - int matrixGeneration) { - return new AccumulatedDraw(quads, transform, flags, commandIndex, matrixGeneration, 0); - } - - public static AccumulatedDraw createDraw( - List quads, - Matrix4f transform, - CapturingTessellator.Flags flags, - int commandIndex, - int matrixGeneration, - int stateGeneration) { - return new AccumulatedDraw(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration); - } - - /** - * Create an AccumulatedDraw with a single quad and identity transform. - */ - public static AccumulatedDraw createSimpleDraw(int commandIndex) { - return createDraw( - Collections.singletonList(createSimpleQuad()), - new Matrix4f(), - positionOnly(), - commandIndex - ); - } - - /** - * Create an AccumulatedDraw with specified transform. - */ - public static AccumulatedDraw createDrawWithTransform(Matrix4f transform, int commandIndex, int matrixGeneration) { - return createDraw( - Collections.singletonList(createSimpleQuad()), - transform, - positionOnly(), - commandIndex, - matrixGeneration - ); - } - - /** - * Create an AccumulatedDraw with specified transform and stateGeneration. - */ - public static AccumulatedDraw createDrawWithTransformAndBatch(Matrix4f transform, int commandIndex, int matrixGeneration, int stateGeneration) { - return createDraw( - Collections.singletonList(createSimpleQuad()), - transform, - positionOnly(), - commandIndex, - matrixGeneration, - stateGeneration - ); - } - - /** - * Create an AccumulatedDraw with specified flags. - */ - public static AccumulatedDraw createDrawWithFlags(CapturingTessellator.Flags flags, int commandIndex) { - return createDraw( - Collections.singletonList(createSimpleQuad()), - new Matrix4f(), - flags, - commandIndex - ); - } - - /** - * Create an AccumulatedDraw with multiple quads. - */ - public static AccumulatedDraw createDrawWithQuads(int quadCount, int commandIndex) { - return createDraw( - createQuads(quadCount), - new Matrix4f(), - positionOnly(), - commandIndex - ); - } - - // ==================== Flag Helpers ==================== - - /** - * Flags for position-only vertices (no color, texture, brightness, normals). - */ - public static CapturingTessellator.Flags positionOnly() { - return new CapturingTessellator.Flags(false, false, false, false); - } - - /** - * Flags for position + color vertices. - */ - public static CapturingTessellator.Flags positionColor() { - return new CapturingTessellator.Flags(false, false, true, false); - } - - /** - * Flags for position + texture vertices. - */ - public static CapturingTessellator.Flags positionTexture() { - return new CapturingTessellator.Flags(true, false, false, false); - } - - /** - * Flags for position + color + texture vertices. - */ - public static CapturingTessellator.Flags positionColorTexture() { - return new CapturingTessellator.Flags(true, false, true, false); - } - - /** - * Flags for full vertex format (all attributes). - */ - public static CapturingTessellator.Flags fullFormat() { - return new CapturingTessellator.Flags(true, true, true, true); - } - - // ==================== Transform Helpers ==================== - - /** - * Create identity transform. - */ - public static Matrix4f identity() { - return new Matrix4f(); - } - - /** - * Create translation transform. - */ - public static Matrix4f translate(float x, float y, float z) { - return new Matrix4f().translate(x, y, z); - } - - /** - * Create rotation transform (around Y axis). - */ - public static Matrix4f rotateY(float degrees) { - return new Matrix4f().rotateY((float) Math.toRadians(degrees)); - } - - /** - * Create scale transform. - */ - public static Matrix4f scale(float s) { - return new Matrix4f().scale(s); - } - - // ==================== Primitive Builders (Lines, Triangles) ==================== - - /** - * Create a ModelLine from two vertex positions. - */ - public static ModelLine createLine(float x1, float y1, float z1, float x2, float y2, float z2) { - ModelLine line = new ModelLine(); - line.setX(0, x1); - line.setY(0, y1); - line.setZ(0, z1); - line.setColor(0, 0xFFFFFFFF); - line.setTexU(0, 0.0f); - line.setTexV(0, 0.0f); - line.setLight(0, 0); - line.setForgeNormal(0, 0); - - line.setX(1, x2); - line.setY(1, y2); - line.setZ(1, z2); - line.setColor(1, 0xFFFFFFFF); - line.setTexU(1, 1.0f); - line.setTexV(1, 1.0f); - line.setLight(1, 0); - line.setForgeNormal(1, 0); - return line; - } - - /** - * Create a simple unit line from (0,0,0) to (1,0,0). - */ - public static ModelLine createSimpleLine() { - return createLine(0, 0, 0, 1, 0, 0); - } - - /** - * Create multiple simple lines. - */ - public static List createLines(int count) { - List lines = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - lines.add(createLine(i, 0, 0, i + 1, 0, 0)); - } - return lines; - } - - /** - * Create a ModelTriangle from three vertex positions. - */ - public static ModelTriangle createTriangle(float x1, float y1, float z1, - float x2, float y2, float z2, - float x3, float y3, float z3) { - ModelTriangle tri = new ModelTriangle(); - tri.setX(0, x1); - tri.setY(0, y1); - tri.setZ(0, z1); - tri.setColor(0, 0xFFFFFFFF); - tri.setTexU(0, 0.0f); - tri.setTexV(0, 0.0f); - tri.setLight(0, 0); - tri.setForgeNormal(0, 0); - - tri.setX(1, x2); - tri.setY(1, y2); - tri.setZ(1, z2); - tri.setColor(1, 0xFFFFFFFF); - tri.setTexU(1, 1.0f); - tri.setTexV(1, 0.0f); - tri.setLight(1, 0); - tri.setForgeNormal(1, 0); - - tri.setX(2, x3); - tri.setY(2, y3); - tri.setZ(2, z3); - tri.setColor(2, 0xFFFFFFFF); - tri.setTexU(2, 0.5f); - tri.setTexV(2, 1.0f); - tri.setLight(2, 0); - tri.setForgeNormal(2, 0); - return tri; - } - - /** - * Create a simple unit triangle at origin. - */ - public static ModelTriangle createSimpleTriangle() { - return createTriangle(0, 0, 0, 1, 0, 0, 0.5f, 1, 0); - } - - /** - * Create multiple simple triangles. - */ - public static List createTriangles(int count) { - List triangles = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - triangles.add(createTriangle(i, 0, 0, i + 1, 0, 0, i + 0.5f, 1, 0)); - } - return triangles; - } - - /** - * Create a mixed list of primitives (lines and triangles). - */ - public static List createMixedPrimitives(int lineCount, int triangleCount) { - List primitives = new ArrayList<>(lineCount + triangleCount); - for (int i = 0; i < lineCount; i++) { - primitives.add(createLine(i, 0, 0, i + 1, 0, 0)); - } - for (int i = 0; i < triangleCount; i++) { - primitives.add(createTriangle(i, 1, 0, i + 1, 1, 0, i + 0.5f, 2, 0)); - } - return primitives; - } - - // ==================== AccumulatedPrimitiveDraw Builders ==================== - - /** - * Create an AccumulatedPrimitiveDraw with specified parameters. - */ - public static AccumulatedPrimitiveDraw createPrimitiveDraw( - List primitives, - Matrix4f transform, - CapturingTessellator.Flags flags, - int commandIndex) { - return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex, 0); - } - - public static AccumulatedPrimitiveDraw createPrimitiveDraw( - List primitives, - Matrix4f transform, - CapturingTessellator.Flags flags, - int commandIndex, - int matrixGeneration) { - return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex, matrixGeneration); - } - - /** - * Create an AccumulatedPrimitiveDraw with lines only. - */ - public static AccumulatedPrimitiveDraw createLinesDraw(int lineCount, int commandIndex) { - List primitives = new ArrayList<>(lineCount); - for (ModelLine line : createLines(lineCount)) { - primitives.add(line); - } - return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); - } - - /** - * Create an AccumulatedPrimitiveDraw with triangles only. - */ - public static AccumulatedPrimitiveDraw createTrianglesDraw(int triangleCount, int commandIndex) { - List primitives = new ArrayList<>(triangleCount); - for (ModelTriangle tri : createTriangles(triangleCount)) { - primitives.add(tri); - } - return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); - } - - /** - * Create an AccumulatedPrimitiveDraw with mixed lines and triangles. - */ - public static AccumulatedPrimitiveDraw createMixedPrimitiveDraw(int lineCount, int triangleCount, int commandIndex) { - List primitives = createMixedPrimitives(lineCount, triangleCount); - return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); - } - - /** - * Create an AccumulatedPrimitiveDraw with specified transform. - */ - public static AccumulatedPrimitiveDraw createPrimitiveDrawWithTransform( - List primitives, Matrix4f transform, int commandIndex) { - return createPrimitiveDraw(primitives, transform, positionOnly(), commandIndex); + public static CompiledDisplayList createDisplayList(Runnable runnable) { + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE); + runnable.run(); + GLStateManager.glEndList(); + CompiledDisplayList compiled = DisplayListManager.getDisplayList(list); + assertNotNull(compiled, "Display list should be compiled"); + return compiled; } } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Batching_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Batching_Test.java index 1a99385bc..086b2bdac 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Batching_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Batching_Test.java @@ -1,19 +1,15 @@ package com.gtnewhorizons.angelica.glsm; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizons.angelica.AngelicaExtension; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; -import com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd; -import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd; -import org.joml.Matrix4f; +import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; +import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBO; +import com.gtnewhorizons.angelica.glsm.recording.GLCommand; +import it.unimi.dsi.fastutil.ints.Int2IntMap; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; import static com.gtnewhorizons.angelica.glsm.DisplayListTestHelper.*; @@ -28,167 +24,99 @@ import static org.junit.jupiter.api.Assertions.*; *

  • Different transforms produce separate DrawRangeCmd but share the VBO
  • *
  • Different formats produce separate VBOs
  • * - * - *

    Tests call {@link DisplayListManager#buildOptimizedDisplayList} directly - * with manually constructed AccumulatedDraws. GL context needed for VBO creation.

    */ @ExtendWith(AngelicaExtension.class) class GLSM_DisplayList_Batching_Test { - // ==================== Helper Methods ==================== - - private long countDrawRangeCmds(DisplayListCommand[] commands) { - long count = 0; - for (DisplayListCommand cmd : commands) { - if (cmd instanceof DrawRangeCmd) count++; + private static int getVBOCount(CompiledDisplayList compiledDisplayList) { + Set vaos = new HashSet<>(); + for (DisplayListVBO.SubVBO vbo : compiledDisplayList.getOwnedVbos().getVBOs()) { + vaos.add(vbo.getVAO().getVBO()); } - return count; - } - - private long countMultMatrixCmds(DisplayListCommand[] commands) { - long count = 0; - for (DisplayListCommand cmd : commands) { - if (cmd instanceof MultMatrixCmd) count++; - } - return count; - } - - private Set getUniqueVBOs(DisplayListCommand[] commands) { - Set vbos = new HashSet<>(); - for (DisplayListCommand cmd : commands) { - if (cmd instanceof DrawRangeCmd rangeCmd) { - vbos.add(rangeCmd.sharedVbo()); - } - } - return vbos; + return vaos.size(); } // ==================== Pure Unit Tests (No GL Context) ==================== @Test void testConsecutiveDrawsWithSameFormatShareSingleVBO() { - // Setup: 3 draws at the same command index, same format - List draws = new ArrayList<>(); - draws.add(createSimpleDraw(0)); - draws.add(createSimpleDraw(0)); - draws.add(createSimpleDraw(0)); + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); + createSimpleDraw(); + createSimpleDraw(); + }); - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); // Verify: 1 VBO for all draws (format-based batching) - assertEquals(1, result.ownedVbos().length, + assertEquals(1, getVBOCount(compiled), "3 draws with same format should produce 1 shared VBO"); // Verify: 1 DrawRangeCmd covering all geometry - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); assertEquals(1, drawCount, "3 consecutive draws with same format and transform should produce 1 DrawRangeCmd"); + + } @Test void testDrawsWithDifferentFormatsProduceSeparateVBOs() { - // Setup: 3 draws with different formats - List draws = new ArrayList<>(); - draws.add(createDrawWithFlags(positionOnly(), 0)); - draws.add(createDrawWithFlags(positionTexture(), 0)); - draws.add(createDrawWithFlags(positionColorTexture(), 0)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); - + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); + createTextureDraw(); + createColorDraw(); + }); // Verify: 3 VBOs (one per format) - assertEquals(3, result.ownedVbos().length, + assertEquals(3, getVBOCount(compiled), "3 draws with different formats should produce 3 VBOs"); // Verify: 3 DrawRangeCmds - long drawCount = countDrawRangeCmds(optimized); - assertEquals(3, drawCount, "3 draws with different formats should produce 3 DrawRangeCmds"); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); + int drawRestoreCount = counts.getOrDefault(GLCommand.DRAW_RANGE_RESTORE, 0); + assertEquals(1, drawCount, "3 draws with different formats should produce 3 DrawRangeCmds"); + assertEquals(2, drawRestoreCount, "3 draws with different formats should produce 3 DrawRangeCmds"); } @Test void testDifferentTransformsSameFormatShareVBO() { - // Setup: draws with different transforms but same format - // With format-based batching, they share 1 VBO but produce separate DrawRangeCmds - List draws = new ArrayList<>(); - draws.add(createDrawWithTransform(new Matrix4f(), 0, 0)); // Identity transform, gen=0 - draws.add(createDrawWithTransform(new Matrix4f().translate(1.0f, 0.0f, 0.0f), 1, 1)); // T(1), gen=1 - draws.add(createDrawWithTransform(new Matrix4f().translate(3.0f, 0.0f, 0.0f), 2, 2)); // T(3), gen=2 - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); + GLStateManager.glTranslatef(1, 0, 0); + createSimpleDraw(); + GLStateManager.glTranslatef(2, 0, 0); + createSimpleDraw(); + }); // Verify: 1 shared VBO (same format) - assertEquals(1, result.ownedVbos().length, "Draws with different transforms but same format should share 1 VBO"); + assertEquals(1, getVBOCount(compiled), "Draws with different transforms but same format should share 1 VBO"); // Verify: 3 DrawRangeCmds (one per draw, each with different transform) - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); + int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0); assertEquals(3, drawCount, "3 draws with different transforms should produce 3 DrawRangeCmds"); - - // Verify: All DrawRangeCmds reference the same VBO - Set uniqueVBOs = getUniqueVBOs(optimized); - assertEquals(1, uniqueVBOs.size(), "All DrawRangeCmds should reference the same shared VBO"); - - // Should have MultMatrix commands for the transforms (2 for T(1) and T(3)) - long matrixCount = countMultMatrixCmds(optimized); - assertEquals(2, matrixCount, "Should have MultMatrix commands for each unique transform"); + assertEquals(2, multMatrixCount, "Should have MultMatrix commands for each unique transform"); } @Test void testManyDrawsSameFormatProduceSingleVBO() { - // Setup: 100 draws at same position, same format - List draws = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - draws.add(createSimpleDraw(0)); - } - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + for (int i = 0; i < 100; i++) { + createSimpleDraw(); + } + }); // Verify: 1 shared VBO - assertEquals(1, result.ownedVbos().length, "100 draws with same format should produce 1 shared VBO"); + assertEquals(1, getVBOCount(compiled), "100 draws with same format should produce 1 shared VBO"); - // Verify: 1 DrawRangeCmd (all same transform) - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); assertEquals(1, drawCount, "100 consecutive draws with same format and transform should produce 1 DrawRangeCmd"); } - @Test - void testDrawsWithMultipleQuadsSameFormat() { - // Setup: draws with varying quad counts should share VBO if same format - List draws = new ArrayList<>(); - draws.add(createDrawWithQuads(1, 0)); - draws.add(createDrawWithQuads(5, 0)); - draws.add(createDrawWithQuads(10, 0)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 1 shared VBO (total 16 quads) - assertEquals(1, result.ownedVbos().length, "Draws with different quad counts but same format should share 1 VBO"); - - // Verify: 1 DrawRangeCmd (all same transform) - long drawCount = countDrawRangeCmds(optimized); - assertEquals(1, drawCount, "Draws with different quad counts but same format and transform should produce 1 DrawRangeCmd"); - } @Test void testCancellingTransformsProduceSeparateDrawRangeCmds() { @@ -199,128 +127,93 @@ class GLSM_DisplayList_Batching_Test { // With format-based batching: 1 shared VBO, 3 DrawRangeCmds // The key point: draws 1 and 3 have the same transform (identity) but draw 2 // has a different transform, so they can't all be merged. - - List draws = new ArrayList<>(); - // Draw 1: captured at identity, gen=0 - draws.add(createDrawWithTransform(new Matrix4f(), 0, 0)); - // Draw 2: captured at translate(0.5, 0, 0), gen=1 (transform changed) - draws.add(createDrawWithTransform(new Matrix4f().translate(0.5f, 0.0f, 0.0f), 1, 1)); - // Draw 3: captured back at identity, gen=2 (transform changed again) - draws.add(createDrawWithTransform(new Matrix4f(), 2, 2)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); + GLStateManager.glTranslatef(0.5f, 0, 0); + createSimpleDraw(); + GLStateManager.glTranslatef(-0.5f, 0, 0); + createSimpleDraw(); + }); // Verify: 1 shared VBO (same format) - assertEquals(1, result.ownedVbos().length, "Draws with same format should share 1 VBO regardless of transforms"); + assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO regardless of transforms"); // Verify: 3 DrawRangeCmds (different transforms require separate draw commands) - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); assertEquals(3, drawCount, "Draws with different recorded transforms must produce separate DrawRangeCmds"); } @Test void testDrawsWithSameTransformProduceSingleDrawRangeCmd() { - // Draws with the same format AND same transform produce a single DrawRangeCmd - Matrix4f commonTransform = new Matrix4f().translate(1.0f, 2.0f, 3.0f); - - List draws = new ArrayList<>(); - // All same transform → same generation → will batch into single DrawRangeCmd - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1)); - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1)); - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f); + createSimpleDraw(); + createSimpleDraw(); + createSimpleDraw(); + }); // Verify: 1 shared VBO - assertEquals(1, result.ownedVbos().length, - "Draws with same format should share 1 VBO"); + assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO"); - // Verify: 1 DrawRangeCmd (same format AND same transform) - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); + int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0); assertEquals(1, drawCount, "Draws with same format and transform should produce 1 DrawRangeCmd"); - - // Should have 1 MultMatrix for the common transform - long matrixCount = countMultMatrixCmds(optimized); - assertEquals(1, matrixCount, - "Should have exactly 1 MultMatrix for the common transform"); + assertEquals(1, multMatrixCount, "Should have exactly 1 MultMatrix for the common transform"); } /** * Test that draws with same transform but different stateGeneration do NOT merge. * This simulates state commands (draw barriers) between draws. - * - * Scenario: Draw1, glColor(red), Draw2, glBindTexture, Draw3 + *
    + * Scenario: Draw1, glColor(red), Draw2, glBindTexture, Draw3, Draw4 * All draws have same transform (gen=1) but different batches (0, 1, 2). - * Expected: 3 separate DrawRangeCmds (no merging across draw barriers). - * + * Expected: 3 separate DrawRangeCmds (only draw 3 & 4 should get merged). + *
    * This test will FAIL until FormatBuffer is fixed to check stateGeneration. */ @Test void testDrawsWithDifferentBatchIdDoNotMerge() { - // Setup: 3 draws with same transform generation but different batch IDs - // This simulates state commands (draw barriers) between draws - List draws = new ArrayList<>(); - draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 0, 1, 0)); // batch 0 - draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 1, 1, 1)); // batch 1 (state cmd between) - draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 2, 1, 2)); // batch 2 (state cmd between) - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); + DisplayListManager.drawBarrier(); + createSimpleDraw(); + DisplayListManager.drawBarrier(); + createSimpleDraw(); + createSimpleDraw(); + }); // Verify: 1 shared VBO (same format) - assertEquals(1, result.ownedVbos().length, - "Draws with same format should share 1 VBO"); + assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO"); // Verify: 3 DrawRangeCmds (NOT merged due to different batch IDs) - // BUG: Currently this will produce 1 DrawRangeCmd because FormatBuffer - // only checks matrixGeneration, not stateGeneration - long drawCount = countDrawRangeCmds(optimized); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); assertEquals(3, drawCount, "Draws with same transform but different batch IDs (draw barriers between) must NOT merge"); } @Test void testInterleavedFormatsProduceSeparateVBOs() { - // Setup: A A B A A - should produce 2 VBOs (one for A, one for B) - // With format-based batching, all A draws are grouped together and merged - // (since they have same transform), producing 2 DrawRangeCmds total - CapturingTessellator.Flags flagsA = positionOnly(); - CapturingTessellator.Flags flagsB = positionTexture(); - - List draws = new ArrayList<>(); - draws.add(createDrawWithFlags(flagsA, 0)); // A - draws.add(createDrawWithFlags(flagsA, 0)); // A - draws.add(createDrawWithFlags(flagsB, 0)); // B - draws.add(createDrawWithFlags(flagsA, 0)); // A - draws.add(createDrawWithFlags(flagsA, 0)); // A - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); + CompiledDisplayList compiled = createDisplayList(() -> { + createSimpleDraw(); // A + createSimpleDraw(); // A + createTextureDraw(); // B + createSimpleDraw(); // A + createSimpleDraw(); // A + }); + Int2IntMap counts = compiled.getCommandCounts(); + int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0); + int drawRestoreCount = counts.getOrDefault(GLCommand.DRAW_RANGE_RESTORE, 0); // Verify: 2 VBOs (one for format A, one for format B) - assertEquals(2, result.ownedVbos().length, "A A B A A pattern should produce 2 VBOs (one per format)"); + assertEquals(2, getVBOCount(compiled), "A A B A A pattern should produce 2 VBOs (one per format)"); // Verify: 2 DrawRangeCmds (all A's merged into 1, B is 1) // With format-based batching, all A draws go into the same FormatBuffer // and get merged (same transform). Order within same command index doesn't matter. - long drawCount = countDrawRangeCmds(optimized); assertEquals(2, drawCount, "A A B A A pattern with same transform should produce 2 DrawRangeCmds (A's merged, B separate)"); + assertEquals(1, drawRestoreCount, "A A B A A pattern with same transform should produce 2 DrawRangeCmds (A's merged, B separate)"); } } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java deleted file mode 100644 index be4c7e333..000000000 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java +++ /dev/null @@ -1,535 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; -import com.gtnewhorizons.angelica.AngelicaExtension; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; -import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; -import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; -import com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd; -import org.joml.Matrix4f; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static com.gtnewhorizons.angelica.glsm.DisplayListTestHelper.*; -import static org.junit.jupiter.api.Assertions.*; - -/** - * Tests for display list primitive (lines, triangles) handling. - * - *

    Tests cover: - *

      - *
    • AccumulatedPrimitiveDraw deep copying behavior
    • - *
    • TessellatorPrimitiveBuffer accumulation and range merging
    • - *
    • Integration with buildOptimizedDisplayList for primitive VBOs
    • - *
    • Mixed quad + primitive display lists
    • - *
    - */ -@ExtendWith(AngelicaExtension.class) -class GLSM_DisplayList_Primitive_Test { - - // ==================== Helper Methods ==================== - - private long countDrawRangeCmds(DisplayListCommand[] commands) { - long count = 0; - for (DisplayListCommand cmd : commands) { - if (cmd instanceof DrawRangeCmd) count++; - } - return count; - } - - private Set getUniqueVBOs(DisplayListCommand[] commands) { - Set vbos = new HashSet<>(); - for (DisplayListCommand cmd : commands) { - if (cmd instanceof DrawRangeCmd rangeCmd) { - vbos.add(rangeCmd.sharedVbo()); - } - } - return vbos; - } - - // ==================== AccumulatedPrimitiveDraw Tests ==================== - - @Test - void testAccumulatedPrimitiveDrawDeepCopiesLines() { - // Setup: Create a line and capture its original values - ModelLine originalLine = createSimpleLine(); - float originalX0 = originalLine.getX(0); - float originalY0 = originalLine.getY(0); - - List primitives = new ArrayList<>(); - primitives.add(originalLine); - - // Execute: Create AccumulatedPrimitiveDraw (should deep copy) - AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0, 0); - - // Modify original - originalLine.setX(0, 999.0f); - originalLine.setY(0, 888.0f); - - // Verify: Copied primitive should be unchanged - ModelPrimitiveView copied = draw.primitives.get(0); - assertTrue(copied instanceof ModelLine, "Copied primitive should be a ModelLine"); - ModelLine copiedLine = (ModelLine) copied; - assertEquals(originalX0, copiedLine.getX(0), 0.001f, "Deep copy should preserve original X value"); - assertEquals(originalY0, copiedLine.getY(0), 0.001f, "Deep copy should preserve original Y value"); - } - - @Test - void testAccumulatedPrimitiveDrawDeepCopiesTriangles() { - // Setup: Create a triangle and capture its original values - ModelTriangle originalTri = createSimpleTriangle(); - float originalX0 = originalTri.getX(0); - float originalX1 = originalTri.getX(1); - float originalX2 = originalTri.getX(2); - - List primitives = new ArrayList<>(); - primitives.add(originalTri); - - // Execute: Create AccumulatedPrimitiveDraw (should deep copy) - AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0, 0); - - // Modify original - originalTri.setX(0, 999.0f); - originalTri.setX(1, 888.0f); - originalTri.setX(2, 777.0f); - - // Verify: Copied primitive should be unchanged - ModelPrimitiveView copied = draw.primitives.get(0); - assertTrue(copied instanceof ModelTriangle, "Copied primitive should be a ModelTriangle"); - ModelTriangle copiedTri = (ModelTriangle) copied; - assertEquals(originalX0, copiedTri.getX(0), 0.001f, "Deep copy should preserve original X0 value"); - assertEquals(originalX1, copiedTri.getX(1), 0.001f, "Deep copy should preserve original X1 value"); - assertEquals(originalX2, copiedTri.getX(2), 0.001f, "Deep copy should preserve original X2 value"); - } - - @Test - void testAccumulatedPrimitiveDrawDeepCopiesMixedPrimitives() { - // Setup: Create mixed primitives - List primitives = createMixedPrimitives(2, 2); - - // Execute - AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0, 0); - - // Verify: All primitives copied correctly - assertEquals(4, draw.primitives.size(), "Should have 4 primitives (2 lines + 2 triangles)"); - - int lineCount = 0; - int triCount = 0; - for (ModelPrimitiveView prim : draw.primitives) { - if (prim instanceof ModelLine) lineCount++; - else if (prim instanceof ModelTriangle) triCount++; - } - assertEquals(2, lineCount, "Should have 2 lines"); - assertEquals(2, triCount, "Should have 2 triangles"); - } - - @Test - void testAccumulatedPrimitiveDrawDeepCopiesTransform() { - // Setup - Matrix4f originalTransform = translate(1.0f, 2.0f, 3.0f); - List primitives = new ArrayList<>(); - primitives.add(createSimpleLine()); - - // Execute - AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, originalTransform, positionOnly(), 0, 0); - - // Modify original transform - originalTransform.identity(); - - // Verify: Stored transform should be unchanged (not identity) - assertFalse(draw.transform.equals(new Matrix4f()), "Transform should be deep copied, not identity"); - assertEquals(1.0f, draw.transform.m30(), 0.001f, "Transform X translation should be preserved"); - assertEquals(2.0f, draw.transform.m31(), 0.001f, "Transform Y translation should be preserved"); - assertEquals(3.0f, draw.transform.m32(), 0.001f, "Transform Z translation should be preserved"); - } - - // ==================== TessellatorPrimitiveBuffer Tests ==================== - - @Test - void testPrimitiveBufferSeparatesLinesByTransform() { - // Setup: Create primitive buffer and add draws with different transforms - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - - AccumulatedPrimitiveDraw draw1 = createLinesDraw(2, 0); // 2 lines at identity - AccumulatedPrimitiveDraw draw2 = createPrimitiveDrawWithTransform( - createMixedPrimitives(2, 0), translate(1, 0, 0), 1); // 2 lines translated - - buffer.addDraw(draw1); - buffer.addDraw(draw2); - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify: Has lines, no triangles - assertNotNull(compiled, "Should compile non-empty buffer"); - assertTrue(compiled.hasLines(), "Should have lines"); - assertFalse(compiled.hasTriangles(), "Should not have triangles"); - - // 2 merged ranges (different transforms) - assertEquals(2, compiled.lineMergedRanges().length, - "Different transforms should produce separate merged ranges"); - } - - @Test - void testPrimitiveBufferMergesSameTransformLines() { - // Setup: Multiple draws with same transform - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - - buffer.addDraw(createLinesDraw(2, 0)); // 2 lines - buffer.addDraw(createLinesDraw(3, 0)); // 3 more lines, same transform - buffer.addDraw(createLinesDraw(1, 0)); // 1 more line, same transform - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify: 1 merged range (all same transform) - assertNotNull(compiled); - assertEquals(1, compiled.lineMergedRanges().length, - "Same transform draws should merge into 1 range"); - - // Total vertices: (2+3+1) lines * 2 vertices = 12 - assertEquals(12, compiled.lineMergedRanges()[0].vertexCount(), - "Merged range should contain all line vertices"); - } - - @Test - void testPrimitiveBufferSeparatesTrianglesByTransform() { - // Setup - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - - buffer.addDraw(createTrianglesDraw(2, 0)); // 2 triangles at identity - buffer.addDraw(createPrimitiveDrawWithTransform( - createMixedPrimitives(0, 2), translate(1, 0, 0), 1)); // 2 triangles translated - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify - assertNotNull(compiled); - assertFalse(compiled.hasLines(), "Should not have lines"); - assertTrue(compiled.hasTriangles(), "Should have triangles"); - - assertEquals(2, compiled.triangleMergedRanges().length, - "Different transforms should produce separate merged ranges"); - } - - @Test - void testPrimitiveBufferMergesSameTransformTriangles() { - // Setup - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - - buffer.addDraw(createTrianglesDraw(2, 0)); // 2 triangles - buffer.addDraw(createTrianglesDraw(3, 0)); // 3 more, same transform - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify: 1 merged range - assertNotNull(compiled); - assertEquals(1, compiled.triangleMergedRanges().length, - "Same transform draws should merge into 1 range"); - - // Total vertices: (2+3) triangles * 3 vertices = 15 - assertEquals(15, compiled.triangleMergedRanges()[0].vertexCount(), - "Merged range should contain all triangle vertices"); - } - - @Test - void testPrimitiveBufferHandlesMixedLinesAndTriangles() { - // Setup: Draw with mixed primitives - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - buffer.addDraw(createMixedPrimitiveDraw(3, 2, 0)); // 3 lines + 2 triangles - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify: Both types present - assertNotNull(compiled); - assertTrue(compiled.hasLines(), "Should have lines"); - assertTrue(compiled.hasTriangles(), "Should have triangles"); - - // Verify counts - assertEquals(6, compiled.lineMergedRanges()[0].vertexCount(), - "Should have 6 line vertices (3 lines * 2)"); - assertEquals(6, compiled.triangleMergedRanges()[0].vertexCount(), - "Should have 6 triangle vertices (2 triangles * 3)"); - } - - @Test - void testPrimitiveBufferEmptyReturnsNull() { - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - CompiledPrimitiveBuffers compiled = buffer.finish(); - assertNull(compiled, "Empty buffer should return null"); - } - - @Test - void testPrimitiveBufferPerDrawRangesTrackEachDraw() { - // Setup: Multiple draws - TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); - - buffer.addDraw(createLinesDraw(2, 0)); // 4 vertices - buffer.addDraw(createLinesDraw(3, 1)); // 6 vertices (same transform, different cmd index) - buffer.addDraw(createLinesDraw(1, 2)); // 2 vertices - - // Execute - CompiledPrimitiveBuffers compiled = buffer.finish(); - - // Verify: Per-draw ranges track each individual draw - assertNotNull(compiled); - assertEquals(3, compiled.linePerDrawRanges().length, - "Should have 3 per-draw ranges"); - - // Verify individual range sizes - assertEquals(4, compiled.linePerDrawRanges()[0].vertexCount()); - assertEquals(6, compiled.linePerDrawRanges()[1].vertexCount()); - assertEquals(2, compiled.linePerDrawRanges()[2].vertexCount()); - } - - @Test - void testDifferentFlagsProduceDifferentFormats() { - // Test that format-aware compilation uses optimal vertex sizes - // positionOnly = 12 bytes, positionColor = 16 bytes, fullFormat = 32 bytes - - // Position only (12 bytes per vertex) - TessellatorPrimitiveBuffer posOnlyBuffer = new TessellatorPrimitiveBuffer(positionOnly()); - posOnlyBuffer.addDraw(createLinesDraw(1, 0)); - CompiledPrimitiveBuffers posOnlyCompiled = posOnlyBuffer.finish(); - assertNotNull(posOnlyCompiled); - assertEquals(positionOnly(), posOnlyCompiled.flags(), "Should preserve positionOnly flags"); - - // Position + Color (16 bytes per vertex) - TessellatorPrimitiveBuffer posColorBuffer = new TessellatorPrimitiveBuffer(positionColor()); - posColorBuffer.addDraw(createPrimitiveDraw(createMixedPrimitives(1, 0), identity(), positionColor(), 0)); - CompiledPrimitiveBuffers posColorCompiled = posColorBuffer.finish(); - assertNotNull(posColorCompiled); - assertEquals(positionColor(), posColorCompiled.flags(), "Should preserve positionColor flags"); - - // Full format (32 bytes per vertex) - TessellatorPrimitiveBuffer fullBuffer = new TessellatorPrimitiveBuffer(fullFormat()); - fullBuffer.addDraw(createPrimitiveDraw(createMixedPrimitives(1, 0), identity(), fullFormat(), 0)); - CompiledPrimitiveBuffers fullCompiled = fullBuffer.finish(); - assertNotNull(fullCompiled); - assertEquals(fullFormat(), fullCompiled.flags(), "Should preserve fullFormat flags"); - - // Verify the flags differ (ensuring format selection works) - assertNotEquals(posOnlyCompiled.flags(), posColorCompiled.flags()); - assertNotEquals(posColorCompiled.flags(), fullCompiled.flags()); - } - - // ==================== Integration Tests ==================== - - @Test - void testBuildOptimizedDisplayListWithLinesOnly() { - // Setup: Only primitive draws - List quadDraws = new ArrayList<>(); - List primitiveDraws = new ArrayList<>(); - primitiveDraws.add(createLinesDraw(5, 0)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 1 VBO for lines - assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for lines"); - - // Verify: 1 DrawRangeCmd - assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); - } - - @Test - void testBuildOptimizedDisplayListWithTrianglesOnly() { - // Setup - List quadDraws = new ArrayList<>(); - List primitiveDraws = new ArrayList<>(); - primitiveDraws.add(createTrianglesDraw(3, 0)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 1 VBO for triangles - assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for triangles"); - assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); - } - - @Test - void testBuildOptimizedDisplayListWithMixedPrimitives() { - // Setup: Lines and triangles - List quadDraws = new ArrayList<>(); - List primitiveDraws = new ArrayList<>(); - primitiveDraws.add(createLinesDraw(3, 0)); - primitiveDraws.add(createTrianglesDraw(2, 1)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 2 VBOs (one for lines, one for triangles) - assertEquals(2, result.ownedVbos().length, - "Should have 2 VBOs (lines + triangles)"); - assertEquals(2, countDrawRangeCmds(optimized), - "Should have 2 DrawRangeCmds"); - } - - @Test - void testBuildOptimizedDisplayListWithQuadsAndPrimitives() { - // Setup: Mixed quads and primitives - List quadDraws = new ArrayList<>(); - quadDraws.add(createSimpleDraw(0)); // 1 quad - - List primitiveDraws = new ArrayList<>(); - primitiveDraws.add(createLinesDraw(2, 1)); // 2 lines - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 2 VBOs (quads + lines) - assertEquals(2, result.ownedVbos().length, - "Should have 2 VBOs (quads + lines)"); - assertEquals(2, countDrawRangeCmds(optimized), - "Should have 2 DrawRangeCmds"); - - // Verify unique VBOs in commands - Set uniqueVBOs = getUniqueVBOs(optimized); - assertEquals(2, uniqueVBOs.size(), "Commands should reference 2 unique VBOs"); - } - - @Test - void testBuildOptimizedDisplayListWithQuadsLinesAndTriangles() { - // Setup: All three types - List quadDraws = new ArrayList<>(); - quadDraws.add(createSimpleDraw(0)); - - List primitiveDraws = new ArrayList<>(); - primitiveDraws.add(createLinesDraw(2, 1)); - primitiveDraws.add(createTrianglesDraw(2, 2)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 3 VBOs (quads + lines + triangles) - assertEquals(3, result.ownedVbos().length, - "Should have 3 VBOs (quads + lines + triangles)"); - assertEquals(3, countDrawRangeCmds(optimized), - "Should have 3 DrawRangeCmds"); - } - - @Test - void testBuildOptimizedDisplayListPrimitiveTransformMerging() { - // Setup: Multiple draws with same transform should merge - List quadDraws = new ArrayList<>(); - List primitiveDraws = new ArrayList<>(); - - // Add 3 line draws at same transform - primitiveDraws.add(createLinesDraw(2, 0)); - primitiveDraws.add(createLinesDraw(3, 0)); - primitiveDraws.add(createLinesDraw(1, 0)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 1 VBO, 1 merged DrawRangeCmd - assertEquals(1, result.ownedVbos().length, "Should have 1 VBO"); - assertEquals(1, countDrawRangeCmds(optimized), - "Same-transform draws should merge into 1 DrawRangeCmd"); - } - - @Test - void testBuildOptimizedDisplayListPrimitiveDifferentTransforms() { - // Setup: Draws with different transforms - List quadDraws = new ArrayList<>(); - List primitiveDraws = new ArrayList<>(); - - List lines1 = new ArrayList<>(); - lines1.add(createSimpleLine()); - primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0, 0)); - - List lines2 = new ArrayList<>(); - lines2.add(createSimpleLine()); - primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1, 1)); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: 1 VBO (same format), 2 DrawRangeCmds (different transforms) - assertEquals(1, result.ownedVbos().length, - "Same-type primitives should share VBO"); - assertEquals(2, countDrawRangeCmds(optimized), - "Different transforms should produce separate DrawRangeCmds"); - } - - @Test - void testBuildOptimizedDisplayListNullPrimitiveDraws() { - // Setup: null primitiveDraws list (backwards compatibility) - List quadDraws = new ArrayList<>(); - quadDraws.add(createSimpleDraw(0)); - - List commands = new ArrayList<>(); - - // Execute: Pass null for primitiveDraws - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, null, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: Works normally with just quads - assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for quads"); - assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); - } - - @Test - void testBuildOptimizedDisplayListEmptyPrimitiveDraws() { - // Setup: Empty primitiveDraws list - List quadDraws = new ArrayList<>(); - quadDraws.add(createSimpleDraw(0)); - - List primitiveDraws = new ArrayList<>(); - - List commands = new ArrayList<>(); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, quadDraws, primitiveDraws, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: Works normally with just quads - assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for quads"); - assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); - } -} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLMS_MatrixStack_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java similarity index 97% rename from src/test/java/com/gtnewhorizons/angelica/glsm/GLMS_MatrixStack_UnitTest.java rename to src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java index f4f5f715d..b5aa60488 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLMS_MatrixStack_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java @@ -3,7 +3,6 @@ package com.gtnewhorizons.angelica.glsm; import com.gtnewhorizons.angelica.AngelicaExtension; import org.joml.Matrix4f; import org.joml.Matrix4fStack; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -16,7 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(AngelicaExtension.class) -public class GLMS_MatrixStack_UnitTest { +public class GLSM_MatrixStack_UnitTest { final static FloatBuffer buffer = BufferUtils.createFloatBuffer(16); Matrix4f getMatrix(int matrix, boolean cached) { diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java index 3f8158123..20f18af24 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java @@ -42,7 +42,7 @@ public class GLSM_VAO_UnitTest { // Set the vertex attrib to a defined state int vbo = GL15.glGenBuffers(); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL11.glVertexPointer(defaultVertexSize, defaultVertexType, defaultVertexStride, 0); @@ -53,16 +53,16 @@ public class GLSM_VAO_UnitTest { verifyState(GL11.GL_VERTEX_ARRAY_TYPE, defaultVertexType, "GL_VERTEX_ARRAY_TYPE - Setup"); verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, defaultVertexStride, "GL_VERTEX_ARRAY_STRIDE - Setup"); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); // Verify VAO & VBO creation int vao = UniversalVAO.genVertexArrays(); Assertions.assertTrue(vao > 0, "GL_VERTEX_ARRAY_BINDING - VAO Created"); - UniversalVAO.bindVertexArray(vao); + glBindVertexArray(vao); verifyState(GL30.GL_VERTEX_ARRAY_BINDING, vao, "GL_VERTEX_ARRAY_BINDING - Bound"); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); verifyState(GL15.GL_ARRAY_BUFFER_BINDING, vbo, "GL_ARRAY_BUFFER_BINDING - Bound"); verifyState(GL13.GL_CLIENT_ACTIVE_TEXTURE, GL13.GL_TEXTURE1, "GL_CLIENT_ACTIVE_TEXTURE - Preserved"); @@ -81,10 +81,10 @@ public class GLSM_VAO_UnitTest { verifyState(GL11.GL_VERTEX_ARRAY_TYPE, vaoVertexType, "GL_VERTEX_ARRAY_TYPE - Set"); verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, vaoVertexStride, "GL_VERTEX_ARRAY_STRIDE - Set"); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); // Check if everything got reset to default - UniversalVAO.bindVertexArray(0); + glBindVertexArray(0); verifyState(GL30.GL_VERTEX_ARRAY_BINDING, 0, "GL_VERTEX_ARRAY_BINDING - Unbound"); verifyState(GL15.GL_ARRAY_BUFFER_BINDING, 0, "GL_ARRAY_BUFFER_BINDING - Unbound"); @@ -96,15 +96,27 @@ public class GLSM_VAO_UnitTest { verifyState(GL11.GL_NORMAL_ARRAY, true, "GL_NORMAL_ARRAY - Reset"); // Check if the VAO states are still valid after re-binding it - UniversalVAO.bindVertexArray(vao); + glBindVertexArray(vao); verifyState(GL11.GL_VERTEX_ARRAY, vaoVertexEnabled, "GL_VERTEX_ARRAY - Preserved"); verifyState(GL11.GL_VERTEX_ARRAY_SIZE, vaoVertexSize, "GL_VERTEX_ARRAY_SIZE - Preserved"); verifyState(GL11.GL_VERTEX_ARRAY_TYPE, vaoVertexType, "GL_VERTEX_ARRAY_TYPE - Preserved"); verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, vaoVertexStride, "GL_VERTEX_ARRAY_STRIDE - Preserved"); - UniversalVAO.bindVertexArray(0); + glBindVertexArray(0); + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + + glBindVertexArray(vao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + + GLStateManager.glPopAttrib(); + + verifyState(GL30.GL_VERTEX_ARRAY_BINDING, vao, "GL_VERTEX_ARRAY_BINDING - Not affected by glPushAttrib"); + verifyState(GL15.GL_ARRAY_BUFFER_BINDING, vbo, "GL_ARRAY_BUFFER_BINDING - Not affected by glPushAttrib"); + + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); GL15.glDeleteBuffers(vbo); UniversalVAO.deleteVertexArrays(vao); @@ -117,4 +129,9 @@ public class GLSM_VAO_UnitTest { verifyState(GL11.GL_COLOR_ARRAY, false, "GL_COLOR_ARRAY Default State"); verifyState(GL11.GL_INDEX_ARRAY, false, "GL_INDEX_ARRAY Default State"); } + + private static void glBindVertexArray(int array) { + GLStateManager.boundVAO = array; + UniversalVAO.bindVertexArray(array); + } } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java index 2447604dd..ba246904a 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java @@ -1,9 +1,10 @@ package com.gtnewhorizons.angelica.glsm.recording; +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.AngelicaExtension; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.recording.commands.DrawCommand; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -33,14 +34,6 @@ class RecordingDataStructuresTest { } } - @Test - void testDrawCommandCreation() { - DrawCommand cmd = new DrawCommand(0, 4, GL11.GL_QUADS); - assertEquals(0, cmd.firstVertex()); - assertEquals(4, cmd.vertexCount()); - assertEquals(GL11.GL_QUADS, cmd.primitiveType()); - } - @Test void testCompiledDisplayListCreation() { // Create a display list with PushMatrix, Scale, PopMatrix @@ -73,182 +66,40 @@ class RecordingDataStructuresTest { } @Test - void testImmediateModeRecorderCapturesQuads() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); + void testImmediateModeRecorder() { + DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator(); // Record a single quad using immediate mode - recorder.begin(GL11.GL_QUADS); - recorder.setTexCoord(0, 0); - recorder.vertex(0, 0, 0); - recorder.setTexCoord(1, 0); - recorder.vertex(1, 0, 0); - recorder.setTexCoord(1, 1); - recorder.vertex(1, 1, 0); - recorder.setTexCoord(0, 1); - recorder.vertex(0, 1, 0); + recorder.startDrawing(GL11.GL_QUADS); + recorder.setTextureUV(0, 0); + recorder.addVertex(0, 0, 0); + recorder.setTextureUV(1, 0); + recorder.addVertex(1, 0, 0); + recorder.setTextureUV(1, 1); + recorder.addVertex(1, 1, 0); + recorder.setTextureUV(0, 1); + recorder.addVertex(0, 1, 0); // end() now returns quads immediately (for correct command interleaving) - ImmediateModeRecorder.Result result = recorder.end(); + DirectTessellator result = ImmediateModeRecorder.end(); assertNotNull(result); - assertEquals(1, result.quads().size()); - assertTrue(result.flags().hasTexture); // We called setTexCoord + assertTrue(ImmediateModeRecorder.hasGeometry()); + assertEquals(4, result.getVertexCount()); + assertEquals(GL11.GL_QUADS, result.getDrawMode()); + assertTrue(result.hasTexture); // We called setTexCoord + assertFalse(result.hasNormals); + assertFalse(result.hasColor); + assertFalse(result.hasBrightness); + assertEquals(DefaultVertexFormat.POSITION_TEXTURE, result.getVertexFormat()); - // After end(), recorder should be empty (quads were returned immediately) - assertFalse(recorder.hasGeometry()); - assertNull(recorder.getQuadsAndClear()); - } + result.reset(); - @Test - void testImmediateModeRecorderCapturesTriangles() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // Record 2 triangles (6 vertices, should become 2 degenerate quads) - recorder.begin(GL11.GL_TRIANGLES); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(0.5f, 1, 0); - recorder.vertex(2, 0, 0); - recorder.vertex(3, 0, 0); - recorder.vertex(2.5f, 1, 0); - - // end() now returns quads immediately - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertEquals(2, result.quads().size()); // 2 triangles = 2 degenerate quads - - // Recorder should be empty after end() - assertFalse(recorder.hasGeometry()); - } - - @Test - void testImmediateModeRecorderCapturesTriangleFan() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // Record a triangle fan (center + 3 outer vertices = 2 triangles = 2 quads) - recorder.begin(GL11.GL_TRIANGLE_FAN); - recorder.vertex(0, 0, 0); // Center - recorder.vertex(1, 0, 0); - recorder.vertex(1, 1, 0); - recorder.vertex(0, 1, 0); - - // end() now returns quads immediately - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertEquals(2, result.quads().size()); // 2 triangles from fan - - // Recorder should be empty after end() - assertFalse(recorder.hasGeometry()); - } - - @Test - void testImmediateModeRecorderEmptyAfterReset() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - recorder.begin(GL11.GL_QUADS); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(1, 1, 0); - recorder.vertex(0, 1, 0); - - // end() returns quads immediately, so recorder is empty after - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertEquals(1, result.quads().size()); - - // Already empty after end(), but reset() should still work - assertFalse(recorder.hasGeometry()); - - recorder.reset(); - - assertFalse(recorder.hasGeometry()); - assertNull(recorder.getQuadsAndClear()); - } - - @Test - void testImmediateModeRecorderNormalAndColor() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - recorder.setNormal(0, 0, 1); // Normal pointing +Z - recorder.begin(GL11.GL_QUADS); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(1, 1, 0); - recorder.vertex(0, 1, 0); - - // end() now returns quads immediately - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertTrue(result.flags().hasNormals); - } - - @Test - void testImmediateModeRecorderThrowsOnInvalidState() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // glEnd without glBegin - assertThrows(IllegalStateException.class, () -> recorder.end()); - - // glVertex without glBegin - assertThrows(IllegalStateException.class, () -> recorder.vertex(0, 0, 0)); - - // Nested glBegin - recorder.begin(GL11.GL_QUADS); - assertThrows(IllegalStateException.class, () -> recorder.begin(GL11.GL_QUADS)); - recorder.end(); - - // getQuadsAndClear while in primitive - recorder.begin(GL11.GL_QUADS); - assertThrows(IllegalStateException.class, () -> recorder.getQuadsAndClear()); - } - - @Test - void testImmediateModeRecorderCapturesLines() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // Record 2 lines (4 vertices) - recorder.begin(GL11.GL_LINES); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(0, 1, 0); - recorder.vertex(1, 1, 0); - - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertTrue(result.quads().isEmpty(), "Lines should not produce quads"); - assertEquals(4, result.lines().size(), "4 vertices for 2 lines"); - } - - @Test - void testImmediateModeRecorderCapturesLineStrip() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // Record a line strip: 4 vertices = 3 line segments = 6 line vertices - recorder.begin(GL11.GL_LINE_STRIP); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(1, 1, 0); - recorder.vertex(0, 1, 0); - - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertTrue(result.quads().isEmpty(), "Line strips should not produce quads"); - assertEquals(6, result.lines().size(), "4 vertices in strip = 3 segments = 6 line vertices"); - } - - @Test - void testImmediateModeRecorderCapturesLineLoop() { - ImmediateModeRecorder recorder = new ImmediateModeRecorder(); - - // Record a line loop: 4 vertices = 4 line segments (closes back to start) = 8 line vertices - recorder.begin(GL11.GL_LINE_LOOP); - recorder.vertex(0, 0, 0); - recorder.vertex(1, 0, 0); - recorder.vertex(1, 1, 0); - recorder.vertex(0, 1, 0); - - ImmediateModeRecorder.Result result = recorder.end(); - assertNotNull(result); - assertTrue(result.quads().isEmpty(), "Line loops should not produce quads"); - assertEquals(8, result.lines().size(), "4 vertices in loop = 4 segments (including closing) = 8 line vertices"); + assertFalse(ImmediateModeRecorder.hasGeometry()); + assertEquals(0, result.getVertexCount()); + assertFalse(result.hasTexture); + assertFalse(result.hasNormals); + assertFalse(result.hasColor); + assertFalse(result.hasBrightness); + assertNull(result.getVertexFormat()); } }