diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java index 20f63a1a3..eed048ded 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java @@ -2,12 +2,13 @@ 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; @@ -16,17 +17,16 @@ import java.util.Map; /** * Builds final command buffers from raw command buffers and compiled VBO data. - * Bridges the gap between VBO compilation (glsm types) and buffer processing (recording types). + * Transforms are already collapsed to MultMatrix during recording; the optimizer + * tracks transform state to emit deltas when draws need a different transform. */ public final class CommandBufferBuilder { + private static final Logger LOGGER = LogManager.getLogger("CommandBufferBuilder"); + private CommandBufferBuilder() {} - /** - * 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. - */ + /** Build with transform delta optimization and merged draw ranges. */ public static void buildOptimizedFromRawBuffer( CommandBuffer rawBuffer, Map compiledQuadBuffers, @@ -76,11 +76,7 @@ public final class CommandBufferBuilder { } } - /** - * Build commands without transform collapsing. - * Copies state commands directly (no transform optimization), but still uses - * merged draw ranges (draws already collapsed by format + transform in VBO compilation). - */ + /** Debug build: no optimizations, 1:1 draw commands. */ public static void buildUnoptimizedFromRawBuffer( CommandBuffer rawBuffer, Map compiledQuadBuffers, @@ -96,8 +92,8 @@ public final class CommandBufferBuilder { vboIndexMap.put(ownedVbos[i], i); } - // Collect all merged draw ranges sorted by command index - final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); + // Collect per-draw ranges (no merging) sorted by command index + final List allRanges = collectDrawRangesUnoptimized(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); rawBuffer.resetRead(); int cmdIndex = 0; @@ -110,6 +106,7 @@ public final class CommandBufferBuilder { 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()); } } @@ -124,17 +121,32 @@ public final class CommandBufferBuilder { 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()); } } } - /** - * Collect all draw ranges from compiled buffers, sorted by command index. - */ + /** 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<>(); @@ -142,17 +154,21 @@ public final class CommandBufferBuilder { 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 = compiledBuffer.mergedRanges(); + 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().hasBrightness)); + 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 DrawRange[] ranges = compiledLineBuffer.mergedRanges(); + 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(), false)); + allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), lineFlags, + DrawRangeWithBuffer.DrawSource.IMMEDIATE_MODE_LINES)); } } @@ -161,21 +177,23 @@ public final class CommandBufferBuilder { final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]); for (int p = 0; p < primBufferArray.length; p++) { final CompiledPrimitiveBuffers primBuffers = primBufferArray[p]; - final boolean hasBrightness = primBuffers.flags().hasBrightness; + final CapturingTessellator.Flags primFlags = primBuffers.flags(); // Tessellator lines if (primBuffers.hasLines()) { - final DrawRange[] ranges = primBuffers.lineMergedRanges(); + 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, hasBrightness)); + allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags, + DrawRangeWithBuffer.DrawSource.TESSELLATOR_LINES)); } } // Tessellator triangles if (primBuffers.hasTriangles()) { - final DrawRange[] ranges = primBuffers.triangleMergedRanges(); + 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, hasBrightness)); + allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags, + DrawRangeWithBuffer.DrawSource.TESSELLATOR_TRIANGLES)); } } } @@ -185,21 +203,36 @@ public final class CommandBufferBuilder { return allRanges; } - /** - * Emit a draw range to the output buffer, with transform if needed. - */ + /** Emit draw range with delta transform. Uses writeDrawRangeRestore for immediate mode. */ private static void emitDrawRangeToBuffer( DrawRangeWithBuffer drb, BufferTransformOptimizer opt, CommandBuffer out, Object2IntMap vboIndexMap) { + // Emit transform to reach the draw's expected transform opt.emitTransformTo(out, drb.range().transform()); // Write the draw range command final int vboIdx = vboIndexMap.getInt(drb.vbo()); if (vboIdx >= 0) { - out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness()); + 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()); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java index 029fb8cc9..d5244a17c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledLineBuffer.java @@ -14,7 +14,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; * */ @Desugar -record CompiledLineBuffer( +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 index 523299994..596cac9ee 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java @@ -12,7 +12,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; * Similar to CompiledFormatBuffer but handles primitives instead of quads. */ @Desugar -record CompiledPrimitiveBuffers( +public record CompiledPrimitiveBuffers( CapturingTessellator.Flags flags, VertexBuffer lineVbo, DrawRange[] lineMergedRanges, diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java index 492512ca8..20ba6d3cf 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java @@ -16,9 +16,11 @@ 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.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; @@ -31,6 +33,7 @@ import org.joml.Vector3f; import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; +import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; @@ -40,75 +43,52 @@ import java.util.List; import java.util.Map; /** - * Manages display list compilation, caching, and playback. - * Handles VBO-based display list emulation with command recording and batching. + * VBO-based display list emulation with command recording, transform collapsing, and format-based batching. * - *

This class is responsible for: - *

    - *
  • Display list lifecycle (glNewList, glEndList, glCallList, glDeleteLists)
  • - *
  • Command recording and accumulation during compilation
  • - *
  • Building optimized (batched) and unoptimized (nested-safe) command lists
  • - *
  • Transform tracking and collapsing for optimal GL call counts
  • - *
  • Cache management for compiled display lists
  • - *
+ *

Transform Collapsing: Consecutive transforms collapse into single MultMatrix commands, + * emitted at barriers (draws, CallList, exit). Vertices stay canonical in VBOs. Handles nested + * display lists correctly and maintains Push/Pop semantics. * - *

Architecture: Transform Collapsing

- *

The optimization strategy collapses consecutive MODELVIEW transforms into single MultMatrix - * commands, emitting them at "barriers" (draws, CallList, exit). This approach:

- *
    - *
  • Keeps vertices canonical (untransformed) in VBOs
  • - *
  • Properly handles nested display lists (CallList) - GL state is correct before sub-list
  • - *
  • Reduces GL calls (multiple transforms → one MultMatrix)
  • - *
  • Maintains proper Push/Pop stack semantics
  • - *
- * - *

Transform Tracking State

- *
    - *
  • accumulated: Total relative transform (what GL matrix should be)
  • - *
  • lastEmitted: What we've emitted (what GL matrix is)
  • - *
  • stack: Saved accumulated values at Push points
  • - *
- * - *

Batching Strategy

- *

Format-based batching: All draws with the same vertex format share a single VBO via - * {@link FormatBuffer}. Each draw's position within the VBO is tracked as a {@link DrawRange}. - * Consecutive draws with the same transform are merged into single ranges. Transforms are - * handled via delta-based emission using {@link TransformOptimizer}.

- * - * @see com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList - * @see com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw - * @see com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd + *

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. + * Delta transforms handled via {@link TransformOptimizer}. */ @UtilityClass public class DisplayListManager { private static final Logger LOGGER = LogManager.getLogger("DisplayListManager"); - /** - * Debug flag to enable building unoptimized display list commands. - * When false (default), unoptimized commands are not built - * When true, unoptimized commands are built for debugging GL behavior. - * Set via: -Dangelica.debugDisplayLists=true - */ + // -Dangelica.debugDisplayLists: disable transform collapsing and draw merging private static final boolean DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debugDisplayLists"); + // -Dangelica.logDisplayListCompilation: log compiled display list commands + private static final boolean LOG_DISPLAY_LIST_COMPILATION; + + static { + LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.logDisplayListCompilation"); + if (LOG_DISPLAY_LIST_COMPILATION) { + LogManager.getLogger("DisplayListManager").warn("Display list compilation logging ENABLED (-Dangelica.logDisplayListCompilation=true)"); + } + } + // Track which display list is currently being rendered @Getter private static int currentRenderingList = -1; - /** - * Check if we're currently rendering a display list. - * Used by format overrides to avoid interfering with display list VBOs. - */ - public static boolean isRenderingDisplayList() { - return currentRenderingList != -1; - } + private static final Matrix4f IDENTITY = new Matrix4f(); public static boolean isIdentity(Matrix4f m) { - return (m.properties() & Matrix4f.PROPERTY_IDENTITY) != 0; + return (m.properties() & Matrix4f.PROPERTY_IDENTITY) != 0 || m.equals(IDENTITY, 1e-6f); } /** Transform operation types for relative transform tracking. */ public enum TransformOp { TRANSLATE, SCALE, ROTATE } + /** Recording mode for display list compilation. */ + public enum RecordMode { + NONE, // Not recording + COMPILE, // GL_COMPILE: record only, don't execute + COMPILE_AND_EXECUTE // GL_COMPILE_AND_EXECUTE: record and execute + } + // Display list compilation state (current/active context) private static int glListMode = 0; private static int glListId = -1; @@ -118,8 +98,31 @@ public class DisplayListManager { 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 relative transforms during compilation (with push/pop support) + 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 + /** + * -- 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 + private static List pendingTransformOps = null; // Ops accumulated since last flush + private static List> multMatrixSources = null; // Source ops for each MULT_MATRIX in raw buffer + private static List drawRangeSources = null; // Source type for each DRAW_RANGE in final buffer + + // For flushMatrix() - reusable buffer for executing collapsed transforms + private static final FloatBuffer flushMatrixBuffer = org.lwjgl.BufferUtils.createFloatBuffer(16); // Nested compilation support - stack of parent contexts private static final Deque compilationStack = new ArrayDeque<>(); @@ -141,110 +144,454 @@ public class DisplayListManager { List primitiveDraws, Matrix4fStack transform, boolean wasTessellatorCompiling, - ImmediateModeRecorder immediateRecorder + ImmediateModeRecorder immediateRecorder, + StackTraceElement[] stackTrace, + + // Debug logging fields (only used when LOG_DISPLAY_LIST_COMPILATION) + List pendingOps, + List> matrixSources, + List drawSources ) {} - /** - * Check if the current thread is recording a display list. - * Only returns true for the thread that started recording. - * This prevents other threads from having their GL calls captured. - */ + public static RecordMode getRecordMode() { + if (currentRecorder == null || Thread.currentThread() != recordingThread) { + return RecordMode.NONE; + } + return glListMode == GL11.GL_COMPILE_AND_EXECUTE ? RecordMode.COMPILE_AND_EXECUTE : RecordMode.COMPILE; + } + + /** True only for the thread that started recording. */ public static boolean isRecording() { return currentRecorder != null && Thread.currentThread() == recordingThread; } - /** - * Get the ID of the display list currently being recorded. - * @return The list ID, or -1 if not recording - */ + public static boolean isCompileAndExecute() { + return glListMode == GL11.GL_COMPILE_AND_EXECUTE; + } + + /** Emit accumulated transform as MultMatrix if non-identity, then reset. */ + public static boolean 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; + } + + // Save pending transform ops for logging (before we clear them) + if (multMatrixSources != null && pendingTransformOps != null) { + if (pendingTransformOps.isEmpty()) { + LOGGER.warn("flushMatrix: non-identity transform with no tracked ops"); + multMatrixSources.add(Collections.singletonList("(unknown source)")); + } else { + multMatrixSources.add(new ArrayList<>(pendingTransformOps)); + } + pendingTransformOps.clear(); + } + + // Record the collapsed MultMatrix command (for playback) + if (currentRecorder != null) { + currentRecorder.recordMultMatrix(relativeTransform); + } + + // COMPILE_AND_EXECUTE: execute now. Bypass GLSM to avoid re-entering recording path. + if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { + flushMatrixBuffer.clear(); + relativeTransform.get(flushMatrixBuffer); + GL11.glMultMatrix(flushMatrixBuffer); + GLStateManager.getMatrixStack().mul(relativeTransform); + } + + // Reset to identity - we're now synchronized with GL + relativeTransform.identity(); + + return true; + } + + public static void matrixBarrier() { + flushMatrix(); + } + public static int getRecordingListId() { return glListId; } - /** - * Get the current display list mode (GL_COMPILE or GL_COMPILE_AND_EXECUTE). - * @return The current list mode, or 0 if not recording - */ public static int getListMode() { return glListMode; } - /** - * Get the current command count (for draw position tracking). - * @return The current command position - */ public static int getCommandCount() { return currentRecorder != null ? currentRecorder.getCommandCount() : 0; } - // ==================== Recording Method Delegates ==================== - // These delegate to the current CommandRecorder during compilation. + public static void trackDrawRangeSource(String source) { + if (drawRangeSources != null) { + drawRangeSources.add(source); + } + } - public static void recordEnable(int cap) { if (currentRecorder != null) currentRecorder.recordEnable(cap); } - public static void recordDisable(int cap) { if (currentRecorder != null) currentRecorder.recordDisable(cap); } - public static void recordClear(int mask) { if (currentRecorder != null) currentRecorder.recordClear(mask); } - public static void recordClearColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordClearColor(r, g, b, a); } - public static void recordClearDepth(double depth) { if (currentRecorder != null) currentRecorder.recordClearDepth(depth); } - public static void recordBlendColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordBlendColor(r, g, b, a); } - public static void recordClearStencil(int s) { if (currentRecorder != null) currentRecorder.recordClearStencil(s); } - public static void recordColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordColor(r, g, b, a); } - public static void recordColorMask(boolean r, boolean g, boolean b, boolean a) { if (currentRecorder != null) currentRecorder.recordColorMask(r, g, b, a); } - public static void recordDepthMask(boolean flag) { if (currentRecorder != null) currentRecorder.recordDepthMask(flag); } - public static void recordFrontFace(int mode) { if (currentRecorder != null) currentRecorder.recordFrontFace(mode); } - public static void recordDepthFunc(int func) { if (currentRecorder != null) currentRecorder.recordDepthFunc(func); } - public static void recordBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { if (currentRecorder != null) currentRecorder.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); } - public static void recordAlphaFunc(int func, float ref) { if (currentRecorder != null) currentRecorder.recordAlphaFunc(func, ref); } - public static void recordCullFace(int mode) { if (currentRecorder != null) currentRecorder.recordCullFace(mode); } - public static void recordShadeModel(int mode) { if (currentRecorder != null) currentRecorder.recordShadeModel(mode); } - public static void recordBindTexture(int target, int texture) { if (currentRecorder != null) currentRecorder.recordBindTexture(target, texture); } - public static void recordTexParameteri(int target, int pname, int param) { if (currentRecorder != null) currentRecorder.recordTexParameteri(target, pname, param); } - public static void recordTexParameterf(int target, int pname, float param) { if (currentRecorder != null) currentRecorder.recordTexParameterf(target, pname, param); } - public static void recordMatrixMode(int mode) { if (currentRecorder != null) currentRecorder.recordMatrixMode(mode); } - public static void recordLoadIdentity(int matrixMode) { if (currentRecorder != null) currentRecorder.recordLoadIdentity(matrixMode); } - public static void recordPushMatrix(int matrixMode) { if (currentRecorder != null) currentRecorder.recordPushMatrix(matrixMode); } - public static void recordPopMatrix(int matrixMode) { if (currentRecorder != null) currentRecorder.recordPopMatrix(matrixMode); } - public static void recordTranslate(int matrixMode, double x, double y, double z) { if (currentRecorder != null) currentRecorder.recordTranslate(matrixMode, x, y, z); } - public static void recordRotate(int matrixMode, double angle, double x, double y, double z) { if (currentRecorder != null) currentRecorder.recordRotate(matrixMode, angle, x, y, z); } - public static void recordScale(int matrixMode, double x, double y, double z) { if (currentRecorder != null) currentRecorder.recordScale(matrixMode, x, y, z); } - public static void recordMultMatrix(int matrixMode, Matrix4f matrix) { if (currentRecorder != null) currentRecorder.recordMultMatrix(matrixMode, matrix); } - public static void recordLoadMatrix(int matrixMode, Matrix4f matrix) { if (currentRecorder != null) currentRecorder.recordLoadMatrix(matrixMode, matrix); } - public static void recordOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { if (currentRecorder != null) currentRecorder.recordOrtho(left, right, bottom, top, zNear, zFar); } - public static void recordFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { if (currentRecorder != null) currentRecorder.recordFrustum(left, right, bottom, top, zNear, zFar); } - public static void recordViewport(int x, int y, int width, int height) { if (currentRecorder != null) currentRecorder.recordViewport(x, y, width, height); } - public static void recordPointSize(float size) { if (currentRecorder != null) currentRecorder.recordPointSize(size); } - public static void recordLineWidth(float width) { if (currentRecorder != null) currentRecorder.recordLineWidth(width); } - public static void recordLineStipple(int factor, int pattern) { if (currentRecorder != null) currentRecorder.recordLineStipple(factor, pattern); } - public static void recordPolygonOffset(float factor, float units) { if (currentRecorder != null) currentRecorder.recordPolygonOffset(factor, units); } - public static void recordPolygonMode(int face, int mode) { if (currentRecorder != null) currentRecorder.recordPolygonMode(face, mode); } - public static void recordColorMaterial(int face, int mode) { if (currentRecorder != null) currentRecorder.recordColorMaterial(face, mode); } - public static void recordLogicOp(int opcode) { if (currentRecorder != null) currentRecorder.recordLogicOp(opcode); } - public static void recordActiveTexture(int texture) { if (currentRecorder != null) currentRecorder.recordActiveTexture(texture); } - public static void recordUseProgram(int program) { if (currentRecorder != null) currentRecorder.recordUseProgram(program); } - public static void recordPushAttrib(int mask) { if (currentRecorder != null) currentRecorder.recordPushAttrib(mask); } - public static void recordPopAttrib() { if (currentRecorder != null) currentRecorder.recordPopAttrib(); } - public static void recordFogf(int pname, float param) { if (currentRecorder != null) currentRecorder.recordFogf(pname, param); } - public static void recordFogi(int pname, int param) { if (currentRecorder != null) currentRecorder.recordFogi(pname, param); } - public static void recordHint(int target, int mode) { if (currentRecorder != null) currentRecorder.recordHint(target, mode); } - public static void recordFog(int pname, java.nio.FloatBuffer params) { if (currentRecorder != null) currentRecorder.recordFog(pname, params); } - public static void recordLightf(int light, int pname, float param) { if (currentRecorder != null) currentRecorder.recordLightf(light, pname, param); } - public static void recordLighti(int light, int pname, int param) { if (currentRecorder != null) currentRecorder.recordLighti(light, pname, param); } - public static void recordLight(int light, int pname, java.nio.FloatBuffer params) { if (currentRecorder != null) currentRecorder.recordLight(light, pname, params); } - public static void recordLightModelf(int pname, float param) { if (currentRecorder != null) currentRecorder.recordLightModelf(pname, param); } - public static void recordLightModeli(int pname, int param) { if (currentRecorder != null) currentRecorder.recordLightModeli(pname, param); } - public static void recordLightModel(int pname, java.nio.FloatBuffer params) { if (currentRecorder != null) currentRecorder.recordLightModel(pname, params); } - public static void recordMaterialf(int face, int pname, float val) { if (currentRecorder != null) currentRecorder.recordMaterialf(face, pname, val); } - public static void recordMaterial(int face, int pname, java.nio.FloatBuffer params) { if (currentRecorder != null) currentRecorder.recordMaterial(face, pname, params); } - public static void recordStencilFunc(int func, int ref, int mask) { if (currentRecorder != null) currentRecorder.recordStencilFunc(func, ref, mask); } - public static void recordStencilFuncSeparate(int face, int func, int ref, int mask) { if (currentRecorder != null) currentRecorder.recordStencilFuncSeparate(face, func, ref, mask); } - public static void recordStencilOp(int fail, int zfail, int zpass) { if (currentRecorder != null) currentRecorder.recordStencilOp(fail, zfail, zpass); } - public static void recordStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { if (currentRecorder != null) currentRecorder.recordStencilOpSeparate(face, sfail, dpfail, dppass); } - public static void recordStencilMask(int mask) { if (currentRecorder != null) currentRecorder.recordStencilMask(mask); } - public static void recordStencilMaskSeparate(int face, int mask) { if (currentRecorder != null) currentRecorder.recordStencilMaskSeparate(face, mask); } - public static void recordCallList(int listId) { if (currentRecorder != null) currentRecorder.recordCallList(listId); } - public static void recordDrawBuffer(int mode) { if (currentRecorder != null) currentRecorder.recordDrawBuffer(mode); } - public static void recordDrawBuffers(int count, int buf) { if (currentRecorder != null) currentRecorder.recordDrawBuffers(count, buf); } - public static void recordDrawBuffers(int count, java.nio.IntBuffer bufs) { if (currentRecorder != null) currentRecorder.recordDrawBuffers(count, bufs); } - public static void recordComplexCommand(DisplayListCommand cmd) { if (currentRecorder != null) currentRecorder.recordComplexCommand(cmd); } + // Draw barriers: state commands that prevent draw merging + private static void drawBarrier() { + stateGeneration++; + } + + public static void recordEnable(int cap) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordEnable(cap); + } + + public static void recordDisable(int cap) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDisable(cap); + } + + // ==================== NON-BARRIER COMMANDS ==================== + // Clear commands don't affect subsequent draws, just clear buffers. + + public static void recordClear(int mask) { + if (currentRecorder == null) return; + currentRecorder.recordClear(mask); + } + + public static void recordClearColor(float r, float g, float b, float a) { + if (currentRecorder == null) return; + currentRecorder.recordClearColor(r, g, b, a); + } + + public static void recordClearDepth(double depth) { + if (currentRecorder == null) return; + currentRecorder.recordClearDepth(depth); + } + + public static void recordClearStencil(int s) { + if (currentRecorder == null) return; + currentRecorder.recordClearStencil(s); + } + + // ==================== MORE DRAW BARRIER COMMANDS ==================== + + public static void recordBlendColor(float r, float g, float b, float a) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordBlendColor(r, g, b, a); + } + + public static void recordColor(float r, float g, float b, float a) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordColor(r, g, b, a); + } + + public static void recordColorMask(boolean r, boolean g, boolean b, boolean a) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordColorMask(r, g, b, a); + } + + public static void recordDepthMask(boolean flag) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDepthMask(flag); + } + + public static void recordFrontFace(int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordFrontFace(mode); + } + + public static void recordDepthFunc(int func) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDepthFunc(func); + } + + public static void recordBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); + } + + public static void recordAlphaFunc(int func, float ref) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordAlphaFunc(func, ref); + } + + public static void recordCullFace(int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordCullFace(mode); + } + + public static void recordShadeModel(int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordShadeModel(mode); + } + + public static void recordBindTexture(int target, int texture) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordBindTexture(target, texture); + } + + public static void recordTexParameteri(int target, int pname, int param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordTexParameteri(target, pname, param); + } + + public static void recordTexParameterf(int target, int pname, float param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordTexParameterf(target, pname, param); + } + + public static void recordMatrixMode(int mode) { + if (currentRecorder == null) return; + matrixBarrier(); // Matrix barrier: flush and reset + currentRecorder.recordMatrixMode(mode); + } + + public static void recordPushMatrix() { + if (currentRecorder == null) return; + // Flush any pending delta, then record push. + flushMatrix(); + currentRecorder.recordPushMatrix(); + } + + public static void recordPopMatrix() { + if (currentRecorder == null) return; + // Flush any pending delta, then record pop. + flushMatrix(); + currentRecorder.recordPopMatrix(); + } + + public static void recordViewport(int x, int y, int width, int height) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordViewport(x, y, width, height); + } + + public static void recordPointSize(float size) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordPointSize(size); + } + + public static void recordLineWidth(float width) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLineWidth(width); + } + + public static void recordLineStipple(int factor, int pattern) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLineStipple(factor, pattern); + } + + public static void recordPolygonOffset(float factor, float units) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordPolygonOffset(factor, units); + } + + public static void recordPolygonMode(int face, int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordPolygonMode(face, mode); + } + + public static void recordColorMaterial(int face, int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordColorMaterial(face, mode); + } + + public static void recordLogicOp(int opcode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLogicOp(opcode); + } + + public static void recordActiveTexture(int texture) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordActiveTexture(texture); + } + + public static void recordUseProgram(int program) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordUseProgram(program); + } + + // PushAttrib saves state but doesn't change it - not a draw barrier + public static void recordPushAttrib(int mask) { + if (currentRecorder == null) return; + currentRecorder.recordPushAttrib(mask); + } + + // PopAttrib restores potentially any state - draw barrier + public static void recordPopAttrib() { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordPopAttrib(); + } + + public static void recordFogf(int pname, float param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordFogf(pname, param); + } + + public static void recordFogi(int pname, int param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordFogi(pname, param); + } + + public static void recordHint(int target, int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordHint(target, mode); + } + + public static void recordFog(int pname, java.nio.FloatBuffer params) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordFog(pname, params); + } + + public static void recordLightf(int light, int pname, float param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLightf(light, pname, param); + } + + public static void recordLighti(int light, int pname, int param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLighti(light, pname, param); + } + + public static void recordLight(int light, int pname, java.nio.FloatBuffer params) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLight(light, pname, params); + } + + public static void recordLightModelf(int pname, float param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLightModelf(pname, param); + } + + public static void recordLightModeli(int pname, int param) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLightModeli(pname, param); + } + + public static void recordLightModel(int pname, java.nio.FloatBuffer params) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordLightModel(pname, params); + } + + public static void recordMaterialf(int face, int pname, float val) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordMaterialf(face, pname, val); + } + + public static void recordMaterial(int face, int pname, java.nio.FloatBuffer params) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordMaterial(face, pname, params); + } + + public static void recordStencilFunc(int func, int ref, int mask) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilFunc(func, ref, mask); + } + + public static void recordStencilFuncSeparate(int face, int func, int ref, int mask) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilFuncSeparate(face, func, ref, mask); + } + + public static void recordStencilOp(int fail, int zfail, int zpass) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilOp(fail, zfail, zpass); + } + + public static void recordStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilOpSeparate(face, sfail, dpfail, dppass); + } + + public static void recordStencilMask(int mask) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilMask(mask); + } + + public static void recordStencilMaskSeparate(int face, int mask) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordStencilMaskSeparate(face, mask); + } + + public static void recordCallList(int listId) { + if (currentRecorder == null) return; + matrixBarrier(); // Matrix barrier: nested list has own transforms + currentRecorder.recordCallList(listId); + } + + public static void recordDrawBuffer(int mode) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDrawBuffer(mode); + } + + public static void recordDrawBuffers(int count, int buf) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDrawBuffers(count, buf); + } + + public static void recordDrawBuffers(int count, java.nio.IntBuffer bufs) { + if (currentRecorder == null) return; + drawBarrier(); + currentRecorder.recordDrawBuffers(count, bufs); + } + + // Complex commands are texture uploads - not draw barriers + public static void recordComplexCommand(DisplayListCommand cmd) { + if (currentRecorder == null) return; + currentRecorder.recordComplexCommand(cmd); + } + + public static void recordLoadMatrix(Matrix4f matrix) { + if (currentRecorder != null) currentRecorder.recordLoadMatrix(matrix); + } + + public static void recordLoadIdentity() { + if (currentRecorder != null) currentRecorder.recordLoadIdentity(); + } + + // recordOrtho/recordFrustum removed - these now accumulate into relativeTransform + // via updateRelativeTransformOrtho/updateRelativeTransformFrustum /** * Add an immediate mode draw to the current display list compilation. @@ -261,45 +608,80 @@ public class DisplayListManager { return; } - // Get relative transform (changes since glNewList, not absolute matrix state) - final Matrix4f currentTransform = new Matrix4f(relativeTransform); + 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(); - // Add quad draw if we have quads if (!result.quads().isEmpty()) { - final AccumulatedDraw quadDraw = new AccumulatedDraw(result.quads(), currentTransform, result.flags(), getCommandCount()); + 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()); + final AccumulatedLineDraw lineDraw = new AccumulatedLineDraw(result.lines(), currentTransform, result.flags(), getCommandCount(), currentBatchId); accumulatedLineDraws.add(lineDraw); } } - /** - * Update the relative transform during display list compilation. - * Called by GLStateManager matrix methods (glTranslate, glRotate, glScale). - * - * @param x Translation x, scale x, or rotation angle (degrees) - * @param y Translation y or scale y (ignored for rotate) - * @param z Translation z or scale z (ignored for rotate) - * @param op The operation type - * @param rotationAxis For rotation only, the axis vector (null otherwise) - */ + private static void applyTransformOp(Matrix4f m, float x, float y, float z, TransformOp op, Vector3f axis) { + switch (op) { + case TRANSLATE -> m.translate(x, y, z); + case SCALE -> m.scale(x, y, z); + case ROTATE -> { if (axis != null) m.rotate((float) Math.toRadians(x), axis); } + } + } + public static void updateRelativeTransform(float x, float y, float z, TransformOp op, Vector3f rotationAxis) { - if (relativeTransform == null || !GLStateManager.isModelViewMatrix()) { + if (relativeTransform == null) return; + + if (DEBUG_DISPLAY_LISTS) { + final Matrix4f singleTransform = new Matrix4f(); + applyTransformOp(singleTransform, x, y, z, op, rotationAxis); + if (currentRecorder != null) currentRecorder.recordMultMatrix(singleTransform); + if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { + flushMatrixBuffer.clear(); + singleTransform.get(flushMatrixBuffer); + GL11.glMultMatrix(flushMatrixBuffer); + GLStateManager.getMatrixStack().mul(singleTransform); + } return; } - switch (op) { - case TRANSLATE -> relativeTransform.translate(x, y, z); - case SCALE -> relativeTransform.scale(x, y, z); - case ROTATE -> { - if (rotationAxis != null) { - relativeTransform.rotate((float) Math.toRadians(x), rotationAxis); - } - } + applyTransformOp(relativeTransform, x, y, z, op, rotationAxis); + matrixGeneration++; + + if (pendingTransformOps != null) { + final String log = switch (op) { + case TRANSLATE -> String.format("glTranslatef(%.4f, %.4f, %.4f)", x, y, z); + case SCALE -> String.format("glScalef(%.4f, %.4f, %.4f)", x, y, z); + case ROTATE -> rotationAxis != null ? String.format("glRotatef(%.4f, %.4f, %.4f, %.4f)", x, rotationAxis.x, rotationAxis.y, rotationAxis.z) : null; + }; + if (log != null) pendingTransformOps.add(log); } } @@ -307,6 +689,9 @@ public class DisplayListManager { * Update the relative transform with a matrix multiplication during display list compilation. * Called by GLStateManager.glMultMatrix(). * + *

In normal mode: accumulates transforms, emits collapsed MultMatrix at barriers. + *

In debug mode: emits MultMatrix immediately (no collapsing). + * * @param matrix The matrix to multiply */ public static void updateRelativeTransform(Matrix4f matrix) { @@ -314,51 +699,76 @@ public class DisplayListManager { return; } - // Only track MODELVIEW - projection/texture don't affect baked geometry - if (!GLStateManager.isModelViewMatrix()) { + if (DEBUG_DISPLAY_LISTS) { + if (currentRecorder != null) { + currentRecorder.recordMultMatrix(matrix); + } + + if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { + flushMatrixBuffer.clear(); + matrix.get(flushMatrixBuffer); + GL11.glMultMatrix(flushMatrixBuffer); + GLStateManager.getMatrixStack().mul(matrix); + } return; } relativeTransform.mul(matrix); + matrixGeneration++; + + if (pendingTransformOps != null) { + pendingTransformOps.add("glMultMatrixf(...)"); + } } - /** - * Push the current MODELVIEW transform onto the stack. - * Only operates when current matrix mode is MODELVIEW. - * Called by GLStateManager.glPushMatrix() during recording. - */ - public static void pushRelativeTransform() { - if (relativeTransform == null) { + // Reusable matrix for ortho/frustum computation + private static final Matrix4f orthoFrustumTemp = new Matrix4f(); + + /** Accumulate ortho projection into relativeTransform. */ + public static void updateRelativeTransformOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { + if (relativeTransform == null) return; + + orthoFrustumTemp.identity().ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar); + + if (DEBUG_DISPLAY_LISTS) { + if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp); + if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { + flushMatrixBuffer.clear(); + orthoFrustumTemp.get(flushMatrixBuffer); + GL11.glMultMatrix(flushMatrixBuffer); + GLStateManager.getMatrixStack().mul(orthoFrustumTemp); + } return; } - // Only track MODELVIEW - projection/texture don't affect baked geometry - if (!GLStateManager.isModelViewMatrix()) { - return; + relativeTransform.mul(orthoFrustumTemp); + matrixGeneration++; + if (pendingTransformOps != null) { + pendingTransformOps.add(String.format("glOrtho(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } - - relativeTransform.pushMatrix(); } - /** - * Pop the MODELVIEW transform from stack. - * Only operates when current matrix mode is MODELVIEW. - * Called by GLStateManager.glPopMatrix() during recording. - */ - public static void popRelativeTransform() { - if (relativeTransform == null) { + /** Accumulate frustum projection into relativeTransform. */ + public static void updateRelativeTransformFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { + if (relativeTransform == null) return; + + orthoFrustumTemp.identity().frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar); + + if (DEBUG_DISPLAY_LISTS) { + if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp); + if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { + flushMatrixBuffer.clear(); + orthoFrustumTemp.get(flushMatrixBuffer); + GL11.glMultMatrix(flushMatrixBuffer); + GLStateManager.getMatrixStack().mul(orthoFrustumTemp); + } return; } - // Only track MODELVIEW - projection/texture don't affect baked geometry - if (!GLStateManager.isModelViewMatrix()) { - return; - } - - try { - relativeTransform.popMatrix(); - } catch (RuntimeException e) { - LOGGER.warn("[DisplayList] Transform stack underflow in list={}", glListId); + relativeTransform.mul(orthoFrustumTemp); + matrixGeneration++; + if (pendingTransformOps != null) { + pendingTransformOps.add(String.format("glFrustum(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } } @@ -394,7 +804,6 @@ public class DisplayListManager { /** * Get a compiled display list from the cache. - * Used by CallListCmd to execute nested display lists with the unoptimized version. * * @param list The display list ID * @return The CompiledDisplayList, or null if not found @@ -406,6 +815,8 @@ public class DisplayListManager { /** * Start display list compilation. * Supports nested glNewList() calls (spec-violating but needed for mod compatibility). + * GL_COMPILE: Commands are recorded only (not executed), GLSM cache unchanged + * 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 @@ -421,7 +832,9 @@ public class DisplayListManager { // Save current compilation context and start fresh for nested list final CompilationContext parentContext = new CompilationContext( glListId, glListMode, currentRecorder, accumulatedDraws, accumulatedLineDraws, - accumulatedPrimitiveDraws, relativeTransform, tessellatorCompiling, immediateModeRecorder + accumulatedPrimitiveDraws, relativeTransform, + tessellatorCompiling, immediateModeRecorder, compilationStackTrace, + pendingTransformOps, multMatrixSources, drawRangeSources ); compilationStack.push(parentContext); } @@ -435,8 +848,23 @@ public class DisplayListManager { accumulatedLineDraws = new ArrayList<>(16); // Immediate mode line draws are less common accumulatedPrimitiveDraws = new ArrayList<>(16); // Tessellator primitive draws are less common relativeTransform = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH); - relativeTransform.identity(); // Track relative transforms from identity + 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) + if (LOG_DISPLAY_LIST_COMPILATION) { + pendingTransformOps = new ArrayList<>(); + multMatrixSources = new ArrayList<>(); + drawRangeSources = new ArrayList<>(); + } else { + pendingTransformOps = null; + multMatrixSources = null; + 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.) @@ -449,26 +877,33 @@ public class DisplayListManager { return; } - // Get relative transform (changes since glNewList, not absolute matrix state) - final Matrix4f currentTransform = new Matrix4f(relativeTransform); + 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)); + 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)); + accumulatedPrimitiveDraws.add(new AccumulatedPrimitiveDraw(primitives, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId)); } }); tessellatorCompiling = true; // We hijack display list compilation completely - no GL11.glNewList() calls - // During compile don't actually apply any changes to GL, but do track them - GLStateManager.getModelViewMatrix().pushMatrix(); // Save current model view matrix state - GLStateManager.pushState(GL11.GL_ALL_ATTRIB_BITS); } /** @@ -478,7 +913,7 @@ public class DisplayListManager { if (glListMode == 0) { throw new RuntimeException("glEndList called outside of a display list!"); } - final boolean needsRender = glListMode == GL11.GL_COMPILE_AND_EXECUTE; + flushMatrix(); final boolean isNested = !compilationStack.isEmpty(); // Stop compiling mode (works for both root and nested lists now) @@ -520,13 +955,20 @@ public class DisplayListManager { currentRecorder.free(); compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), ownedVbos); - displayListCache.put(glListId, compiled); } else { // Free the recorder even if empty if (currentRecorder != null) { currentRecorder.free(); } - compiled = null; + // Empty display list - per OpenGL spec, still valid after glNewList/glEndList + compiled = CompiledDisplayList.EMPTY; + } + // Store the compiled list (even if empty - an empty list is still a valid list) + displayListCache.put(glListId, compiled); + + // Log compilation details if enabled (before context restoration changes glListId) + if (LOG_DISPLAY_LIST_COMPILATION) { + logCompiledDisplayList(glListId, compiled, compilationStackTrace); } // Handle nested compilation - restore parent context @@ -543,6 +985,10 @@ public class DisplayListManager { relativeTransform = parentContext.transform; tessellatorCompiling = parentContext.wasTessellatorCompiling; immediateModeRecorder = parentContext.immediateRecorder; + compilationStackTrace = parentContext.stackTrace; + pendingTransformOps = parentContext.pendingOps; + multMatrixSources = parentContext.matrixSources; + drawRangeSources = parentContext.drawSources; // Note: TessellatorManager callback stack was popped by stopCompiling() // Parent's COMPILING callback is now active again @@ -555,34 +1001,27 @@ public class DisplayListManager { accumulatedPrimitiveDraws = null; relativeTransform = null; immediateModeRecorder = null; + compilationStackTrace = null; + pendingTransformOps = null; + multMatrixSources = null; + drawRangeSources = null; glListId = -1; glListMode = 0; } - - GLStateManager.getModelViewMatrix().popMatrix(); - GLStateManager.popState(); - - // Only execute if COMPILE_AND_EXECUTE AND this is the root (non-nested) list - // Nested lists will execute naturally when the parent executes via CallListCmd - if (needsRender && !isNested && compiled != null) { - compiled.render(); - } } /** * Execute a compiled display list. */ public static void glCallList(int list) { - // If we're currently recording, record a reference to this list Per OpenGL spec: the inner list is NOT executed during compilation. - // It only executes when the parent list is played back. - // For GL_COMPILE_AND_EXECUTE: the entire parent list (including this CallListCmd) executes at the end of glEndList, not during compilation. if (currentRecorder != null) { - // Record a CallList command that will execute the referenced list during playback recordCallList(list); - return; + + if (glListMode == GL11.GL_COMPILE) { + return; + } } - // Normal playback mode final CompiledDisplayList compiled = displayListCache.get(list); if (compiled != null) { GLStateManager.trySyncProgram(); @@ -934,4 +1373,257 @@ public class DisplayListManager { return vao; } + // ==================== DEBUG LOGGING ==================== + + private static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) { + final StringBuilder sb = new StringBuilder(); + sb.append("\n========== Display List Compiled: ID=").append(listId).append(" ==========\n"); + + // Identify probable source mod from stack trace + sb.append("Source: ").append(identifySourceFromStackTrace(stackTrace)).append("\n"); + + // Log commands if not empty + if (compiled == CompiledDisplayList.EMPTY) { + sb.append("Contents: EMPTY (no commands or draws)\n"); + } else { + final ByteBuffer buffer = compiled.getCommandBuffer(); + if (buffer == null || buffer.limit() == 0) { + sb.append("Contents: No commands\n"); + } else { + sb.append("Commands (").append(buffer.limit()).append(" bytes):\n"); + dumpCommandBuffer(buffer, compiled.getComplexObjects(), compiled.getOwnedVbos(), sb); + } + } + + // Log full stack trace + sb.append("\nFull Stack Trace:\n"); + if (stackTrace != null) { + for (StackTraceElement element : stackTrace) { + sb.append(" at ").append(element.toString()).append("\n"); + } + } else { + sb.append(" (not captured)\n"); + } + + sb.append("========== End Display List ").append(listId).append(" ==========\n"); + LOGGER.debug(sb.toString()); + } + + private static String identifySourceFromStackTrace(StackTraceElement[] stackTrace) { + if (stackTrace == null || stackTrace.length == 0) { + return "Unknown (no stack trace)"; + } + + for (StackTraceElement element : stackTrace) { + final String className = element.getClassName(); + + // Skip Java/LWJGL/Angelica/Minecraft internals + if (className.startsWith("java.") || className.startsWith("sun.") || + className.startsWith("jdk.") || + className.startsWith("org.lwjgl.") || + className.startsWith("com.gtnewhorizons.angelica.") || + className.startsWith("com.gtnewhorizon.gtnhlib.") || + className.startsWith("net.minecraft.") || + className.startsWith("net.minecraftforge.") || + className.contains("GLStateManager") || + className.contains("GradleStart") || + className.contains("launchwrapper") || + className.contains("retrofuturabootstrap")) { + continue; + } + + // Try to extract mod name from package + final String modGuess = guessModFromClassName(className); + return modGuess + " (" + element.getClassName() + "." + element.getMethodName() + + ":" + element.getLineNumber() + ")"; + } + + // Fallback: return the first non-internal frame with class info + for (StackTraceElement element : stackTrace) { + final String className = element.getClassName(); + if (!className.startsWith("java.") && !className.startsWith("sun.") && !className.startsWith("jdk.")) { + return guessModFromClassName(className) + " (" + element + ")"; + } + } + return "Unknown"; + } + + private static String guessModFromClassName(String className) { + final String lc = className.toLowerCase(); + + // Common mod package patterns (use lowercase for matching) + if (lc.contains("buildcraft")) return "BuildCraft"; + if (lc.contains("cofh")) return "CoFH/ThermalExpansion"; + if (lc.contains(".ic2.") || lc.startsWith("ic2.")) return "IndustrialCraft2"; + if (lc.contains("gregtech")) return "GregTech"; + if (lc.contains("thaumcraft")) return "Thaumcraft"; + if (lc.contains("forestry")) return "Forestry"; + if (lc.contains("appeng") || lc.contains(".ae2.")) return "Applied Energistics 2"; + if (lc.contains("enderio") || lc.contains("crazypants.ender")) return "EnderIO"; + if (lc.contains("mekanism")) return "Mekanism"; + if (lc.contains("tconstruct")) return "Tinkers Construct"; + if (lc.contains("chisel")) return "Chisel"; + if (lc.contains("opencomputers") || lc.contains("li.cil.oc")) return "OpenComputers"; + if (lc.contains("computercraft") || lc.contains("dan200.computer")) return "ComputerCraft"; + if (lc.contains("railcraft")) return "Railcraft"; + if (lc.contains("projectred") || lc.contains("mrtjpcore")) return "Project Red"; + if (lc.contains("botania")) return "Botania"; + if (lc.contains("extrautil")) return "ExtraUtilities"; + if (lc.contains("openblocks")) return "OpenBlocks"; + if (lc.contains("carpenters")) return "Carpenters Blocks"; + if (lc.contains("biomesoplenty")) return "Biomes O Plenty"; + if (lc.contains("natura")) return "Natura"; + if (lc.contains("twilightforest")) return "Twilight Forest"; + if (lc.contains("immersive")) return "Immersive Engineering"; + if (lc.contains("galacticraft")) return "Galacticraft"; + if (lc.contains("draconicevolution")) return "Draconic Evolution"; + if (lc.contains("net.minecraft")) return "Minecraft"; + + // Extract first 2 package segments as fallback + final String[] parts = className.split("\\."); + if (parts.length >= 2) { + return parts[0] + "." + parts[1]; + } + return className; + } + + private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos, StringBuilder sb) { + if (buffer == null) return; + + final long basePtr = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.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 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); + 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); + 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(")"); + // 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("]"); + } + multMatrixIdx++; + ptr += 68; // cmd + 16 floats + } + 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)); + 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); + 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); + 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); + sb.append("(").append(calledList).append(")"); + ptr += 8; + } + case GLCommand.MATRIX_MODE -> { + final int mode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.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 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); + } + } + 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 index 37d9ddee8..504affc81 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRange.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRange.java @@ -1,11 +1,25 @@ 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 -record DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {} +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 index bc881f041..86941e015 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRangeWithBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DrawRangeWithBuffer.java @@ -1,12 +1,43 @@ 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 brightness flag. + * 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, boolean hasBrightness) {} +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 index 92d9bd438..4ace6129c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/FormatBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/FormatBuffer.java @@ -11,13 +11,7 @@ import java.util.List; /** * Accumulates geometry for a single vertex format during display list compilation. - * All draws with the same format are collected here, then compiled into a single VBO. - *

- * 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)
  • - *
+ * Tracks merged ranges (same-transform draws combined) and per-draw ranges (1:1). */ class FormatBuffer { final CapturingTessellator.Flags flags; @@ -36,25 +30,36 @@ class FormatBuffer { 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 to this format buffer. - * Tracks both merged (for optimized) and per-draw (for unoptimized) ranges. - */ + /** Add a draw, tracking both merged and per-draw ranges. */ void addDraw(AccumulatedDraw draw) { - int vertexCount = draw.quads.size() * 4; // 4 vertices per quad + final int vertexCount = draw.quads.size() * 4; // 4 vertices per quad - // Always track per-draw range for unoptimized path - perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex)); + // 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 - if (pendingTransform != null && pendingTransform.equals(draw.transform)) { + // 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(); @@ -64,6 +69,9 @@ class FormatBuffer { pendingVertexCount = vertexCount; pendingTransform = new Matrix4f(draw.transform); pendingCommandIndex = draw.commandIndex; + pendingGeneration = draw.matrixGeneration; + pendingStateGen = draw.stateGeneration; + pendingRestoreData = draw.restoreData; } allQuads.addAll(draw.quads); @@ -71,16 +79,18 @@ class FormatBuffer { } private void flushPendingRange() { - if (pendingTransform != null) { - mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex)); + if (pendingGeneration != -1) { + mergedRanges.add(new DrawRange( + pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex, pendingRestoreData + )); pendingTransform = null; + pendingGeneration = -1; + pendingStateGen = -1; + pendingRestoreData = null; } } - /** - * Compile all accumulated quads into a single VBO. - * @return The compiled buffer with VBO and both range types - */ + /** Compile accumulated quads into a VBO. */ CompiledFormatBuffer finish() { // Flush any remaining pending range flushPendingRange(); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index b5ce42704..193a32879 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm; 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.CompiledDisplayList; import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import com.gtnewhorizons.angelica.glsm.recording.commands.TexImage2DCmd; @@ -478,8 +479,12 @@ public class GLStateManager { // LWJGL Overrides public static void glEnable(int cap) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordEnable(cap); + if (mode == RecordMode.COMPILE) { + return; + } } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { @@ -553,8 +558,12 @@ public class GLStateManager { } public static void glDisable(int cap) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDisable(cap); + if (mode == RecordMode.COMPILE) { + return; + } } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { @@ -926,14 +935,24 @@ public class GLStateManager { // GLStateManager Functions public static void glBlendColor(float red, float green, float blue, float alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordBlendColor(red, green, blue, alpha); - } else { - GL14.glBlendColor(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; + } } + GL14.glBlendColor(red, green, blue, alpha); } public static void enableBlend() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_BLEND); + if (mode == RecordMode.COMPILE) { + return; + } + } if (Iris.enabled) { if (BlendModeStorage.isBlendLocked()) { BlendModeStorage.deferBlendModeToggle(true); @@ -944,6 +963,13 @@ public class GLStateManager { } public static void disableBlend() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_BLEND); + if (mode == RecordMode.COMPILE) { + return; + } + } if (Iris.enabled) { if (BlendModeStorage.isBlendLocked()) { BlendModeStorage.deferBlendModeToggle(false); @@ -954,16 +980,34 @@ public class GLStateManager { } public static void enableScissorTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_SCISSOR_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } scissorTest.enable(); } public static void disableScissorTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_SCISSOR_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } scissorTest.disable(); } public static void glBlendFunc(int srcFactor, int dstFactor) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor); + if (mode == RecordMode.COMPILE) { + return; + } } if (Iris.enabled) { if (BlendModeStorage.isBlendLocked()) { @@ -975,19 +1019,13 @@ public class GLStateManager { final boolean caching = isCachingEnabled(); if (HUDCaching.renderingCacheOverride) { if (caching) blendState.setAll(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - OpenGlHelper.glBlendFunc(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); - } + OpenGlHelper.glBlendFunc(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); return; } final boolean bypass = BYPASS_CACHE || !caching; if (bypass || blendState.getSrcRgb() != srcFactor || blendState.getDstRgb() != dstFactor) { if (caching) blendState.setSrcDstRgb(srcFactor, dstFactor); - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - GL11.glBlendFunc(srcFactor, dstFactor); - } + GL11.glBlendFunc(srcFactor, dstFactor); } // Iris @@ -1009,8 +1047,12 @@ public class GLStateManager { } public static void tryBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); + if (mode == RecordMode.COMPILE) { + return; + } } if (Iris.enabled) { if (BlendModeStorage.isBlendLocked()) { @@ -1027,10 +1069,7 @@ public class GLStateManager { final boolean bypass = BYPASS_CACHE || !caching; if (bypass || blendState.getSrcRgb() != srcRgb || blendState.getDstRgb() != dstRgb || blendState.getSrcAlpha() != srcAlpha || blendState.getDstAlpha() != dstAlpha) { if (caching) blendState.setAll(srcRgb, dstRgb, srcAlpha, dstAlpha); - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - OpenGlHelper.glBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); - } + OpenGlHelper.glBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); } // Iris @@ -1087,21 +1126,27 @@ public class GLStateManager { } public static void glDepthFunc(int func) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDepthFunc(func); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || func != depthState.getFunc()) { if (caching) depthState.setFunc(func); - if (!isRecordingDisplayList()) { - GL11.glDepthFunc(func); - } + GL11.glDepthFunc(func); } } public static void glDepthMask(boolean mask) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDepthMask(mask); + if (mode == RecordMode.COMPILE) { + return; + } } if (Iris.enabled) { if (DepthColorStorage.isDepthColorLocked()) { @@ -1112,9 +1157,7 @@ public class GLStateManager { final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || mask != depthState.isEnabled()) { if (caching) depthState.setEnabled(mask); - if (!isRecordingDisplayList()) { - GL11.glDepthMask(mask); - } + GL11.glDepthMask(mask); } } @@ -1123,91 +1166,107 @@ public class GLStateManager { } public static void glColor4f(float red, float green, float blue, float alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(red, green, blue, alpha); - changeColor(red, green, blue, alpha); // Update state for glGet queries - } else { - if (changeColor(red, green, blue, alpha)) { - GL11.glColor4f(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(red, green, blue, alpha)) { + GL11.glColor4f(red, green, blue, alpha); + } } public static void glColor4d(double red, double green, double blue, double alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor((float) red, (float) green, (float) blue, (float) alpha); - changeColor((float) red, (float) green, (float) blue, (float) alpha); // Update state for glGet queries - } else { - if (changeColor((float) red, (float) green, (float) blue, (float) alpha)) { - GL11.glColor4d(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor((float) red, (float) green, (float) blue, (float) alpha)) { + GL11.glColor4d(red, green, blue, alpha); + } } public static void glColor4b(byte red, byte green, byte blue, byte alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(b2f(red), b2f(green), b2f(blue), b2f(alpha)); - changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha)); // Update state for glGet queries - } else { - if (changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha))) { - GL11.glColor4b(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha))) { + GL11.glColor4b(red, green, blue, alpha); + } } public static void glColor4ub(byte red, byte green, byte blue, byte alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha)); - changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha)); // Update state for glGet queries - } else { - if (changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha))) { - GL11.glColor4ub(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha))) { + GL11.glColor4ub(red, green, blue, alpha); + } } public static void glColor3f(float red, float green, float blue) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(red, green, blue, 1.0F); - changeColor(red, green, blue, 1.0F); // Update state for glGet queries - } else { - if (changeColor(red, green, blue, 1.0F)) { - GL11.glColor3f(red, green, blue); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(red, green, blue, 1.0F)) { + GL11.glColor3f(red, green, blue); + } } public static void glColor3d(double red, double green, double blue) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor((float) red, (float) green, (float) blue, 1.0F); - changeColor((float) red, (float) green, (float) blue, 1.0F); // Update state for glGet queries - } else { - if (changeColor((float) red, (float) green, (float) blue, 1.0F)) { - GL11.glColor3d(red, green, blue); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor((float) red, (float) green, (float) blue, 1.0F)) { + GL11.glColor3d(red, green, blue); + } } public static void glColor3b(byte red, byte green, byte blue) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(b2f(red), b2f(green), b2f(blue), 1.0F); - changeColor(b2f(red), b2f(green), b2f(blue), 1.0F); // Update state for immediate mode vertex capture - } else { - if (changeColor(b2f(red), b2f(green), b2f(blue), 1.0F)) { - GL11.glColor3b(red, green, blue); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(b2f(red), b2f(green), b2f(blue), 1.0F)) { + GL11.glColor3b(red, green, blue); + } } public static void glColor3ub(byte red, byte green, byte blue) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F); - changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F); // Update state for immediate mode vertex capture - } else { - if (changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F)) { - GL11.glColor3ub(red, green, blue); + if (mode == RecordMode.COMPILE) { + return; } } + if (changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F)) { + GL11.glColor3ub(red, green, blue); + } } private static float ub2f(byte b) { @@ -1242,8 +1301,12 @@ public class GLStateManager { } public static void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordColorMask(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; + } } if (Iris.enabled) { if (DepthColorStorage.isDepthColorLocked()) { @@ -1256,45 +1319,51 @@ public class GLStateManager { final boolean bypass = BYPASS_CACHE || !caching; if (bypass || red != colorMask.red || green != colorMask.green || blue != colorMask.blue || alpha != colorMask.alpha) { if (caching) colorMask.setAll(red, green, blue, alpha); - if (!isRecordingDisplayList()) { - GL11.glColorMask(red, green, blue, alpha); - } + GL11.glColorMask(red, green, blue, alpha); } } // Clear Color public static void glClearColor(float red, float green, float blue, float alpha) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordClearColor(red, green, blue, alpha); - // Update state for glGet queries (recording only happens on main thread) - clearColor.setRed(red); - clearColor.setGreen(green); - clearColor.setBlue(blue); - clearColor.setAlpha(alpha); - } else { - final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || red != clearColor.getRed() || green != clearColor.getGreen() || blue != clearColor.getBlue() || alpha != clearColor.getAlpha()) { - if (caching) { - clearColor.setRed(red); - clearColor.setGreen(green); - clearColor.setBlue(blue); - clearColor.setAlpha(alpha); - } - GL11.glClearColor(red, green, blue, alpha); + if (mode == RecordMode.COMPILE) { + return; } } + final boolean caching = isCachingEnabled(); + if (BYPASS_CACHE || !caching || red != clearColor.getRed() || green != clearColor.getGreen() || blue != clearColor.getBlue() || alpha != clearColor.getAlpha()) { + if (caching) { + clearColor.setRed(red); + clearColor.setGreen(green); + clearColor.setBlue(blue); + clearColor.setAlpha(alpha); + } + GL11.glClearColor(red, green, blue, alpha); + } } public static void glClearDepth(double depth) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordClearDepth(depth); - } else { - GL11.glClearDepth(depth); + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glClearDepth(depth); } // ALPHA public static void enableAlphaTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_ALPHA_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } if (Iris.enabled) { if (AlphaTestStorage.isAlphaTestLocked()) { AlphaTestStorage.deferAlphaTestToggle(true); @@ -1305,6 +1374,13 @@ public class GLStateManager { } public static void disableAlphaTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_ALPHA_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } if (Iris.enabled) { if (AlphaTestStorage.isAlphaTestLocked()) { AlphaTestStorage.deferAlphaTestToggle(false); @@ -1315,8 +1391,12 @@ public class GLStateManager { } public static void glAlphaFunc(int function, float reference) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordAlphaFunc(function, reference); + if (mode == RecordMode.COMPILE) { + return; + } } if (Iris.enabled) { if (AlphaTestStorage.isAlphaTestLocked()) { @@ -1328,19 +1408,17 @@ public class GLStateManager { alphaState.setFunction(function); alphaState.setReference(reference); } - if (!isRecordingDisplayList()) { - GL11.glAlphaFunc(function, reference); - } + GL11.glAlphaFunc(function, reference); } // Textures public static void glActiveTexture(int texture) { - // Recording mode: record command and update state tracking (only on main thread) - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordActiveTexture(texture); - final int newTexture = texture - GL13.GL_TEXTURE0; - activeTextureUnit.setValue(newTexture); // Update state for glGet queries - return; // Don't execute during recording + if (mode == RecordMode.COMPILE) { + return; + } } final int newTexture = texture - GL13.GL_TEXTURE0; final boolean caching = isCachingEnabled(); @@ -1351,12 +1429,12 @@ public class GLStateManager { } public static void glActiveTextureARB(int texture) { - // Recording mode: record command and update state tracking (only on main thread) - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordActiveTexture(texture); - final int newTexture = texture - GL13.GL_TEXTURE0; - activeTextureUnit.setValue(newTexture); // Update state for glGet queries - return; // Don't execute during recording + if (mode == RecordMode.COMPILE) { + return; + } } final int newTexture = texture - GL13.GL_TEXTURE0; final boolean caching = isCachingEnabled(); @@ -1375,14 +1453,16 @@ public class GLStateManager { } public static void glBindTexture(int target, int texture) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordBindTexture(target, texture); + if (mode == RecordMode.COMPILE) { + return; + } } if (target != GL11.GL_TEXTURE_2D) { // We're only supporting 2D textures for now - if (!isRecordingDisplayList()) { - GL11.glBindTexture(target, texture); - } + GL11.glBindTexture(target, texture); LOGGER.info("SKIPPING glBindTexture for target {}", target); return; } @@ -1397,19 +1477,20 @@ public class GLStateManager { final int cachedBinding = textureUnit.getBinding(); if (cachedBinding != texture) { - if (!isRecordingDisplayList()) { - GL11.glBindTexture(target, texture); - } + GL11.glBindTexture(target, texture); textureUnit.setBinding(texture); TextureTracker.INSTANCE.onBindTexture(texture); } } public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexImage2DCmd.fromIntBuffer(target, level, internalformat, width, height, border, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } - // Always update cache for glGet queries TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture @@ -1421,30 +1502,39 @@ public class GLStateManager { } public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, FloatBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexImage2DCmd.fromFloatBuffer(target, level, internalformat, width, height, border, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } - // Always update cache for glGet queries TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); // FloatBuffer not in DSA interface - use direct GL call GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, DoubleBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexImage2DCmd.fromDoubleBuffer(target, level, internalformat, width, height, border, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } - // Always update cache for glGet queries TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); // DoubleBuffer not in DSA interface - use direct GL call GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexImage2DCmd.fromByteBuffer(target, level, internalformat, width, height, border, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } - // Always update cache for glGet queries TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels != null ? pixels.asIntBuffer() : null); if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - keeps GL binding state unchanged @@ -1559,8 +1649,12 @@ public class GLStateManager { } public static void enableTexture() { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordEnable(GL11.GL_TEXTURE_2D); + if (mode == RecordMode.COMPILE) { + return; + } } final int textureUnit = getActiveTextureUnit(); if (Iris.enabled) { @@ -1582,8 +1676,12 @@ public class GLStateManager { } public static void disableTexture() { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDisable(GL11.GL_TEXTURE_2D); + if (mode == RecordMode.COMPILE) { + return; + } } final int textureUnit = getActiveTextureUnit(); if (Iris.enabled) { @@ -1790,8 +1888,12 @@ public class GLStateManager { } public static void glDrawBuffer(int mode) { - if (DisplayListManager.isRecording()) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordDrawBuffer(mode); + if (recordMode == RecordMode.COMPILE) { + return; + } } trySyncProgram(); GL11.glDrawBuffer(mode); @@ -1866,9 +1968,12 @@ public class GLStateManager { } public static void glLogicOp(int opcode) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLogicOp(opcode); - return; + if (mode == RecordMode.COMPILE) { + return; + } } GL11.glLogicOp(opcode); } @@ -1878,30 +1983,79 @@ public class GLStateManager { } public static void enableCull() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_CULL_FACE); + if (mode == RecordMode.COMPILE) { + return; + } + } cullState.enable(); } public static void disableCull() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_CULL_FACE); + if (mode == RecordMode.COMPILE) { + return; + } + } cullState.disable(); } public static void enableDepthTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_DEPTH_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } depthTest.enable(); } public static void disableDepthTest() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_DEPTH_TEST); + if (mode == RecordMode.COMPILE) { + return; + } + } depthTest.disable(); } public static void enableLighting() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_LIGHTING); + if (mode == RecordMode.COMPILE) { + return; + } + } lightingState.enable(); } public static void enableLight(int light) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_LIGHT0 + light); + if (mode == RecordMode.COMPILE) { + return; + } + } lightStates[light].enable(); } public static void enableColorMaterial() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_COLOR_MATERIAL); + if (mode == RecordMode.COMPILE) { + return; + } + } colorMaterial.enable(); float r = getColor().getRed(); float g = getColor().getGreen(); @@ -1934,26 +2088,68 @@ public class GLStateManager { } public static void disableColorMaterial() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_COLOR_MATERIAL); + if (mode == RecordMode.COMPILE) { + return; + } + } colorMaterial.disable(); } public static void disableLighting() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_LIGHTING); + if (mode == RecordMode.COMPILE) { + return; + } + } lightingState.disable(); } public static void disableLight(int light) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_LIGHT0 + light); + if (mode == RecordMode.COMPILE) { + return; + } + } lightStates[light].disable(); } public static void enableRescaleNormal() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL12.GL_RESCALE_NORMAL); + if (mode == RecordMode.COMPILE) { + return; + } + } rescaleNormalState.enable(); } public static void disableRescaleNormal() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL12.GL_RESCALE_NORMAL); + if (mode == RecordMode.COMPILE) { + return; + } + } rescaleNormalState.disable(); } public static void enableFog() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordEnable(GL11.GL_FOG); + if (mode == RecordMode.COMPILE) { + return; + } + } fogMode.enable(); if (fogToggleListener != null) { fogToggleListener.run(); @@ -1961,6 +2157,13 @@ public class GLStateManager { } public static void disableFog() { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordDisable(GL11.GL_FOG); + if (mode == RecordMode.COMPILE) { + return; + } + } fogMode.disable(); if (fogToggleListener != null) { fogToggleListener.run(); @@ -1968,15 +2171,17 @@ public class GLStateManager { } public static void glFog(int pname, FloatBuffer param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordFog(pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } // TODO: Iris Notifier if (HAS_MULTIPLE_SET.contains(pname)) { - if (!isRecordingDisplayList()) { - GL11.glFog(pname, param); - } - // Only update cached state on main thread + GL11.glFog(pname, param); + if (pname == GL11.GL_FOG_COLOR && isCachingEnabled()) { final float red = param.get(0); final float green = param.get(1); @@ -2016,11 +2221,14 @@ public class GLStateManager { } public static void glFogf(int pname, float param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordFogf(pname, param); - } else { - GL11.glFogf(pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glFogf(pname, param); // Note: Does not handle GL_FOG_INDEX // Only update cached state when caching is enabled if (isCachingEnabled()) { @@ -2048,8 +2256,12 @@ public class GLStateManager { } public static void glFogi(int pname, int param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordFogi(pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } GL11.glFogi(pname, param); // Only update cached state when caching is enabled @@ -2066,9 +2278,12 @@ public class GLStateManager { } public static void glShadeModel(int mode) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordShadeModel(mode); + if (recordMode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); final int oldValue = shadeModelState.getValue(); @@ -2078,9 +2293,7 @@ public class GLStateManager { if (caching) { shadeModelState.setValue(mode); } - if (!isRecordingDisplayList()) { - GL11.glShadeModel(mode); - } + GL11.glShadeModel(mode); } } @@ -2171,7 +2384,7 @@ public class GLStateManager { /** * Get a compiled display list from the cache. - * Used by CallListCmd to execute nested display lists with the unoptimized version. + * Used for executing nested display lists. * @param list The display list ID * @return The CompiledDisplayList, or null if not found */ @@ -2180,7 +2393,9 @@ public class GLStateManager { } public static void glCallList(int list) { + GLDebug.pushGroup("glCallList " + list); DisplayListManager.glCallList(list); + GLDebug.popGroup(); } public static void pushState(int mask) { @@ -2221,82 +2436,93 @@ public class GLStateManager { } public static void glClear(int mask) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordClear(mask); + if (mode == RecordMode.COMPILE) { + return; + } } - // Always execute - clears are immediate operations GL11.glClear(mask); } public static void glPushAttrib(int mask) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordPushAttrib(mask); - } else { - GL11.glPushAttrib(mask); + if (mode == RecordMode.COMPILE) { + return; + } } - // Only track on main thread (splash thread has separate GL context) + GLDebug.pushGroup("pushState"); + GL11.glPushAttrib(mask); if (isCachingEnabled()) { pushState(mask); } } public static void glPopAttrib() { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordPopAttrib(); - } else { - GL11.glPopAttrib(); + if (mode == RecordMode.COMPILE) { + return; + } } - // Only track on main thread (splash thread has separate GL context) + GL11.glPopAttrib(); + GLDebug.popGroup(); if (isCachingEnabled()) { poppingAttributes = true; + GLDebug.pushGroup("popState"); popState(); + GLDebug.popGroup(); poppingAttributes = false; } } // Matrix Operations public static void glMatrixMode(int mode) { - if (DisplayListManager.isRecording()) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordMatrixMode(mode); + DisplayListManager.resetRelativeTransform(); // Mode switch is a barrier - reset delta tracking + if (recordMode == RecordMode.COMPILE) { + return; + } } + GL11.glMatrixMode(mode); matrixMode.setMode(mode); } - /** - * Check if the current matrix mode is MODELVIEW. - * Used by DisplayListManager to determine which transforms to track. - */ - public static boolean isModelViewMatrix() { - return matrixMode.getMode() == GL11.GL_MODELVIEW; - } - public static void glLoadMatrix(FloatBuffer m) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { final Matrix4f matrix = new Matrix4f().set(m); m.rewind(); - DisplayListManager.recordLoadMatrix(matrixMode.getMode(), matrix); - // Reset relative transform for MODELVIEW - subsequent transforms are relative to loaded matrix - if (isModelViewMatrix()) { - DisplayListManager.resetRelativeTransform(); + DisplayListManager.recordLoadMatrix(matrix); + // Reset relative transform - subsequent transforms are relative to loaded matrix + DisplayListManager.resetRelativeTransform(); + if (mode == RecordMode.COMPILE) { + return; } - return; } if (isCachingEnabled()) getMatrixStack().set(m); GL11.glLoadMatrix(m); } public static void glLoadMatrix(DoubleBuffer m) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { // Convert double buffer to float buffer for recording conversionMatrix4d.set(m); m.rewind(); final Matrix4f floatMatrix = new Matrix4f(); floatMatrix.set(conversionMatrix4d); - DisplayListManager.recordLoadMatrix(matrixMode.getMode(), floatMatrix); - // Reset relative transform for MODELVIEW - subsequent transforms are relative to loaded matrix - if (isModelViewMatrix()) { - DisplayListManager.resetRelativeTransform(); + DisplayListManager.recordLoadMatrix(floatMatrix); + // Reset relative transform - subsequent transforms are relative to loaded matrix + DisplayListManager.resetRelativeTransform(); + if (mode == RecordMode.COMPILE) { + return; } - return; } if (isCachingEnabled()) { conversionMatrix4d.set(m); @@ -2321,51 +2547,56 @@ public class GLStateManager { } public static void glLoadIdentity() { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordLoadIdentity(matrixMode.getMode()); - } else { - GL11.glLoadIdentity(); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordLoadIdentity(); + // Reset relative transform - accumulated transforms are discarded (overwritten by load) + DisplayListManager.resetRelativeTransform(); + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glLoadIdentity(); if (isCachingEnabled()) getMatrixStack().identity(); } public static void glTranslatef(float x, float y, float z) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordTranslate(matrixMode.getMode(), x, y, z); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.TRANSLATE, null); - } else { - GL11.glTranslatef(x, y, z); + return; } + GL11.glTranslatef(x, y, z); if (isCachingEnabled()) getMatrixStack().translate(x, y, z); } public static void glTranslated(double x, double y, double z) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordTranslate(matrixMode.getMode(), x, y, z); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.TRANSLATE, null); - } else { - GL11.glTranslated(x, y, z); + return; } + GL11.glTranslated(x, y, z); if (isCachingEnabled()) getMatrixStack().translate((float) x, (float) y, (float) z); } public static void glScalef(float x, float y, float z) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordScale(matrixMode.getMode(), x, y, z); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.SCALE, null); - } else { - GL11.glScalef(x, y, z); + return; } + GL11.glScalef(x, y, z); if (isCachingEnabled()) getMatrixStack().scale(x, y, z); } public static void glScaled(double x, double y, double z) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordScale(matrixMode.getMode(), x, y, z); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.SCALE, null); - } else { - GL11.glScaled(x, y, z); + return; } + GL11.glScaled(x, y, z); if (isCachingEnabled()) getMatrixStack().scale((float) x, (float) y, (float) z); } @@ -2374,17 +2605,12 @@ public class GLStateManager { multMatrix.set(floatBuffer); final int currentMode = matrixMode.getMode(); - if (DisplayListManager.isRecording()) { - // Record with the mode it's being applied to - DisplayListManager.recordMultMatrix(currentMode, multMatrix); - - // Only track if MODELVIEW (for baking into VBO vertices) - if (currentMode == GL11.GL_MODELVIEW) { - DisplayListManager.updateRelativeTransform(multMatrix); - } - } else { - GL11.glMultMatrix(floatBuffer); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.updateRelativeTransform(multMatrix); + return; } + GL11.glMultMatrix(floatBuffer); if (isCachingEnabled()) getMatrixStack().mul(multMatrix); } @@ -2393,91 +2619,73 @@ public class GLStateManager { public static void glMultMatrix(DoubleBuffer matrix) { conversionMatrix4d.set(matrix); conversionMatrix4f.set(conversionMatrix4d); - final int currentMode = matrixMode.getMode(); - if (DisplayListManager.isRecording()) { - // Record with the mode it's being applied to - DisplayListManager.recordMultMatrix(currentMode, conversionMatrix4f); - - // Only track if MODELVIEW (for baking into VBO vertices) - if (currentMode == GL11.GL_MODELVIEW) { - DisplayListManager.updateRelativeTransform(conversionMatrix4f); - } - } else { - GL11.glMultMatrix(matrix); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.updateRelativeTransform(conversionMatrix4f); + return; } + GL11.glMultMatrix(matrix); if (isCachingEnabled()) getMatrixStack().mul(conversionMatrix4f); } private static final Vector3f rotation = new Vector3f(); public static void glRotatef(float angle, float x, float y, float z) { - final boolean recording = DisplayListManager.isRecording(); - final boolean caching = isCachingEnabled(); - - if (recording) { - DisplayListManager.recordRotate(matrixMode.getMode(), angle, x, y, z); - } else { - GL11.glRotatef(angle, x, y, z); - } - - // Compute rotation vector once for relative transform tracking and/or matrix stack - if (recording || caching) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { rotation.set(x, y, z).normalize(); - if (recording) { - DisplayListManager.updateRelativeTransform(angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); - } - if (caching) { - getMatrixStack().rotate((float)Math.toRadians(angle), rotation); - } + DisplayListManager.updateRelativeTransform(angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); + return; + } + GL11.glRotatef(angle, x, y, z); + if (isCachingEnabled()) { + rotation.set(x, y, z).normalize(); + getMatrixStack().rotate((float)Math.toRadians(angle), rotation); } } public static void glRotated(double angle, double x, double y, double z) { - final boolean recording = DisplayListManager.isRecording(); - final boolean caching = isCachingEnabled(); - - if (recording) { - DisplayListManager.recordRotate(matrixMode.getMode(), angle, x, y, z); - } else { - GL11.glRotated(angle, x, y, z); - } - - // Compute rotation vector once for relative transform tracking and/or matrix stack - if (recording || caching) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { rotation.set((float) x, (float) y, (float) z).normalize(); - if (recording) { - DisplayListManager.updateRelativeTransform((float) angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); - } - if (caching) { - getMatrixStack().rotate((float)Math.toRadians(angle), rotation); - } + DisplayListManager.updateRelativeTransform((float) angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); + return; + } + GL11.glRotated(angle, x, y, z); + if (isCachingEnabled()) { + rotation.set((float) x, (float) y, (float) z).normalize(); + getMatrixStack().rotate((float)Math.toRadians(angle), rotation); } } public static void glOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordOrtho(left, right, bottom, top, zNear, zFar); - } else { - GL11.glOrtho(left, right, bottom, top, zNear, zFar); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.updateRelativeTransformOrtho(left, right, bottom, top, zNear, zFar); + return; // Transform accumulated, will be emitted at barriers } + GL11.glOrtho(left, right, bottom, top, zNear, zFar); if (isCachingEnabled()) getMatrixStack().ortho((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); } public static void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordFrustum(left, right, bottom, top, zNear, zFar); - } else { - GL11.glFrustum(left, right, bottom, top, zNear, zFar); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.updateRelativeTransformFrustum(left, right, bottom, top, zNear, zFar); + return; // Transform accumulated, will be emitted at barriers } + GL11.glFrustum(left, right, bottom, top, zNear, zFar); if (isCachingEnabled()) getMatrixStack().frustum((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); } public static void glPushMatrix() { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordPushMatrix(matrixMode.getMode()); - DisplayListManager.pushRelativeTransform(); // Track MODELVIEW transform stack - } else { - GL11.glPushMatrix(); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordPushMatrix(); // Handles flush + relativeTransform stack + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glPushMatrix(); // Only track stack on main thread (splash thread has separate GL context) if (isCachingEnabled()) { try { @@ -2490,12 +2698,14 @@ public class GLStateManager { } public static void glPopMatrix() { - if (DisplayListManager.isRecording()) { - DisplayListManager.recordPopMatrix(matrixMode.getMode()); - DisplayListManager.popRelativeTransform(); // Track MODELVIEW transform stack - } else { - GL11.glPopMatrix(); + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordPopMatrix(); // Handles flush + relativeTransform stack + lastRecordedTransform sync + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glPopMatrix(); // Only track stack on main thread (splash thread has separate GL context) if (isCachingEnabled()) { try { @@ -2517,11 +2727,14 @@ public class GLStateManager { } public static void glViewport(int x, int y, int width, int height) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordViewport(x, y, width, height); - } else { - GL11.glViewport(x, y, width, height); + if (mode == RecordMode.COMPILE) { + return; + } } + GL11.glViewport(x, y, width, height); // Only update cached state when caching is enabled if (isCachingEnabled()) { viewportState.setViewPort(x, y, width, height); @@ -2600,24 +2813,20 @@ public class GLStateManager { } public static void glTexParameteri(int target, int pname, int param) { - // Recording mode: record command but continue to update state tracking - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordTexParameteri(target, pname, param); - // Don't return - fall through to update cache for glGet queries + if (mode == RecordMode.COMPILE) { + return; + } } if (target != GL11.GL_TEXTURE_2D) { - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - GL11.glTexParameteri(target, pname, param); - } + GL11.glTexParameteri(target, pname, param); return; } if (!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, param)) return; - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - GL11.glTexParameteri(target, pname, param); - } + GL11.glTexParameteri(target, pname, param); } @@ -2643,24 +2852,20 @@ public class GLStateManager { } public static void glTexParameterf(int target, int pname, float param) { - // Recording mode: record command but continue to update state tracking - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordTexParameterf(target, pname, param); - // Don't return - fall through to update cache for glGet queries + if (mode == RecordMode.COMPILE) { + return; + } } if (target != GL11.GL_TEXTURE_2D) { - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - GL11.glTexParameterf(target, pname, param); - } + GL11.glTexParameterf(target, pname, param); return; } if (!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, param)) return; - // Skip actual GL call during display list recording (state tracking only) - if (!isRecordingDisplayList()) { - GL11.glTexParameterf(target, pname, param); - } + GL11.glTexParameterf(target, pname, param); } public static int getTexParameterOrDefault(int texture, int pname, IntSupplier defaultSupplier) { @@ -2816,8 +3021,12 @@ public class GLStateManager { } public static void glMaterial(int face, int pname, FloatBuffer params) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordMaterial(face, pname, params); + if (mode == RecordMode.COMPILE) { + return; + } } if (face == GL11.GL_FRONT) { glMaterialFront(pname, params); @@ -2832,6 +3041,21 @@ public class GLStateManager { } public static void glMaterial(int face, int pname, IntBuffer params) { + // For IntBuffer version, we need to convert to float for recording + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + // Convert int params to float for recording + final float[] floatParams = new float[params.remaining()]; + params.mark(); + for (int i = 0; i < floatParams.length; i++) { + floatParams[i] = GLStateManager.i2f(params.get()); + } + params.reset(); + DisplayListManager.recordMaterial(face, pname, java.nio.FloatBuffer.wrap(floatParams)); + if (mode == RecordMode.COMPILE) { + return; + } + } if (face == GL11.GL_FRONT) { glMaterialFront(pname, params); } else if (face == GL11.GL_BACK) { @@ -2842,38 +3066,15 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } - - // Capture already-converted float values from state - // For FRONT_AND_BACK, capture from frontMaterial (both should have same values) - if (DisplayListManager.isRecording()) { - final MaterialStateStack material = (face == GL11.GL_BACK) ? backMaterial : frontMaterial; - final float[] floatParams; - switch (pname) { - case GL11.GL_AMBIENT -> floatParams = new float[] {material.ambient.x, material.ambient.y, material.ambient.z, material.ambient.w}; - case GL11.GL_DIFFUSE -> floatParams = new float[] {material.diffuse.x, material.diffuse.y, material.diffuse.z, material.diffuse.w}; - case GL11.GL_SPECULAR -> floatParams = new float[] {material.specular.x, material.specular.y, material.specular.z, material.specular.w}; - case GL11.GL_EMISSION -> floatParams = new float[] {material.emission.x, material.emission.y, material.emission.z, material.emission.w}; - case GL11.GL_SHININESS -> floatParams = new float[] {material.shininess}; - case GL11.GL_AMBIENT_AND_DIFFUSE -> // For AMBIENT_AND_DIFFUSE, capture ambient (could also use diffuse, they're the same) - floatParams = new float[] {material.ambient.x, material.ambient.y, material.ambient.z, material.ambient.w}; - case GL11.GL_COLOR_INDEXES -> floatParams = new float[] {material.colorIndexes.x, material.colorIndexes.y, material.colorIndexes.z}; - default -> { - // Fallback for unknown pname - do simple cast - floatParams = new float[params.remaining()]; - params.mark(); - for (int i = 0; i < floatParams.length; i++) { - floatParams[i] = params.get(); - } - params.reset(); - } - } - DisplayListManager.recordMaterial(face, pname, java.nio.FloatBuffer.wrap(floatParams)); - } } public static void glMaterialf(int face, int pname, float val) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordMaterialf(face, pname, val); + if (mode == RecordMode.COMPILE) { + return; + } } if (pname != GL11.GL_SHININESS) { // it is only valid to call glMaterialf for the GL_SHININESS parameter @@ -2899,8 +3100,12 @@ public class GLStateManager { } public static void glLight(int light, int pname, FloatBuffer params) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLight(light, pname, params); + if (mode == RecordMode.COMPILE) { + return; + } } final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { @@ -2919,7 +3124,21 @@ public class GLStateManager { } public static void glLight(int light, int pname, IntBuffer params) { - // Call state setter first to convert IntBuffer to float + // For IntBuffer version, we need to convert to float for recording + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + // Convert int params to float for recording + final float[] floatParams = new float[params.remaining()]; + params.mark(); + for (int i = 0; i < floatParams.length; i++) { + floatParams[i] = GLStateManager.i2f(params.get()); + } + params.reset(); + DisplayListManager.recordLight(light, pname, java.nio.FloatBuffer.wrap(floatParams)); + if (mode == RecordMode.COMPILE) { + return; + } + } final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { case GL11.GL_AMBIENT -> lightState.setAmbient(params); @@ -2934,38 +3153,15 @@ public class GLStateManager { case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params); default -> GL11.glLight(light, pname, params); } - - // Capture already-converted float values from state - if (DisplayListManager.isRecording()) { - final float[] floatParams; - switch (pname) { - case GL11.GL_AMBIENT -> floatParams = new float[] {lightState.ambient.x, lightState.ambient.y, lightState.ambient.z, lightState.ambient.w}; - case GL11.GL_DIFFUSE -> floatParams = new float[] {lightState.diffuse.x, lightState.diffuse.y, lightState.diffuse.z, lightState.diffuse.w}; - case GL11.GL_SPECULAR -> floatParams = new float[] {lightState.specular.x, lightState.specular.y, lightState.specular.z, lightState.specular.w}; - case GL11.GL_POSITION -> floatParams = new float[] {lightState.position.x, lightState.position.y, lightState.position.z, lightState.position.w}; - case GL11.GL_SPOT_DIRECTION -> floatParams = new float[] {lightState.spotDirection.x, lightState.spotDirection.y, lightState.spotDirection.z}; - case GL11.GL_SPOT_EXPONENT -> floatParams = new float[] {lightState.spotExponent}; - case GL11.GL_SPOT_CUTOFF -> floatParams = new float[] {lightState.spotCutoff}; - case GL11.GL_CONSTANT_ATTENUATION -> floatParams = new float[] {lightState.constantAttenuation}; - case GL11.GL_LINEAR_ATTENUATION -> floatParams = new float[] {lightState.linearAttenuation}; - case GL11.GL_QUADRATIC_ATTENUATION -> floatParams = new float[] {lightState.quadraticAttenuation}; - default -> { - // Fallback for unknown pname - do simple cast - floatParams = new float[params.remaining()]; - params.mark(); - for (int i = 0; i < floatParams.length; i++) { - floatParams[i] = params.get(); - } - params.reset(); - } - } - DisplayListManager.recordLight(light, pname, java.nio.FloatBuffer.wrap(floatParams)); - } } public static void glLightf(int light, int pname, float param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLightf(light, pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { @@ -2979,8 +3175,12 @@ public class GLStateManager { } public static void glLighti(int light, int pname, int param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLighti(light, pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { @@ -2994,8 +3194,12 @@ public class GLStateManager { } public static void glLightModel(int pname, FloatBuffer params) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLightModel(pname, params); + if (mode == RecordMode.COMPILE) { + return; + } } switch (pname) { case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params); @@ -3005,7 +3209,21 @@ public class GLStateManager { } } public static void glLightModel(int pname, IntBuffer params) { - // Call state setter first to convert IntBuffer to float + // For IntBuffer version, we need to convert to float for recording + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + // Convert int params to float for recording + final float[] floatParams = new float[params.remaining()]; + params.mark(); + for (int i = 0; i < floatParams.length; i++) { + floatParams[i] = GLStateManager.i2f(params.get()); + } + params.reset(); + DisplayListManager.recordLightModel(pname, java.nio.FloatBuffer.wrap(floatParams)); + if (mode == RecordMode.COMPILE) { + return; + } + } switch (pname) { case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params); case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(params); @@ -3013,33 +3231,16 @@ public class GLStateManager { case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params); default -> GL11.glLightModel(pname, params); } - - // Capture already-converted float values from state - if (DisplayListManager.isRecording()) { - final float[] floatParams; - switch (pname) { - case GL11.GL_LIGHT_MODEL_AMBIENT -> floatParams = new float[] {lightModel.ambient.x, lightModel.ambient.y, lightModel.ambient.z, lightModel.ambient.w}; - case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> floatParams = new float[] {(float) lightModel.colorControl}; - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> floatParams = new float[] {lightModel.localViewer}; - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> floatParams = new float[] {lightModel.twoSide}; - default -> { - // Fallback for unknown pname - do simple cast - floatParams = new float[params.remaining()]; - params.mark(); - for (int i = 0; i < floatParams.length; i++) { - floatParams[i] = params.get(); - } - params.reset(); - } - } - DisplayListManager.recordLightModel(pname, java.nio.FloatBuffer.wrap(floatParams)); - } } public static void glLightModelf(int pname, float param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLightModelf(pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } - // Only update cached state on main thread + if (isCachingEnabled()) { switch (pname) { case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param); @@ -3051,10 +3252,14 @@ public class GLStateManager { } } public static void glLightModeli(int pname, int param) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLightModeli(pname, param); + if (mode == RecordMode.COMPILE) { + return; + } } - // Only update cached state on main thread + if (isCachingEnabled()) { switch (pname) { case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(param); @@ -3068,8 +3273,12 @@ public class GLStateManager { } public static void glColorMaterial(int face, int mode) { - if (DisplayListManager.isRecording()) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordColorMaterial(face, mode); + if (recordMode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || colorMaterialFace.getValue() != face || colorMaterialParameter.getValue() != mode) { @@ -3086,9 +3295,12 @@ public class GLStateManager { } public static void glUseProgram(int program) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordUseProgram(program); - return; + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || program != activeProgram) { @@ -3126,25 +3338,30 @@ public class GLStateManager { } public static void glLineWidth(float width) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLineWidth(width); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || lineState.getWidth() != width) { if (caching) { lineState.setWidth(width); } - if (!recording) { - GL11.glLineWidth(width); - } + GL11.glLineWidth(width); } } // Texture commands public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromByteBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - keeps GL binding state unchanged @@ -3156,8 +3373,12 @@ public class GLStateManager { } public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromIntBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels)); + if (mode == RecordMode.COMPILE) { + return; + } } if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture @@ -3219,9 +3440,12 @@ public class GLStateManager { // State commands public static void glCullFace(int mode) { - if (DisplayListManager.isRecording()) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordCullFace(mode); - return; + if (recordMode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || polygonState.getCullFaceMode() != mode) { @@ -3233,9 +3457,12 @@ public class GLStateManager { } public static void glFrontFace(int mode) { - if (DisplayListManager.isRecording()) { + final RecordMode recordMode = DisplayListManager.getRecordMode(); + if (recordMode != RecordMode.NONE) { DisplayListManager.recordFrontFace(mode); - return; + if (recordMode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || polygonState.getFrontFace() != mode) { @@ -3246,21 +3473,24 @@ public class GLStateManager { } } - public static void glHint(int target, int mode) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { - DisplayListManager.recordHint(target, mode); - if (DisplayListManager.getListMode() == GL11.GL_COMPILE) { + public static void glHint(int target, int hint) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordHint(target, hint); + if (mode == RecordMode.COMPILE) { return; } } - GL11.glHint(target, mode); + GL11.glHint(target, hint); } public static void glLineStipple(int factor, short pattern) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordLineStipple(factor, pattern); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || lineState.getStippleFactor() != factor || lineState.getStipplePattern() != pattern) { @@ -3268,57 +3498,62 @@ public class GLStateManager { lineState.setStippleFactor(factor); lineState.setStipplePattern(pattern); } - if (!recording) { - GL11.glLineStipple(factor, pattern); - } + GL11.glLineStipple(factor, pattern); } } public static void glPointSize(float size) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordPointSize(size); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || pointState.getSize() != size) { if (caching) { pointState.setSize(size); } - if (!recording) { - GL11.glPointSize(size); - } + GL11.glPointSize(size); } } - public static void glPolygonMode(int face, int mode) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { - DisplayListManager.recordPolygonMode(face, mode); + public static void glPolygonMode(int face, int polygonMode) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { + DisplayListManager.recordPolygonMode(face, polygonMode); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); final boolean needsUpdate; if (face == GL11.GL_FRONT) { - needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != mode; - if (caching && needsUpdate) polygonState.setFrontMode(mode); + needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode; + if (caching && needsUpdate) polygonState.setFrontMode(polygonMode); } else if (face == GL11.GL_BACK) { - needsUpdate = BYPASS_CACHE || !caching || polygonState.getBackMode() != mode; - if (caching && needsUpdate) polygonState.setBackMode(mode); + needsUpdate = BYPASS_CACHE || !caching || polygonState.getBackMode() != polygonMode; + if (caching && needsUpdate) polygonState.setBackMode(polygonMode); } else { // GL_FRONT_AND_BACK - needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != mode || polygonState.getBackMode() != mode; + needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode || polygonState.getBackMode() != polygonMode; if (caching && needsUpdate) { - polygonState.setFrontMode(mode); - polygonState.setBackMode(mode); + polygonState.setFrontMode(polygonMode); + polygonState.setBackMode(polygonMode); } } - if (needsUpdate && !recording) { - GL11.glPolygonMode(face, mode); + if (needsUpdate) { + GL11.glPolygonMode(face, polygonMode); } } public static void glPolygonOffset(float factor, float units) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordPolygonOffset(factor, units); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || polygonState.getOffsetFactor() != factor || polygonState.getOffsetUnits() != units) { @@ -3326,9 +3561,7 @@ public class GLStateManager { polygonState.setOffsetFactor(factor); polygonState.setOffsetUnits(units); } - if (!recording) { - GL11.glPolygonOffset(factor, units); - } + GL11.glPolygonOffset(factor, units); } } @@ -3347,50 +3580,53 @@ public class GLStateManager { } public static void glStencilFunc(int func, int ref, int mask) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilFunc(func, ref, mask); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != mask) { if (caching) { stencilState.setFunc(func, ref, mask); } - if (!recording) { - GL11.glStencilFunc(func, ref, mask); - } + GL11.glStencilFunc(func, ref, mask); } } public static void glStencilMask(int mask) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilMask(mask); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || stencilState.getWriteMaskFront() != mask) { if (caching) { stencilState.setWriteMask(mask); } - if (!recording) { - GL11.glStencilMask(mask); - } + GL11.glStencilMask(mask); } } public static void glStencilOp(int fail, int zfail, int zpass) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilOp(fail, zfail, zpass); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || stencilState.getFailOpFront() != fail || stencilState.getZFailOpFront() != zfail || stencilState.getZPassOpFront() != zpass) { if (caching) { stencilState.setOp(fail, zfail, zpass); } - if (!recording) { - GL11.glStencilOp(fail, zfail, zpass); - } + GL11.glStencilOp(fail, zfail, zpass); } } @@ -3440,32 +3676,41 @@ public class GLStateManager { // Clear Commands public static void glClearStencil(int s) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordClearStencil(s); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || stencilState.getClearValue() != s) { if (caching) { stencilState.setClearValue(s); } - if (!recording) { - GL11.glClearStencil(s); - } + GL11.glClearStencil(s); } } // Draw Buffer Commands (GL 2.0+) public static void glDrawBuffers(int buffer) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDrawBuffers(1, buffer); + if (mode == RecordMode.COMPILE) { + return; + } } GL20.glDrawBuffers(buffer); } public static void glDrawBuffers(IntBuffer bufs) { - if (DisplayListManager.isRecording()) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordDrawBuffers(bufs.remaining(), bufs); + if (mode == RecordMode.COMPILE) { + return; + } } GL20.glDrawBuffers(bufs); } @@ -3480,9 +3725,12 @@ public class GLStateManager { // Stencil Separate Functions (GL 2.0+) public static void glStencilFuncSeparate(int face, int func, int ref, int mask) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilFuncSeparate(face, func, ref, mask); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); boolean needsUpdate = BYPASS_CACHE || !caching; @@ -3507,16 +3755,17 @@ public class GLStateManager { stencilState.setValueMaskBack(mask); } } - if (!recording) { - GL20.glStencilFuncSeparate(face, func, ref, mask); - } + GL20.glStencilFuncSeparate(face, func, ref, mask); } } public static void glStencilMaskSeparate(int face, int mask) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilMaskSeparate(face, mask); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); boolean needsUpdate = BYPASS_CACHE || !caching; @@ -3537,16 +3786,17 @@ public class GLStateManager { stencilState.setWriteMaskBack(mask); } } - if (!recording) { - GL20.glStencilMaskSeparate(face, mask); - } + GL20.glStencilMaskSeparate(face, mask); } } public static void glStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { + final RecordMode mode = DisplayListManager.getRecordMode(); + if (mode != RecordMode.NONE) { DisplayListManager.recordStencilOpSeparate(face, sfail, dpfail, dppass); + if (mode == RecordMode.COMPILE) { + return; + } } final boolean caching = isCachingEnabled(); boolean needsUpdate = BYPASS_CACHE || !caching; @@ -3571,9 +3821,7 @@ public class GLStateManager { stencilState.setZPassOpBack(dppass); } } - if (!recording) { - GL20.glStencilOpSeparate(face, sfail, dpfail, dppass); - } + GL20.glStencilOpSeparate(face, sfail, dpfail, dppass); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java index 124f7ae84..3228fbdbe 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/LineBuffer.java @@ -41,6 +41,7 @@ class LineBuffer { private int pendingVertexCount = 0; private Matrix4f pendingTransform = null; private int pendingCommandIndex = -1; + private int pendingStateGen = -1; /** * Add a line draw to this buffer. @@ -52,8 +53,14 @@ class LineBuffer { // Always track per-draw range for unoptimized path perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex)); - // Merge logic for optimized path - if (pendingTransform != null && pendingTransform.equals(draw.transform)) { + // 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 { @@ -65,6 +72,7 @@ class LineBuffer { pendingVertexCount = vertexCount; pendingTransform = new Matrix4f(draw.transform); pendingCommandIndex = draw.commandIndex; + pendingStateGen = draw.stateGeneration; } allVertices.addAll(draw.lines); @@ -75,6 +83,7 @@ class LineBuffer { if (pendingTransform != null) { mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex)); pendingTransform = null; + pendingStateGen = -1; } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java index a138cace8..5e2c64500 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java @@ -40,6 +40,7 @@ class TessellatorPrimitiveBuffer { private int pendingLineVertexCount = 0; private Matrix4f pendingLineTransform = null; private int pendingLineCommandIndex = -1; + private int pendingLineStateGen = -1; // Ranges for triangles final List triangleMergedRanges = new ArrayList<>(); @@ -49,6 +50,7 @@ class TessellatorPrimitiveBuffer { private int pendingTriangleVertexCount = 0; private Matrix4f pendingTriangleTransform = null; private int pendingTriangleCommandIndex = -1; + private int pendingTriangleStateGen = -1; TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) { this.flags = flags; @@ -81,8 +83,14 @@ class TessellatorPrimitiveBuffer { final int lineVertexCount = lineCount * 2; // 2 vertices per line linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex)); - // Merge logic for optimized path - if (pendingLineTransform != null && pendingLineTransform.equals(draw.transform)) { + // 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(); @@ -90,6 +98,7 @@ class TessellatorPrimitiveBuffer { pendingLineVertexCount = lineVertexCount; pendingLineTransform = new Matrix4f(draw.transform); pendingLineCommandIndex = draw.commandIndex; + pendingLineStateGen = draw.stateGeneration; } currentLineVertexOffset += lineVertexCount; } @@ -99,8 +108,14 @@ class TessellatorPrimitiveBuffer { final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex)); - // Merge logic for optimized path - if (pendingTriangleTransform != null && pendingTriangleTransform.equals(draw.transform)) { + // 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(); @@ -108,6 +123,7 @@ class TessellatorPrimitiveBuffer { pendingTriangleVertexCount = triangleVertexCount; pendingTriangleTransform = new Matrix4f(draw.transform); pendingTriangleCommandIndex = draw.commandIndex; + pendingTriangleStateGen = draw.stateGeneration; } currentTriangleVertexOffset += triangleVertexCount; } @@ -117,6 +133,7 @@ class TessellatorPrimitiveBuffer { if (pendingLineTransform != null) { lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex)); pendingLineTransform = null; + pendingLineStateGen = -1; } } @@ -124,6 +141,7 @@ class TessellatorPrimitiveBuffer { if (pendingTriangleTransform != null) { triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex)); pendingTriangleTransform = null; + pendingTriangleStateGen = -1; } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/TransformOptimizer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/TransformOptimizer.java index 1fef31607..de91a3bf0 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/TransformOptimizer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/TransformOptimizer.java @@ -5,14 +5,13 @@ import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; /** - * Helper class for tracking and collapsing MODELVIEW transforms during optimization. + * Helper class for tracking and collapsing matrix transforms during optimization. * Implements the transform accumulation and emission strategy: *
    *
  • accumulated: total relative transform (what GL matrix should be)
  • @@ -100,11 +99,11 @@ class TransformOptimizer { // But for simplicity, if lastEmitted is identity, just emit target if (DisplayListManager.isIdentity(lastEmitted)) { // Simple case: just emit target - output.add(MultMatrixCmd.create(target, GL11.GL_MODELVIEW)); + output.add(MultMatrixCmd.create(target)); } else { // Need to emit delta: inv(lastEmitted) * target final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target); - output.add(MultMatrixCmd.create(delta, GL11.GL_MODELVIEW)); + output.add(MultMatrixCmd.create(delta)); } lastEmitted.set(target); } @@ -126,7 +125,7 @@ class TransformOptimizer { /** * Check if the GL matrix is at an absolute value and clear the flag. - * Used by LoadIdentityCmd to determine if it needs to emit. + * Used to determine if LoadIdentity needs to emit. * @return true if LoadMatrix was called and not yet reset by LoadIdentity */ boolean checkAndClearAbsoluteMatrix() { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/debug/OpenGLDebugging.java b/src/main/java/com/gtnewhorizons/angelica/glsm/debug/OpenGLDebugging.java index 4810bae88..18c0790f5 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/debug/OpenGLDebugging.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/debug/OpenGLDebugging.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm.debug; +import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; import net.minecraft.client.Minecraft; @@ -23,7 +24,9 @@ import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.function.Consumer; // Adapted from https://github.com/makamys/CoreTweaks/blob/master/src/main/java/makamys/coretweaks/util/OpenGLDebugging.java; @@ -34,6 +37,7 @@ public class OpenGLDebugging { public static final Logger LOGGER = LogManager.getLogger("gldumper"); private static final Consumer LINE_LOGGER = LOGGER::debug; + private static final Set seenErrors = new HashSet<>(); public static final String GL_IS_ENABLED = "glIsEnabled()"; public static final String GL_GET_BOOLEANV = "glGetBooleanv()"; public static final String GL_GET_INTEGERV = "glGetIntegerv()"; @@ -455,49 +459,195 @@ public class OpenGLDebugging { } public static String getGLSMErrorLog() { - StringBuilder error = new StringBuilder(); + return getGLSMErrorLog(null, false, false); + } + + // Re-entrancy guard - getGLSMErrorLog calls glActiveTexture which could trigger checkGLSMOnce + private static boolean inCheck = false; + + /** + * Enhanced GLSM error logging with context, stack trace, and first-occurrence filtering. + * + * @param context Optional context string to include in error messages (e.g., "During rendering") + * @param logStacktrace If true, includes the current stack trace in the error output + * @param onlyFirstOccurrence If true, only logs each unique error once + * @return Error log string if mismatches found, null otherwise + */ + public static String getGLSMErrorLog(String context, boolean logStacktrace, boolean onlyFirstOccurrence) { + if (inCheck) return null; + if (!GLStateManager.isCachingEnabled() || GLStateManager.isRecordingDisplayList()) { + return null; + } + inCheck = true; + try { + String group = "checkGLSM" + (context == null ? "" : " " + context); + GLDebug.pushGroup(group); + final StringBuilder error = new StringBuilder(); boolean mismatch = false; + + if (context != null && !context.isEmpty()) { + error.append("[").append(context).append("] "); + } + for (int i = 0; i < instance.propertyList.length; ++i) { final GLproperty gLProperty = instance.propertyList[i]; if (gLProperty.fetchCommand.equals(GL_GET_FLOATV) && gLProperty.name.endsWith("_MATRIX")) { final Matrix4f cached = gLProperty.getAsMatrix4f(true); final Matrix4f uncached = gLProperty.getAsMatrix4f(false); - // Some precision issues due to RAD vs degrees, and translated (vs f) - if (!cached.equals(uncached, 0.001f)) { - LOGGER.error("GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached); - mismatch = true; + + // Skip comparison if either matrix is degenerate (contains NaN/Infinity) these represent invalid GL state from bad parameters, not cache bugs + if (isMatrixDegenerate(cached) || isMatrixDegenerate(uncached)) continue; + + if (!matricesEquivalent(cached, uncached, 0.001f)) { + final String errorKey = "MATRIX:" + gLProperty.name; + if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { + final String errorMsg = "GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached; + LOGGER.error(errorMsg); + error.append(errorMsg).append('\n'); + mismatch = true; + } } } else { final String cached = gLProperty.getAsString(true); final String uncached = gLProperty.getAsString(false); if (!cached.equals(uncached)) { - error.append("GLSM mismatch: " + gLProperty.name + " cached: " + cached + " uncached: " + uncached); - error.append('\n'); + final String errorKey = "PROPERTY:" + gLProperty.name + ":" + cached + ":" + uncached; + if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { + error.append("GLSM mismatch: ").append(gLProperty.name).append(" cached: ").append(cached).append(" uncached: ").append(uncached); + error.append('\n'); + mismatch = true; + } + } + } + } + + final TextureUnitArray textureUnits = GLStateManager.getTextures(); + final int currentActiveTexture = GLStateManager.getActiveTextureUnit(); + + // Check GL_ACTIVE_TEXTURE + final int glActiveUnit = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0; + if (glActiveUnit != currentActiveTexture) { + final String errorKey = "ACTIVE_TEXTURE:" + currentActiveTexture + ":" + glActiveUnit; + if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { + error.append("GLSM mismatch: GL_ACTIVE_TEXTURE cached: ").append(currentActiveTexture) + .append(" uncached: ").append(glActiveUnit).append('\n'); + mismatch = true; + } + } + + // Check per-unit texture state + for (int i = 0; i < textureUnits.textureMatricies.length; i++) { + GL13.glActiveTexture(GL13.GL_TEXTURE0 + i); + + // Check GL_TEXTURE_2D enabled + final boolean cachedEnabled = textureUnits.getTextureUnitStates(i).isEnabled(); + final boolean uncachedEnabled = GL11.glIsEnabled(GL11.GL_TEXTURE_2D); + if (cachedEnabled != uncachedEnabled) { + final String errorKey = "TEXTURE_2D:" + i + ":" + cachedEnabled + ":" + uncachedEnabled; + if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { + error.append("GLSM mismatch: GL_TEXTURE_2D cached: ").append(cachedEnabled) + .append(" uncached: ").append(uncachedEnabled) + .append(", texture unit: GL_TEXTURE").append(i).append('\n'); + mismatch = true; + } + } + + // Check GL_TEXTURE_BINDING_2D + final int cachedBinding = textureUnits.getTextureUnitBindings(i).getBinding(); + final int uncachedBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + if (cachedBinding != uncachedBinding) { + final String errorKey = "TEXTURE_BINDING_2D:" + i + ":" + cachedBinding + ":" + uncachedBinding; + if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { + error.append("GLSM mismatch: GL_TEXTURE_BINDING_2D cached: ").append(cachedBinding) + .append(" uncached: ").append(uncachedBinding) + .append(", texture unit: GL_TEXTURE").append(i).append('\n'); mismatch = true; } } } - final TextureUnitArray textureUnits = GLStateManager.getTextures(); - int currentActiveTexture = GLStateManager.getActiveTextureUnit(); - for (int i = 0; i < textureUnits.textureMatricies.length; i++) { - GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); - final boolean cached = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D); - final boolean uncached = GL11.glIsEnabled(GL11.GL_TEXTURE_2D); - if (cached != uncached) { - error.append("GLSM mismatch: " + "GL_TEXTURE_2D" + " cached: " + cached + " uncached: " + uncached + ", texture unit: GL_TEXTURE" + i); - error.append('\n'); - mismatch = true; + GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture); + + // Add stack trace if requested + if (mismatch && logStacktrace) { + error.append("\nStack trace:\n"); + final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); + for (int i = 2; i < stackTrace.length; i++) { + error.append(" at ").append(stackTrace[i].toString()).append('\n'); } } - GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture); - if (!mismatch) { - return null; + GLDebug.popGroup(); + + return mismatch ? error.toString() : null; + } finally { + inCheck = false; } - return error.toString(); + } + + public static boolean checkGLSMOnce(String context) { + final String output = getGLSMErrorLog(context, true, true); + + if (output != null) { + // Only log on actual mismatch + LOGGER.error("[{}] MISMATCH thread={}\n{}", context, Thread.currentThread().getName(), output); + return false; + } + return true; + } + + /** + * Check if a matrix contains any non-finite values (NaN or Infinity). + * Such matrices represent invalid/degenerate GL state (e.g., zero near/far in projection). + */ + private static boolean isMatrixDegenerate(Matrix4f matrix) { + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + if (!Float.isFinite(matrix.get(col, row))) { + return true; + } + } + } + return false; + } + + /** + * Compare two matrices with tolerance for NaN/Infinity. + * Treats NaN == NaN and Infinity == Infinity as equal (both are degenerate states). + * For finite values, uses epsilon comparison. + */ + private static boolean matricesEquivalent(Matrix4f a, Matrix4f b, float epsilon) { + // Compare all 16 elements + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + final float aVal = a.get(col, row); + final float bVal = b.get(col, row); + + // If both are non-finite (NaN or Infinity), consider them equal + if (!Float.isFinite(aVal) && !Float.isFinite(bVal)) { + // Both non-finite: check if both NaN or both same Infinity + if (Float.isNaN(aVal) && Float.isNaN(bVal)) continue; + if (Float.isInfinite(aVal) && Float.isInfinite(bVal)) { + // Check same sign of infinity + if ((aVal > 0) == (bVal > 0)) continue; + } + return false; // Different non-finite values + } + + // If one is finite and other is not, they differ + if (Float.isFinite(aVal) != Float.isFinite(bVal)) { + return false; + } + + // Both finite: use epsilon comparison + if (Math.abs(aVal - bVal) > epsilon) { + return false; + } + } + } + return true; } public static void checkGLSM() { - String output = getGLSMErrorLog(); + final String output = getGLSMErrorLog(); if (output == null) { LOGGER.info("GLSM state matches!"); @@ -507,7 +657,7 @@ public class OpenGLDebugging { } public static void copyTexture(ResourceLocation resource, File output) { - Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource); + final Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource); if (object != null) { copyTexture(((ITextureObject) object).getGlTextureId(), output); 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 2a7a07d57..b028b4db3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedDraw.java @@ -1,5 +1,6 @@ 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; @@ -17,19 +18,49 @@ public class AccumulatedDraw { public final Matrix4f transform; public final CapturingTessellator.Flags flags; 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 AccumulatedDraw(List quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { + /** + * Last vertex restoration data for immediate mode draws. + * Null for tessellator draws (no restoration needed). + */ + public final RestoreData restoreData; + + /** + * 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 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, flags=C%dT%dL%dN%d]", - quads.size(), commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); + 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"); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java index 1a7e816dd..f3c80a0ab 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedLineDraw.java @@ -16,13 +16,19 @@ public class AccumulatedLineDraw { 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 diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java index 6ee4fae2f..8d29bb58e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java @@ -21,13 +21,21 @@ public class AccumulatedPrimitiveDraw { 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) { + 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; } /** @@ -50,8 +58,8 @@ public class AccumulatedPrimitiveDraw { @Override public String toString() { - return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, mode=%d, flags=C%dT%dL%dN%d]", - primitives.size(), commandIndex, flags.drawMode, + 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 190fe33d5..1405242b5 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java @@ -14,6 +14,12 @@ 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; @@ -137,22 +143,19 @@ public final class CommandBuffer { writeInt(0); // unused padding } - public void writeLoadIdentity(int matrixMode) { - ensureCapacity(8); + public void writeLoadIdentity() { + ensureCapacity(4); writeInt(GLCommand.LOAD_IDENTITY); - writeInt(matrixMode); } - public void writePushMatrix(int matrixMode) { - ensureCapacity(8); + public void writePushMatrix() { + ensureCapacity(4); writeInt(GLCommand.PUSH_MATRIX); - writeInt(matrixMode); } - public void writePopMatrix(int matrixMode) { - ensureCapacity(8); + public void writePopMatrix() { + ensureCapacity(4); writeInt(GLCommand.POP_MATRIX); - writeInt(matrixMode); } public void writeStencilMask(int mask) { @@ -415,29 +418,26 @@ public final class CommandBuffer { // === Double commands === - public void writeTranslate(int matrixMode, double x, double y, double z) { - ensureCapacity(32); + public void writeTranslate(double x, double y, double z) { + ensureCapacity(28); writeInt(GLCommand.TRANSLATE); - writeInt(matrixMode); writeDouble(x); writeDouble(y); writeDouble(z); } - public void writeRotate(int matrixMode, double angle, double x, double y, double z) { - ensureCapacity(40); + public void writeRotate(double angle, double x, double y, double z) { + ensureCapacity(36); writeInt(GLCommand.ROTATE); - writeInt(matrixMode); writeDouble(angle); writeDouble(x); writeDouble(y); writeDouble(z); } - public void writeScale(int matrixMode, double x, double y, double z) { - ensureCapacity(32); + public void writeScale(double x, double y, double z) { + ensureCapacity(28); writeInt(GLCommand.SCALE); - writeInt(matrixMode); writeDouble(x); writeDouble(y); writeDouble(z); @@ -467,17 +467,15 @@ public final class CommandBuffer { // === Matrix commands === - public void writeMultMatrix(int matrixMode, Matrix4f matrix) { - ensureCapacity(72); + public void writeMultMatrix(Matrix4f matrix) { + ensureCapacity(68); writeInt(GLCommand.MULT_MATRIX); - writeInt(matrixMode); writeMatrix4f(matrix); } - public void writeLoadMatrix(int matrixMode, Matrix4f matrix) { - ensureCapacity(72); + public void writeLoadMatrix(Matrix4f matrix) { + ensureCapacity(68); writeInt(GLCommand.LOAD_MATRIX); - writeInt(matrixMode); writeMatrix4f(matrix); } @@ -559,6 +557,58 @@ public final class CommandBuffer { writeInt(hasBrightness ? 1 : 0); } + /** + * Write a DRAW_RANGE_RESTORE command that draws a VBO range and restores GL current state after. + * 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 + ) { + ensureCapacity(56); + 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); + // Last texcoord (2 floats = 8 bytes) + writeFloat(lastTexS); + writeFloat(lastTexT); + } + public void writeCallList(int listId) { ensureCapacity(8); writeInt(GLCommand.CALL_LIST); 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 5e074ec3b..a24dafec5 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java @@ -11,6 +11,7 @@ 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 @@ -96,28 +97,13 @@ public final class CommandBufferExecutor { ptr += 4; // Skip unused padding } case GLCommand.LOAD_IDENTITY -> { - final int mode = memGetInt(ptr); - ptr += 4; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); GLStateManager.glLoadIdentity(); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.PUSH_MATRIX -> { - final int mode = memGetInt(ptr); - ptr += 4; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); GLStateManager.glPushMatrix(); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.POP_MATRIX -> { - final int mode = memGetInt(ptr); - ptr += 4; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); GLStateManager.glPopMatrix(); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.STENCIL_MASK -> { GLStateManager.glStencilMask(memGetInt(ptr)); @@ -346,38 +332,26 @@ public final class CommandBufferExecutor { // === Double commands === case GLCommand.TRANSLATE -> { - final int mode = memGetInt(ptr); - final double x = memGetDouble(ptr + 4); - final double y = memGetDouble(ptr + 12); - final double z = memGetDouble(ptr + 20); - ptr += 28; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); + final double x = memGetDouble(ptr); + final double y = memGetDouble(ptr + 8); + final double z = memGetDouble(ptr + 16); + ptr += 24; GLStateManager.glTranslated(x, y, z); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.ROTATE -> { - final int mode = memGetInt(ptr); - final double angle = memGetDouble(ptr + 4); - final double x = memGetDouble(ptr + 12); - final double y = memGetDouble(ptr + 20); - final double z = memGetDouble(ptr + 28); - ptr += 36; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); + final double angle = memGetDouble(ptr); + final double x = memGetDouble(ptr + 8); + final double y = memGetDouble(ptr + 16); + final double z = memGetDouble(ptr + 24); + ptr += 32; GLStateManager.glRotated(angle, x, y, z); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.SCALE -> { - final int mode = memGetInt(ptr); - final double x = memGetDouble(ptr + 4); - final double y = memGetDouble(ptr + 12); - final double z = memGetDouble(ptr + 20); - ptr += 28; - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); + final double x = memGetDouble(ptr); + final double y = memGetDouble(ptr + 8); + final double z = memGetDouble(ptr + 16); + ptr += 24; GLStateManager.glScaled(x, y, z); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.ORTHO -> { final double left = memGetDouble(ptr); @@ -402,32 +376,23 @@ public final class CommandBufferExecutor { // === Matrix commands === case GLCommand.MULT_MATRIX -> { - final int mode = memGetInt(ptr); - ptr += 4; + // Mode-agnostic: just multiply current matrix MATRIX_BUFFER.clear(); for (int i = 0; i < 16; i++) { MATRIX_BUFFER.put(memGetFloat(ptr)); ptr += 4; } MATRIX_BUFFER.flip(); - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); GLStateManager.glMultMatrix(MATRIX_BUFFER); - GLStateManager.glMatrixMode(savedMode); } case GLCommand.LOAD_MATRIX -> { - final int mode = memGetInt(ptr); - ptr += 4; MATRIX_BUFFER.clear(); for (int i = 0; i < 16; i++) { MATRIX_BUFFER.put(memGetFloat(ptr)); ptr += 4; } MATRIX_BUFFER.flip(); - final int savedMode = GLStateManager.getMatrixMode().getMode(); - GLStateManager.glMatrixMode(mode); GLStateManager.glLoadMatrix(MATRIX_BUFFER); - GLStateManager.glMatrixMode(savedMode); } // === Buffer commands === @@ -494,6 +459,40 @@ public final class CommandBufferExecutor { vbo.draw(start, count); vbo.cleanupState(); } + 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); + + // Draw the VBO + final VertexBuffer vbo = ownedVbos[vboIndex]; + vbo.setupState(); + vbo.draw(start, count); + vbo.cleanupState(); + + // 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 & FLAG_HAS_NORMALS) != 0) { + final float nx = memGetFloat(ptr + 32); + final float ny = memGetFloat(ptr + 36); + final float nz = memGetFloat(ptr + 40); + GLStateManager.glNormal3f(nx, ny, nz); + } + if ((flags & FLAG_HAS_TEXTURE) != 0) { + final float s = memGetFloat(ptr + 44); + final float t = memGetFloat(ptr + 48); + GLStateManager.glTexCoord2f(s, t); + } + ptr += 52; // Skip full command size (56 - 4 for cmd already read) + } case GLCommand.CALL_LIST -> { final int listId = memGetInt(ptr); ptr += 4; 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 4a5a33dcc..f2453f762 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java @@ -19,92 +19,53 @@ public final class CommandBufferProcessor { public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) { switch (opcode) { - // === MODELVIEW matrix commands - accumulate instead of copying === - case GLCommand.TRANSLATE -> { - final int mode = raw.readInt(); - final double x = raw.readDouble(); - final double y = raw.readDouble(); - final double z = raw.readDouble(); - if (mode == GL11.GL_MODELVIEW) { - opt.translate(x, y, z); - } else { - out.writeTranslate(mode, x, y, z); - } - } - case GLCommand.ROTATE -> { - final int mode = raw.readInt(); - final double angle = raw.readDouble(); - final double x = raw.readDouble(); - final double y = raw.readDouble(); - final double z = raw.readDouble(); - if (mode == GL11.GL_MODELVIEW) { - opt.rotate(angle, x, y, z); - } else { - out.writeRotate(mode, angle, x, y, z); - } - } - case GLCommand.SCALE -> { - final int mode = raw.readInt(); - final double x = raw.readDouble(); - final double y = raw.readDouble(); - final double z = raw.readDouble(); - if (mode == GL11.GL_MODELVIEW) { - opt.scale(x, y, z); - } else { - out.writeScale(mode, x, y, z); - } - } + // === MultMatrix - already collapsed transforms from flushMatrix() === case GLCommand.MULT_MATRIX -> { - final int mode = raw.readInt(); raw.readMatrix4f(tempMatrix); - if (mode == GL11.GL_MODELVIEW) { - opt.multMatrix(tempMatrix); - } else { - out.writeMultMatrix(mode, tempMatrix); - } - } - case GLCommand.LOAD_IDENTITY -> { - final int mode = raw.readInt(); - if (mode == GL11.GL_MODELVIEW) { - if (opt.checkAndClearAbsoluteMatrix()) { - out.writeLoadIdentity(mode); - } - opt.loadIdentity(); - } else { - out.writeLoadIdentity(mode); - } - } - case GLCommand.LOAD_MATRIX -> { - final int mode = raw.readInt(); - raw.readMatrix4f(tempMatrix); - if (mode == GL11.GL_MODELVIEW) { - opt.emitPendingTransform(out); - out.writeLoadMatrix(mode, tempMatrix); - opt.loadIdentity(); - opt.markAbsoluteMatrix(); - } else { - out.writeLoadMatrix(mode, tempMatrix); - } + opt.multMatrix(tempMatrix); // accumulated = accumulated * tempMatrix + out.writeMultMatrix(tempMatrix); // Copy to output + opt.markLastEmittedAsAccumulated(); // lastEmitted = accumulated (what GL now has) } - // === Stack operations - update optimizer state and copy === + // === 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 -> { - final int mode = raw.readInt(); - if (mode == GL11.GL_MODELVIEW) { - opt.emitPendingTransform(out); - opt.push(); - } - out.writePushMatrix(mode); + opt.emitPendingTransform(out); + opt.push(); + // Reset accumulated/lastEmitted to identity after push. + opt.loadIdentity(); + opt.resetLastEmitted(); + out.writePushMatrix(); } case GLCommand.POP_MATRIX -> { - final int mode = raw.readInt(); - if (mode == GL11.GL_MODELVIEW) { - opt.pop(); - } - out.writePopMatrix(mode); + 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); @@ -150,9 +111,9 @@ public final class CommandBufferProcessor { case GLCommand.USE_PROGRAM -> out.writeUseProgram(raw.readInt()); case GLCommand.PUSH_ATTRIB -> out.writePushAttrib(raw.readInt()); case GLCommand.POP_ATTRIB -> { raw.readInt(); out.writePopAttrib(); } - case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity(raw.readInt()); - case GLCommand.PUSH_MATRIX -> out.writePushMatrix(raw.readInt()); - case GLCommand.POP_MATRIX -> out.writePopMatrix(raw.readInt()); + case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity(); + case GLCommand.PUSH_MATRIX -> out.writePushMatrix(); + case GLCommand.POP_MATRIX -> out.writePopMatrix(); case GLCommand.STENCIL_MASK -> out.writeStencilMask(raw.readInt()); case GLCommand.DEPTH_MASK -> out.writeDepthMask(raw.readInt() != 0); case GLCommand.FRONT_FACE -> out.writeFrontFace(raw.readInt()); @@ -202,15 +163,15 @@ public final class CommandBufferProcessor { case GLCommand.TEX_PARAMETERF -> out.writeTexParameterf(raw.readInt(), raw.readInt(), raw.readFloat()); // Double commands - case GLCommand.TRANSLATE -> out.writeTranslate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble()); - case GLCommand.ROTATE -> out.writeRotate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); - case GLCommand.SCALE -> out.writeScale(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble()); + case GLCommand.TRANSLATE -> out.writeTranslate(raw.readDouble(), raw.readDouble(), raw.readDouble()); + case GLCommand.ROTATE -> out.writeRotate(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); + case GLCommand.SCALE -> out.writeScale(raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.ORTHO -> out.writeOrtho(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.FRUSTUM -> out.writeFrustum(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); // Matrix commands - case GLCommand.MULT_MATRIX -> { int mode = raw.readInt(); out.writeMultMatrix(mode, raw.readMatrix4f(tempMatrix)); } - case GLCommand.LOAD_MATRIX -> { int mode = raw.readInt(); out.writeLoadMatrix(mode, raw.readMatrix4f(tempMatrix)); } + case GLCommand.MULT_MATRIX -> { out.writeMultMatrix(raw.readMatrix4f(tempMatrix)); } + case GLCommand.LOAD_MATRIX -> { out.writeLoadMatrix(raw.readMatrix4f(tempMatrix)); } // FloatBuffer commands (inline 4 floats max) case GLCommand.FOG -> { @@ -265,11 +226,17 @@ public final class CommandBufferProcessor { /** * Lightweight transform optimizer for buffer-to-buffer processing. - * Tracks accumulated MODELVIEW transform and emits MultMatrix commands when needed. + * 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; @@ -278,18 +245,6 @@ public final class CommandBufferProcessor { lastEmitted.identity(); } - public void translate(double x, double y, double z) { - accumulated.translate((float) x, (float) y, (float) z); - } - - public void rotate(double angle, double x, double y, double z) { - accumulated.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z); - } - - public void scale(double x, double y, double z) { - accumulated.scale((float) x, (float) y, (float) z); - } - public void multMatrix(Matrix4f m) { accumulated.mul(m); } @@ -326,6 +281,18 @@ public final class CommandBufferProcessor { 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); @@ -338,10 +305,10 @@ public final class CommandBufferProcessor { } if (DisplayListManager.isIdentity(lastEmitted)) { - out.writeMultMatrix(GL11.GL_MODELVIEW, target); + out.writeMultMatrix(target); } else { - final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target); - out.writeMultMatrix(GL11.GL_MODELVIEW, delta); + 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 2d7c54e7a..d8e706674 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java @@ -132,43 +132,28 @@ public class CommandRecorder { commandCount++; } - public void recordLoadIdentity(int matrixMode) { - buffer.writeLoadIdentity(matrixMode); + public void recordLoadIdentity() { + buffer.writeLoadIdentity(); commandCount++; } - public void recordPushMatrix(int matrixMode) { - buffer.writePushMatrix(matrixMode); + public void recordPushMatrix() { + buffer.writePushMatrix(); commandCount++; } - public void recordPopMatrix(int matrixMode) { - buffer.writePopMatrix(matrixMode); + public void recordPopMatrix() { + buffer.writePopMatrix(); commandCount++; } - public void recordTranslate(int matrixMode, double x, double y, double z) { - buffer.writeTranslate(matrixMode, x, y, z); + public void recordMultMatrix(Matrix4f matrix) { + buffer.writeMultMatrix(matrix); commandCount++; } - public void recordRotate(int matrixMode, double angle, double x, double y, double z) { - buffer.writeRotate(matrixMode, angle, x, y, z); - commandCount++; - } - - public void recordScale(int matrixMode, double x, double y, double z) { - buffer.writeScale(matrixMode, x, y, z); - commandCount++; - } - - public void recordMultMatrix(int matrixMode, Matrix4f matrix) { - buffer.writeMultMatrix(matrixMode, matrix); - commandCount++; - } - - public void recordLoadMatrix(int matrixMode, Matrix4f matrix) { - buffer.writeLoadMatrix(matrixMode, matrix); + public void recordLoadMatrix(Matrix4f matrix) { + buffer.writeLoadMatrix(matrix); 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 bf69159df..68cac09aa 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java @@ -22,6 +22,12 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; *

    The ownedVbos array contains VBOs that are referenced by DrawRange commands. */ public final class CompiledDisplayList { + /** + * Empty display list singleton. Per OpenGL spec, an empty list is still valid. + * This instance does nothing when rendered and is never deleted (shared singleton). + */ + public static final CompiledDisplayList EMPTY = new CompiledDisplayList(null, null, null); + 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 @@ -97,14 +103,14 @@ public final class CompiledDisplayList { * Used for testing to verify optimization results. */ public Int2IntMap getCommandCounts() { - Int2IntMap counts = new Int2IntOpenHashMap(); + final Int2IntMap counts = new Int2IntOpenHashMap(); if (commandBuffer == null || commandBuffer.limit() == 0) { return counts; } long ptr = memAddress(commandBuffer); - long end = ptr + commandBuffer.limit(); + final long end = ptr + commandBuffer.limit(); while (ptr < end) { - int cmd = memGetInt(ptr); + final int cmd = memGetInt(ptr); counts.mergeInt(cmd, 1, Integer::sum); ptr += getCommandSize(cmd, ptr); } @@ -116,14 +122,14 @@ public final class CompiledDisplayList { * Used for testing to verify command ordering. */ public IntList getCommandOpcodes() { - IntList opcodes = new IntArrayList(); + final IntList opcodes = new IntArrayList(); if (commandBuffer == null || commandBuffer.limit() == 0) { return opcodes; } long ptr = memAddress(commandBuffer); - long end = ptr + commandBuffer.limit(); + final long end = ptr + commandBuffer.limit(); while (ptr < end) { - int cmd = memGetInt(ptr); + final int cmd = memGetInt(ptr); opcodes.add(cmd); ptr += getCommandSize(cmd, ptr); } @@ -135,12 +141,14 @@ public final class CompiledDisplayList { */ 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.LOAD_IDENTITY, - GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.STENCIL_MASK, + 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; @@ -161,22 +169,32 @@ public final class CompiledDisplayList { 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 -> 32; // cmd + mode + 3 doubles + case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double - case GLCommand.ROTATE -> 40; // cmd + mode + 4 doubles + case GLCommand.ROTATE -> 36; // cmd + 4 doubles case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles - // Matrix commands (72 bytes) - case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 72; + // Matrix commands + case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats // Buffer commands (variable, read count) case GLCommand.FOG, GLCommand.LIGHT_MODEL -> { - int count = memGetInt(ptr + 8); // pname at +4, count at +8 + final int count = memGetInt(ptr + 8); // pname at +4, count at +8 yield 12 + count * 4; } case GLCommand.LIGHT, GLCommand.MATERIAL -> { - int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12 + final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12 yield 16 + count * 4; } 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 5143ba93f..8a89449bb 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java @@ -92,6 +92,12 @@ public final class GLCommand { 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) + /** + * 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 // === Complex object reference === public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes @@ -165,6 +171,7 @@ 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"; default -> "UNKNOWN(" + opcode + ")"; }; 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 596c820c4..cccd1bc87 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java @@ -164,6 +164,31 @@ public class ImmediateModeRecorder { 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; + + if (!currentVertices.isEmpty()) { + ImmediateVertex last = currentVertices.get(currentVertices.size() - 1); + + // 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(); @@ -188,7 +213,10 @@ public class ImmediateModeRecorder { quads.clear(); lineVertices.clear(); - return new Result(resultQuads, resultLines, flags); + return new Result(resultQuads, resultLines, flags, + lastColorR, lastColorG, lastColorB, lastColorA, + lastNormalX, lastNormalY, lastNormalZ, + lastTexS, lastTexT); } /** @@ -520,14 +548,28 @@ public class ImmediateModeRecorder { hasNormal = false; // Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec - return new Result(resultQuads, resultLines, flags); + // 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, and their attribute flags. + * 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) {} + 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. diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AccumulableMatrixCommand.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AccumulableMatrixCommand.java deleted file mode 100644 index e14e97653..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AccumulableMatrixCommand.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import org.joml.Matrix4f; - -/** - * Interface for matrix commands that can be accumulated during transform optimization. - * Implemented by TranslateCmd, RotateCmd, ScaleCmd, and MultMatrixCmd. - */ -public interface AccumulableMatrixCommand extends DisplayListCommand { - boolean isModelView(); - void applyTo(Matrix4f matrix); - - @Override - default boolean handleOptimization(OptimizationContext ctx) { - if (isModelView()) { - applyTo(ctx.getAccumulatedTransform()); - return false; // Accumulated, don't emit - } - return true; // Non-MODELVIEW, emit as-is - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/CallListCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/CallListCmd.java deleted file mode 100644 index faf74dcf3..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/CallListCmd.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; - -/** - * Command: Call another display list (glCallList) - * Records a reference to another display list to be executed during playback. - * Per OpenGL spec: the referenced list is NOT executed during compilation, - * only the reference is recorded. - * - */ -@Desugar -public record CallListCmd(int listId) implements DisplayListCommand { - private static final Logger LOGGER = LogManager.getLogger("CallListCmd"); - - @Override - public void execute() { - final CompiledDisplayList compiled = GLStateManager.getDisplayList(listId); - - if (compiled != null) { - GLDebug.pushGroup("CallList(" + listId + ")"); - try { - compiled.render(); - } finally { - GLDebug.popGroup(); - } - } else { - // Fallback if list not found (shouldn't happen in normal operation) - LOGGER.warn("[CallListCmd] List {} not found in cache, using fallback glCallList", listId); - GLStateManager.glCallList(listId); - } - } - - @Override - public void delete() { - // No resources to free - we just hold a reference - } - - @Override - public boolean needsTransformSync() { - return true; // Nested list uses current GL matrix state - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - // Nested list needs current GL matrix state - ctx.emitPendingTransform(); - return true; // Emit this command - } - - @Override - public @NotNull String toString() { - return "CallList(" + listId + ")"; - } -} 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 7d5e5f64e..7d96f08b9 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 @@ -18,23 +18,6 @@ public interface DisplayListCommand { // Most commands don't hold resources } - /** - * Returns true if this barrier command requires the MODELVIEW transform to be - * synchronized with the accumulated state before execution. - * - *

    This should return true for commands where the GL matrix state matters, - * such as CallListCmd (nested lists use current GL state) or PushAttribCmd - * with GL_TRANSFORM_BIT (saves the current matrix).

    - * - *

    Commands like PushAttribCmd with only GL_COLOR_BUFFER_BIT don't need - * transform sync because they don't interact with the matrix stack.

    - * - * @return true if transform must be synced to accumulated before this barrier - */ - default boolean needsTransformSync() { - return false; - } - /** * Handle this command during display list optimization. * diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadIdentityCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadIdentityCmd.java deleted file mode 100644 index cf0754302..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadIdentityCmd.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.lwjgl.opengl.GL11; - -/** - * Command: glLoadIdentity() - * Replaces the current matrix with the identity matrix for the specified matrix mode. - */ -@Desugar -public record LoadIdentityCmd(int matrixMode) implements DisplayListCommand { - @Override - public void execute() { - GLStateManager.glLoadIdentity(); - } - - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - if (isModelView()) { - // Check if we're at an absolute matrix (after LoadMatrix) - // If so, we must emit LoadIdentity to actually reset GL state - if (ctx.checkAndClearAbsoluteMatrix()) { - ctx.emit(this); - ctx.loadIdentity(); - return false; // Already emitted - } - ctx.loadIdentity(); - return false; // Accumulated, don't emit - } - return true; // Non-MODELVIEW, emit as-is - } - - @Override - public @NotNull String toString() { - return String.format("LoadIdentity(%s)", GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadMatrixCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadMatrixCmd.java deleted file mode 100644 index 59687100f..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/LoadMatrixCmd.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -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; - -/** - * Command: glLoadMatrix(matrix) - * Replaces the current matrix with the specified matrix for the given matrix mode. - * - *

    Unlike MultMatrixCmd which can be absorbed into the accumulated transform, - * LoadMatrixCmd must always be emitted because it sets an absolute value, not a relative one. - * After a LoadMatrix command, the accumulated transform is reset to identity since - * subsequent transforms are relative to the newly loaded matrix.

    - */ -@Desugar -public record LoadMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements DisplayListCommand { - - /** - * Create a LoadMatrixCmd with pre-allocated buffer. - */ - public static LoadMatrixCmd create(Matrix4f matrix, int matrixMode) { - final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); - matrix.get(buffer); - buffer.rewind(); - return new LoadMatrixCmd(new Matrix4f(matrix), matrixMode, buffer); - } - - /** - * Create a LoadMatrixCmd from a FloatBuffer (copies the data). - */ - public static LoadMatrixCmd create(FloatBuffer src, int matrixMode) { - final Matrix4f matrix = new Matrix4f().set(src); - src.rewind(); - return create(matrix, matrixMode); - } - - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public void execute() { - // Buffer already populated at construction, just rewind and use - buffer.rewind(); - GLStateManager.glLoadMatrix(buffer); - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - if (isModelView()) { - // LoadMatrix sets an absolute value - emit any pending relative transform first - ctx.emitPendingTransform(); - // Emit this command - ctx.emit(this); - // Reset accumulated to identity - subsequent transforms are relative to the loaded matrix - ctx.loadIdentity(); - // Mark that GL is at an absolute value - LoadIdentity must emit to reset - ctx.markAbsoluteMatrix(); - return false; // Already emitted - } - return true; // Non-MODELVIEW, emit as-is - } - - @Override - public @NotNull String toString() { - return String.format("LoadMatrix(%s, %s)", GLDebug.getMatrixModeName(matrixMode), matrix); - } -} 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 5f9a0f2e1..b68beba49 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 @@ -11,34 +11,23 @@ import java.nio.FloatBuffer; /** * Command: glMultMatrix(matrix) - * Multiplies the specified matrix mode by the specified matrix. + * Multiplies the current matrix by the specified matrix. */ @Desugar -public record MultMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements AccumulableMatrixCommand { +public record MultMatrixCmd(Matrix4f matrix, FloatBuffer buffer) implements DisplayListCommand { /** * Create a MultMatrixCmd with pre-allocated buffer. */ - public static MultMatrixCmd create(Matrix4f matrix, int matrixMode) { + public static MultMatrixCmd create(Matrix4f matrix) { final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); matrix.get(buffer); buffer.rewind(); - return new MultMatrixCmd(new Matrix4f(matrix), matrixMode, buffer); - } - - @Override - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public void applyTo(Matrix4f target) { - target.mul(matrix); + return new MultMatrixCmd(new Matrix4f(matrix), buffer); } @Override public void execute() { - // Buffer already populated at construction, just rewind and use buffer.rewind(); GLStateManager.glMultMatrix(buffer); } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopAttribCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopAttribCmd.java deleted file mode 100644 index 9d44797f7..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopAttribCmd.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; - -/** - * Command: glPopAttrib() - * Pops the server attribute stack. - */ -@Desugar -public record PopAttribCmd() implements DisplayListCommand { - @Override - public void execute() { - GLStateManager.glPopAttrib(); - } - - @Override - public boolean needsTransformSync() { - return true; - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - ctx.emitPendingTransform(); - return true; - } - - @Override - public @NotNull String toString() { - return "PopAttrib()"; - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopMatrixCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopMatrixCmd.java deleted file mode 100644 index 5314218f8..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PopMatrixCmd.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.lwjgl.opengl.GL11; - -/** - * Command: glPopMatrix() - * Pops the current matrix from the matrix stack for the specified matrix mode. - */ -@Desugar -public record PopMatrixCmd(int matrixMode) implements DisplayListCommand { - @Override - public void execute() { - GLStateManager.glPopMatrix(); - } - - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - if (isModelView()) { - ctx.popTransform(); - } - return true; // Always emit Pop - } - - @Override - public @NotNull String toString() { - return String.format("PopMatrix(%s)", GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushAttribCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushAttribCmd.java deleted file mode 100644 index d23c951b4..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushAttribCmd.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.lwjgl.opengl.GL11; - -/** - * Command: glPushAttrib(mask) - * Pushes the server attribute stack. - */ -@Desugar -public record PushAttribCmd(int mask) implements DisplayListCommand { - @Override - public void execute() { - GLStateManager.glPushAttrib(mask); - } - - @Override - public boolean needsTransformSync() { - // Only need transform sync if we're pushing transform state. - // GL_TRANSFORM_BIT includes the matrix mode and matrix stacks. - return (mask & GL11.GL_TRANSFORM_BIT) != 0; - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - if (needsTransformSync()) { - ctx.emitPendingTransform(); - } - return true; - } - - @Override - public @NotNull String toString() { - return String.format("PushAttrib(0x%08X)", mask); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushMatrixCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushMatrixCmd.java deleted file mode 100644 index 7c459982a..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/PushMatrixCmd.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.lwjgl.opengl.GL11; - -/** - * Command: glPushMatrix() - * Pushes the current matrix onto the matrix stack for the specified matrix mode. - */ -@Desugar -public record PushMatrixCmd(int matrixMode) implements DisplayListCommand { - @Override - public void execute() { - GLStateManager.glPushMatrix(); - } - - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public boolean handleOptimization(OptimizationContext ctx) { - if (isModelView()) { - ctx.emitPendingTransform(); - ctx.pushTransform(); - } - return true; // Always emit Push - } - - @Override - public @NotNull String toString() { - return String.format("PushMatrix(%s)", GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/RotateCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/RotateCmd.java deleted file mode 100644 index 8cc2151fa..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/RotateCmd.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; - -/** - * Command: glRotatef() or glRotated() - * Stores as doubles for precision. - */ -@Desugar -public record RotateCmd(double angle, double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand { - @Override - public void execute() { - GLStateManager.glRotated(angle, x, y, z); - } - - @Override - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public void applyTo(Matrix4f matrix) { - matrix.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z); - } - - @Override - public @NotNull String toString() { - return String.format("Rotate(%.2f deg, %.2f, %.2f, %.2f, %s)", angle, x, y, z, GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/ScaleCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/ScaleCmd.java deleted file mode 100644 index c2e963391..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/ScaleCmd.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; - -/** - * Command: glScalef() or glScaled() - * Stores as doubles for precision. - */ -@Desugar -public record ScaleCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand { - @Override - public void execute() { - GLStateManager.glScaled(x, y, z); - } - - @Override - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public void applyTo(Matrix4f matrix) { - matrix.scale((float) x, (float) y, (float) z); - } - - @Override - public @NotNull String toString() { - return String.format("Scale(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TranslateCmd.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TranslateCmd.java deleted file mode 100644 index d620a7f1d..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TranslateCmd.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.recording.commands; - -import com.github.bsideup.jabel.Desugar; -import com.gtnewhorizons.angelica.glsm.GLDebug; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.jetbrains.annotations.NotNull; -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; - -/** - * Command: glTranslatef() or glTranslated() - * Stores as doubles for precision. - */ -@Desugar -public record TranslateCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand { - @Override - public void execute() { - // Save current mode - final int savedMode = GLStateManager.getMatrixMode().getMode(); - - // Switch to the mode this was recorded with - GLStateManager.glMatrixMode(matrixMode); - GLStateManager.glTranslated(x, y, z); - - // Restore mode - GLStateManager.glMatrixMode(savedMode); - } - - @Override - public boolean isModelView() { - return matrixMode == GL11.GL_MODELVIEW; - } - - @Override - public void applyTo(Matrix4f matrix) { - matrix.translate((float) x, (float) y, (float) z); - } - - @Override - public @NotNull String toString() { - return String.format("Translate(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode)); - } -} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java new file mode 100644 index 000000000..9bfef81fc --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java @@ -0,0 +1,56 @@ +package com.gtnewhorizons.angelica.glsm.stacks; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +/** + * BooleanStateStack for per-texture-unit state. + * Switches to correct unit (raw GL) before enable/disable calls. + */ +public class TextureUnitBooleanStateStack extends BooleanStateStack { + private final int unitIndex; + + public TextureUnitBooleanStateStack(int glCap, int unitIndex) { + super(glCap); + this.unitIndex = unitIndex; + } + + public TextureUnitBooleanStateStack(int glCap, int unitIndex, boolean initialState) { + super(glCap, initialState); + this.unitIndex = unitIndex; + } + + @Override + public void setEnabled(boolean enabled) { + beforeModify(); + setEnabledWithUnitSwitch(enabled); + } + + @Override + public TextureUnitBooleanStateStack popDepth() { + if (savedDepth > 0) { + final boolean oldValue = stack[--savedDepth]; + setEnabledWithUnitSwitch(oldValue); + } + return this; + } + + private void setEnabledWithUnitSwitch(boolean enabled) { + final boolean bypass = GLStateManager.shouldBypassCache(); + if (bypass || enabled != this.enabled) { + if (!bypass) this.enabled = enabled; + + int currentUnit = GLStateManager.getActiveTextureUnit(); + boolean needsSwitch = currentUnit != unitIndex; + + if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + unitIndex); + if (enabled) GL11.glEnable(glCap); else GL11.glDisable(glCap); + if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentUnit); + } + } + + public int getUnitIndex() { + return unitIndex; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java index 64b2ed8ad..6fe3da4d4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java @@ -27,13 +27,11 @@ public class BooleanState implements ISettableState { if (!bypass) { this.enabled = enabled; } - // Skip actual GL calls during display list recording (state tracking only) - if (!GLStateManager.isRecordingDisplayList()) { - if (enabled) { - GL11.glEnable(this.glCap); - } else { - GL11.glDisable(this.glCap); - } + // Always call GL - the calling method controls whether we reach here based on recording mode + if (enabled) { + GL11.glEnable(this.glCap); + } else { + GL11.glDisable(this.glCap); } } } 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 d78c01c8f..1a868a63c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureUnitArray.java @@ -1,7 +1,7 @@ package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack; import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack; import lombok.Getter; import org.joml.Matrix4fStack; @@ -10,36 +10,36 @@ import org.lwjgl.opengl.GL12; public class TextureUnitArray { private final TextureBindingStack[] bindings; - private final BooleanStateStack[] states; - private final BooleanStateStack[] texture1DStates; - private final BooleanStateStack[] texture3DStates; - private final BooleanStateStack[] texGenSStates; - private final BooleanStateStack[] texGenTStates; - private final BooleanStateStack[] texGenRStates; - private final BooleanStateStack[] texGenQStates; + private final TextureUnitBooleanStateStack[] states; + private final TextureUnitBooleanStateStack[] texture1DStates; + private final TextureUnitBooleanStateStack[] texture3DStates; + private final TextureUnitBooleanStateStack[] texGenSStates; + private final TextureUnitBooleanStateStack[] texGenTStates; + private final TextureUnitBooleanStateStack[] texGenRStates; + private final TextureUnitBooleanStateStack[] texGenQStates; @Getter public final Matrix4fStack[] textureMatricies; public TextureUnitArray() { bindings = new TextureBindingStack[GLStateManager.MAX_TEXTURE_UNITS]; - states = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texture1DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texture3DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texGenSStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texGenTStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texGenRStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; - texGenQStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + states = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texture1DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texture3DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texGenSStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texGenTStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texGenRStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; + texGenQStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; textureMatricies = new Matrix4fStack[GLStateManager.MAX_TEXTURE_UNITS]; for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { bindings[i] = new TextureBindingStack(); - states[i] = new BooleanStateStack(GL11.GL_TEXTURE_2D); - texture1DStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_1D); - texture3DStates[i] = new BooleanStateStack(GL12.GL_TEXTURE_3D); - texGenSStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_S); - texGenTStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_T); - texGenRStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_R); - texGenQStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_Q); + states[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_2D, i); + texture1DStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_1D, i); + texture3DStates[i] = new TextureUnitBooleanStateStack(GL12.GL_TEXTURE_3D, i); + texGenSStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_S, i); + texGenTStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_T, i); + texGenRStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_R, i); + texGenQStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_Q, i); textureMatricies[i] = new Matrix4fStack(GLStateManager.MAX_TEXTURE_STACK_DEPTH); } } @@ -48,31 +48,31 @@ public class TextureUnitArray { return bindings[index]; } - public BooleanStateStack getTextureUnitStates(int index) { + public TextureUnitBooleanStateStack getTextureUnitStates(int index) { return states[index]; } - public BooleanStateStack getTexture1DStates(int index) { + public TextureUnitBooleanStateStack getTexture1DStates(int index) { return texture1DStates[index]; } - public BooleanStateStack getTexture3DStates(int index) { + public TextureUnitBooleanStateStack getTexture3DStates(int index) { return texture3DStates[index]; } - public BooleanStateStack getTexGenSStates(int index) { + public TextureUnitBooleanStateStack getTexGenSStates(int index) { return texGenSStates[index]; } - public BooleanStateStack getTexGenTStates(int index) { + public TextureUnitBooleanStateStack getTexGenTStates(int index) { return texGenTStates[index]; } - public BooleanStateStack getTexGenRStates(int index) { + public TextureUnitBooleanStateStack getTexGenRStates(int index) { return texGenRStates[index]; } - public BooleanStateStack getTexGenQStates(int index) { + public TextureUnitBooleanStateStack getTexGenQStates(int index) { return texGenQStates[index]; } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java new file mode 100644 index 000000000..bb086e076 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java @@ -0,0 +1,267 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.AngelicaExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.*; + +/** Tests GLSM display list behavior matches OpenGL spec. */ +@ExtendWith(AngelicaExtension.class) +class DisplayListCompilationGLSMTest { + + private int testList = -1; + + private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) { + for (int i = 0; i < 16; i++) { + assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")"); + } + } + + @BeforeEach + void setup() { + // Ensure not recording from a previous failed test + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + // Reset matrix to identity for transform tests + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + } + + @AfterEach + void cleanup() { + // End any open recording + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + if (testList > 0) { + GLStateManager.glDeleteLists(testList, 1); + testList = -1; + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + } + + @Test + void glsm_compile_doesNotChangeState() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.enableBlend(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged"); + + GLStateManager.glEndList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged"); + + GLStateManager.glCallList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed"); + } + + @Test + void glsm_compileAndExecute_changesStateImmediately() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + GLStateManager.enableBlend(); + + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed"); + + GLStateManager.glEndList(); + + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains"); + } + + @Test + void glsm_compile_transformNotApplied() { + FloatBuffer before = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.glTranslatef(10, 20, 30); + + FloatBuffer during = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); + assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged"); + + GLStateManager.glEndList(); + } + + @Test + void glsm_compileAndExecute_transformQueuedUntilFlush() { + // Transforms queue until draw/glEndList (state commands don't flush) + FloatBuffer identity = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, identity); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + GLStateManager.glTranslatef(10, 0, 0); // Queued + + FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); + assertMatrixEquals(identity, beforeFlush, "Before flush: transform queued"); + + GLStateManager.enableBlend(); // State commands DON'T flush transforms anymore + + FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); + assertMatrixEquals(identity, afterStateCmd, "After state cmd: transform still queued"); + + GLStateManager.glEndList(); // glEndList flushes pending transforms + + FloatBuffer afterEndList = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterEndList); + assertEquals(10.0f, afterEndList.get(12), 0.001f, "After glEndList: transform applied"); + } + + @Test + void glsm_playback_appliesRecordedState() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.enableBlend(); + GLStateManager.glEndList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After compile: unchanged"); + + GLStateManager.glCallList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: enabled"); + } + + @Test + void glsm_compile_multipleStateChanges() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.enableBlend(); + GLStateManager.enableDepthTest(); + GLStateManager.enableCull(); + GLStateManager.glEndList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged"); + + GLStateManager.glCallList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled"); + } + + @Test + void glsm_compile_matrixModeChangeRecorded() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glTranslatef(5, 0, 0); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glTranslatef(10, 0, 0); + GLStateManager.glEndList(); + + FloatBuffer proj = BufferUtils.createFloatBuffer(16); + FloatBuffer mv = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); + assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); + + GLStateManager.glCallList(testList); + + proj.clear(); mv.clear(); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)"); + assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); + } + + @Test + void glsm_compile_pushPopMatrixRecorded() { + GLStateManager.glTranslatef(100, 0, 0); // Base transform + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.glPushMatrix(); + GLStateManager.glTranslatef(10, 0, 0); + GLStateManager.glPopMatrix(); + GLStateManager.glEndList(); + + FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); + assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base"); + + GLStateManager.glCallList(testList); + + FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); + assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base"); + } + + @Test + void glsm_compileAndExecute_matrixModeFlushesTransforms() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GLStateManager.glTranslatef(10, 0, 0); // Queued + GLStateManager.glRotatef(45, 0, 1, 0); // Queued + + FloatBuffer beforeMode = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeMode); + assertEquals(0.0f, beforeMode.get(12), 0.001f, "Before MatrixMode: queued"); + + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); // Barrier - flushes + + FloatBuffer afterMode = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterMode); + assertNotEquals(0.0f, afterMode.get(12), "After MatrixMode: flushed to MODELVIEW"); + + FloatBuffer proj = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + assertEquals(0.0f, proj.get(12), 0.001f, "PROJECTION still identity"); + + GLStateManager.glEndList(); + + // Cleanup: restore matrix mode to MODELVIEW + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + @Test + void glsm_compileAndExecute_pushPopMatrixQueued() { + // State commands don't flush, but push/pop ARE matrix barriers + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GLStateManager.glPushMatrix(); + GLStateManager.glTranslatef(10, 0, 0); + + FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); + assertEquals(0.0f, beforeFlush.get(12), 0.001f, "Before flush: queued"); + + GLStateManager.enableBlend(); // NOT a barrier in new model + + FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); + assertEquals(0.0f, afterStateCmd.get(12), 0.001f, "After state cmd: still queued"); + + GLStateManager.glPopMatrix(); // Matrix barrier: flushes transform, then pops + + FloatBuffer afterPop = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); + assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity (pushed state)"); + + GLStateManager.glEndList(); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java new file mode 100644 index 000000000..d6abfc701 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java @@ -0,0 +1,261 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.AngelicaExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.*; + +/** Tests raw GL11 display list behavior (reference for GLSM). */ +@ExtendWith(AngelicaExtension.class) +class DisplayListCompilationRawGLTest { + + private int testList = -1; + + private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) { + for (int i = 0; i < 16; i++) { + assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")"); + } + } + + @BeforeEach + void setup() { + GL11.glDisable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + } + + @AfterEach + void cleanup() { + if (testList > 0) { + GL11.glDeleteLists(testList, 1); + testList = -1; + } + GL11.glDisable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + } + + @Test + void rawGL_compile_doesNotChangeState() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + GL11.glEnable(GL11.GL_BLEND); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged"); + + GL11.glEndList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged"); + + GL11.glCallList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed"); + } + + @Test + void rawGL_compileAndExecute_changesStateImmediately() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + GL11.glEnable(GL11.GL_BLEND); + + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed"); + + GL11.glEndList(); + + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains"); + } + + @Test + void rawGL_compile_transformNotApplied() { + FloatBuffer before = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + GL11.glTranslatef(10, 20, 30); + + FloatBuffer during = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); + assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged"); + + GL11.glEndList(); + } + + @Test + void rawGL_compileAndExecute_transformAppliedImmediately() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + GL11.glTranslatef(10, 0, 0); + + FloatBuffer matrix = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrix); + assertEquals(10.0f, matrix.get(12), 0.001f, "During GL_COMPILE_AND_EXECUTE: transform applied"); + + GL11.glEndList(); + } + + @Test + void rawGL_compile_multipleStateChanges() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEndList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged"); + + GL11.glCallList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled"); + } + + @Test + void rawGL_compile_matrixModeChangeRecorded() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glTranslatef(5, 0, 0); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glTranslatef(10, 0, 0); + GL11.glEndList(); + + FloatBuffer proj = BufferUtils.createFloatBuffer(16); + FloatBuffer mv = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); + assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); + + GL11.glCallList(testList); + + proj.clear(); mv.clear(); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)"); + assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); + } + + @Test + void rawGL_compile_pushPopMatrixRecorded() { + GL11.glTranslatef(100, 0, 0); // Base transform + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + GL11.glPushMatrix(); + GL11.glTranslatef(10, 0, 0); + GL11.glPopMatrix(); + GL11.glEndList(); + + FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); + assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base"); + + GL11.glCallList(testList); + + FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); + assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base (push/pop balanced)"); + } + + @Test + void rawGL_compileAndExecute_pushPopMatrixExecutedImmediately() { + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GL11.glPushMatrix(); + GL11.glTranslatef(10, 0, 0); + + FloatBuffer inside = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, inside); + assertEquals(10.0f, inside.get(12), 0.001f, "Inside push: translate visible"); + + GL11.glPopMatrix(); + + FloatBuffer afterPop = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); + assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity"); + + GL11.glEndList(); + } + + // ==================== Immediate Mode with Transforms (Raw GL) ==================== + + @Test + void rawGL_compile_immediateModeWithTransforms() { + // Verifies GL_COMPILE doesn't execute, playback applies transforms + GL11.glLoadIdentity(); + GL11.glTranslatef(100.0f, 0.0f, 0.0f); // Base position + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + + GL11.glPushMatrix(); + GL11.glTranslatef(50.0f, 25.0f, 0.0f); + GL11.glScalef(0.5f, 0.5f, 1.0f); + + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex3f(0.0f, 0.0f, 0.0f); + GL11.glVertex3f(16.0f, 0.0f, 0.0f); + GL11.glVertex3f(16.0f, 16.0f, 0.0f); + GL11.glVertex3f(0.0f, 16.0f, 0.0f); + GL11.glEnd(); + + GL11.glPopMatrix(); + GL11.glEndList(); + + // Matrix should still be at base position after GL_COMPILE + FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); + assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix unchanged"); + + // Playback - push/pop should preserve base transform + GL11.glCallList(testList); + + FloatBuffer afterPlayback = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlayback); + assertEquals(100.0f, afterPlayback.get(12), 0.001f, "After playback: base position preserved"); + assertEquals(1.0f, afterPlayback.get(0), 0.001f, "After playback: no scale (popped)"); + + GL11.glLoadIdentity(); + } + + @Test + void rawGL_compileAndExecute_immediateModeExecutesImmediately() { + // Verifies GL_COMPILE_AND_EXECUTE executes transforms during recording + GL11.glLoadIdentity(); + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GL11.glScalef(0.5f, 0.5f, 0.5f); + + FloatBuffer during = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); + assertEquals(0.5f, during.get(0), 0.001f, "During COMPILE_AND_EXECUTE: scale applied"); + + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex3f(0.0f, 0.0f, 0.0f); + GL11.glVertex3f(1.0f, 0.0f, 0.0f); + GL11.glVertex3f(1.0f, 1.0f, 0.0f); + GL11.glVertex3f(0.0f, 1.0f, 0.0f); + GL11.glEnd(); + + GL11.glEndList(); + + FloatBuffer after = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, after); + assertEquals(0.5f, after.get(0), 0.001f, "After COMPILE_AND_EXECUTE: scale remains"); + + GL11.glLoadIdentity(); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java index f66355d14..68eb4a5f3 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java @@ -92,7 +92,26 @@ public final class DisplayListTestHelper { Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { - return new AccumulatedDraw(quads, transform, flags, 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); } /** @@ -110,12 +129,27 @@ public final class DisplayListTestHelper { /** * Create an AccumulatedDraw with specified transform. */ - public static AccumulatedDraw createDrawWithTransform(Matrix4f transform, int commandIndex) { + public static AccumulatedDraw createDrawWithTransform(Matrix4f transform, int commandIndex, int matrixGeneration) { return createDraw( Collections.singletonList(createSimpleQuad()), transform, positionOnly(), - commandIndex + 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 ); } @@ -333,7 +367,16 @@ public final class DisplayListTestHelper { Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { - return new AccumulatedPrimitiveDraw(primitives, transform, flags, 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); } /** 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 1a35d2449..1a99385bc 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 @@ -7,11 +7,9 @@ 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 com.gtnewhorizons.angelica.glsm.recording.commands.TranslateCmd; import org.joml.Matrix4f; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.HashSet; @@ -120,15 +118,11 @@ class GLSM_DisplayList_Batching_Test { // 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)); // Identity transform - draws.add(createDrawWithTransform(new Matrix4f().translate(1.0f, 0.0f, 0.0f), 2)); // After translate - draws.add(createDrawWithTransform(new Matrix4f().translate(3.0f, 0.0f, 0.0f), 4)); // After more translates + 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<>(); - commands.add(new TranslateCmd(1.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 0 - commands.add(new TranslateCmd(2.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 1 - commands.add(new TranslateCmd(3.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 2 - commands.add(new TranslateCmd(4.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 3 // Execute OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1); @@ -145,9 +139,9 @@ class GLSM_DisplayList_Batching_Test { Set uniqueVBOs = getUniqueVBOs(optimized); assertEquals(1, uniqueVBOs.size(), "All DrawRangeCmds should reference the same shared VBO"); - // Should have MultMatrix commands for the transforms + // Should have MultMatrix commands for the transforms (2 for T(1) and T(3)) long matrixCount = countMultMatrixCmds(optimized); - assertTrue(matrixCount >= 2, "Should have MultMatrix commands for each unique transform"); + assertEquals(2, matrixCount, "Should have MultMatrix commands for each unique transform"); } @Test @@ -196,52 +190,25 @@ class GLSM_DisplayList_Batching_Test { assertEquals(1, drawCount, "Draws with different quad counts but same format and transform should produce 1 DrawRangeCmd"); } - @Test - void testEmptyDrawListProducesNoVBOs() { - // Setup: no draws - List draws = new ArrayList<>(); - List commands = new ArrayList<>(); - commands.add(new TranslateCmd(1.0, 0.0, 0.0, GL11.GL_MODELVIEW)); - - // Execute - OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( - commands, draws, null, 1); - DisplayListCommand[] optimized = result.commands(); - - // Verify: no VBOs - assertEquals(0, result.ownedVbos().length, "No draws should produce no VBOs"); - - // Verify: no DrawRangeCmds - long drawCount = countDrawRangeCmds(optimized); - assertEquals(0, drawCount, "No draws should produce no DrawRangeCmds"); - - // But should still have the collapsed transform - long matrixCount = countMultMatrixCmds(optimized); - assertEquals(1, matrixCount, - "Transform should still be emitted even without draws"); - } - @Test void testCancellingTransformsProduceSeparateDrawRangeCmds() { - // This tests the specific bug where transforms cancel out in the command stream + // This tests the specific bug where transforms cancel out over the sequence // (e.g., translate(+0.5) then translate(-0.5)) but draws captured in between // have different transform states that must be preserved. // // 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 - draws.add(createDrawWithTransform(new Matrix4f(), 0)); - // Draw 2: captured at translate(0.5, 0, 0) - BEFORE the cancelling translate(-0.5) - draws.add(createDrawWithTransform(new Matrix4f().translate(0.5f, 0.0f, 0.0f), 2)); - // Draw 3: captured back at identity (after translate(-0.5) cancelled out) - draws.add(createDrawWithTransform(new Matrix4f(), 4)); + // 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<>(); - commands.add(new TranslateCmd(0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 0: move +0.5 - commands.add(new TranslateCmd(-0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 1: move -0.5 (cancels out) - commands.add(new TranslateCmd(0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 2: move +0.5 - commands.add(new TranslateCmd(-0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 3: move -0.5 (cancels out) // Execute OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( @@ -262,9 +229,10 @@ class GLSM_DisplayList_Batching_Test { Matrix4f commonTransform = new Matrix4f().translate(1.0f, 2.0f, 3.0f); List draws = new ArrayList<>(); - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0)); - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0)); - draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0)); + // 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<>(); @@ -286,6 +254,44 @@ class GLSM_DisplayList_Batching_Test { "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 + * All draws have same transform (gen=1) but different batches (0, 1, 2). + * Expected: 3 separate DrawRangeCmds (no merging across draw barriers). + * + * 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(); + + // Verify: 1 shared VBO (same format) + assertEquals(1, result.ownedVbos().length, + "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); + 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) diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_FormatOptimization_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_FormatOptimization_Test.java index f1417f075..cb6dbda97 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_FormatOptimization_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_FormatOptimization_Test.java @@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.lwjgl.opengl.GL11; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState; /** * Tests for display list format optimization. @@ -33,15 +33,16 @@ class GLSM_DisplayList_FormatOptimization_Test { @Test void testPositionOnlyFormat() { // Create a display list with only position data (no color, texture, brightness, or normals) + // Use GLStateManager for all calls to ensure they go through GLSM (test env doesn't redirect GL11) displayList = GL11.glGenLists(1); GLStateManager.glNewList(displayList, GL11.GL_COMPILE); - GL11.glBegin(GL11.GL_QUADS); - GL11.glVertex3f(0, 0, 0); - GL11.glVertex3f(1, 0, 0); - GL11.glVertex3f(1, 1, 0); - GL11.glVertex3f(0, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); GLStateManager.glEndList(); @@ -55,16 +56,16 @@ class GLSM_DisplayList_FormatOptimization_Test { displayList = GL11.glGenLists(1); GLStateManager.glNewList(displayList, GL11.GL_COMPILE); - GL11.glBegin(GL11.GL_QUADS); - GL11.glTexCoord2f(0, 0); - GL11.glVertex3f(0, 0, 0); - GL11.glTexCoord2f(1, 0); - GL11.glVertex3f(1, 0, 0); - GL11.glTexCoord2f(1, 1); - GL11.glVertex3f(1, 1, 0); - GL11.glTexCoord2f(0, 1); - GL11.glVertex3f(0, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glTexCoord2f(0, 0); + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glTexCoord2f(1, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glTexCoord2f(1, 1); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glTexCoord2f(0, 1); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); GLStateManager.glEndList(); @@ -78,25 +79,27 @@ class GLSM_DisplayList_FormatOptimization_Test { displayList = GL11.glGenLists(1); GLStateManager.glNewList(displayList, GL11.GL_COMPILE); - GL11.glBegin(GL11.GL_QUADS); - GL11.glColor4f(1, 1, 1, 1); - GL11.glTexCoord2f(0, 0); - GL11.glVertex3f(0, 0, 0); - GL11.glColor4f(1, 0, 0, 1); - GL11.glTexCoord2f(1, 0); - GL11.glVertex3f(1, 0, 0); - GL11.glColor4f(0, 1, 0, 1); - GL11.glTexCoord2f(1, 1); - GL11.glVertex3f(1, 1, 0); - GL11.glColor4f(0, 0, 1, 1); - GL11.glTexCoord2f(0, 1); - GL11.glVertex3f(0, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glColor4f(1, 1, 1, 1); + GLStateManager.glTexCoord2f(0, 0); + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glColor4f(1, 0, 0, 1); + GLStateManager.glTexCoord2f(1, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glColor4f(0, 1, 0, 1); + GLStateManager.glTexCoord2f(1, 1); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glColor4f(0, 0, 1, 1); + GLStateManager.glTexCoord2f(0, 1); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); GLStateManager.glEndList(); - // Call the list to ensure it doesn't crash (verifies compilation succeeded) + // Call the list and verify color is restored to last value (blue) GLStateManager.glCallList(displayList); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f}, + "After playback, color should be blue (last color in immediate mode block)"); } @Test @@ -105,29 +108,31 @@ class GLSM_DisplayList_FormatOptimization_Test { displayList = GL11.glGenLists(1); GLStateManager.glNewList(displayList, GL11.GL_COMPILE); - GL11.glBegin(GL11.GL_QUADS); - GL11.glNormal3f(0, 0, 1); - GL11.glColor4f(1, 1, 1, 1); - GL11.glTexCoord2f(0, 0); - GL11.glVertex3f(0, 0, 0); - GL11.glNormal3f(0, 0, 1); - GL11.glColor4f(1, 0, 0, 1); - GL11.glTexCoord2f(1, 0); - GL11.glVertex3f(1, 0, 0); - GL11.glNormal3f(0, 0, 1); - GL11.glColor4f(0, 1, 0, 1); - GL11.glTexCoord2f(1, 1); - GL11.glVertex3f(1, 1, 0); - GL11.glNormal3f(0, 0, 1); - GL11.glColor4f(0, 0, 1, 1); - GL11.glTexCoord2f(0, 1); - GL11.glVertex3f(0, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glNormal3f(0, 0, 1); + GLStateManager.glColor4f(1, 1, 1, 1); + GLStateManager.glTexCoord2f(0, 0); + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glNormal3f(0, 0, 1); + GLStateManager.glColor4f(1, 0, 0, 1); + GLStateManager.glTexCoord2f(1, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glNormal3f(0, 0, 1); + GLStateManager.glColor4f(0, 1, 0, 1); + GLStateManager.glTexCoord2f(1, 1); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glNormal3f(0, 0, 1); + GLStateManager.glColor4f(0, 0, 1, 1); + GLStateManager.glTexCoord2f(0, 1); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); GLStateManager.glEndList(); - // Call the list to ensure it doesn't crash (verifies compilation succeeded) + // Call the list and verify color is restored to last value (blue) GLStateManager.glCallList(displayList); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f}, + "After playback, color should be blue (last color in immediate mode block)"); } @Test @@ -137,40 +142,82 @@ class GLSM_DisplayList_FormatOptimization_Test { GLStateManager.glNewList(displayList, GL11.GL_COMPILE); // First draw: position only - GL11.glBegin(GL11.GL_QUADS); - GL11.glVertex3f(0, 0, 0); - GL11.glVertex3f(1, 0, 0); - GL11.glVertex3f(1, 1, 0); - GL11.glVertex3f(0, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); // Second draw: position + color - GL11.glBegin(GL11.GL_QUADS); - GL11.glColor4f(1, 0, 0, 1); - GL11.glVertex3f(2, 0, 0); - GL11.glColor4f(0, 1, 0, 1); - GL11.glVertex3f(3, 0, 0); - GL11.glColor4f(0, 0, 1, 1); - GL11.glVertex3f(3, 1, 0); - GL11.glColor4f(1, 1, 0, 1); - GL11.glVertex3f(2, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glColor4f(1, 0, 0, 1); + GLStateManager.glVertex3f(2, 0, 0); + GLStateManager.glColor4f(0, 1, 0, 1); + GLStateManager.glVertex3f(3, 0, 0); + GLStateManager.glColor4f(0, 0, 1, 1); + GLStateManager.glVertex3f(3, 1, 0); + GLStateManager.glColor4f(1, 1, 0, 1); + GLStateManager.glVertex3f(2, 1, 0); + GLStateManager.glEnd(); // Third draw: position + texture - GL11.glBegin(GL11.GL_QUADS); - GL11.glTexCoord2f(0, 0); - GL11.glVertex3f(4, 0, 0); - GL11.glTexCoord2f(1, 0); - GL11.glVertex3f(5, 0, 0); - GL11.glTexCoord2f(1, 1); - GL11.glVertex3f(5, 1, 0); - GL11.glTexCoord2f(0, 1); - GL11.glVertex3f(4, 1, 0); - GL11.glEnd(); + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glTexCoord2f(0, 0); + GLStateManager.glVertex3f(4, 0, 0); + GLStateManager.glTexCoord2f(1, 0); + GLStateManager.glVertex3f(5, 0, 0); + GLStateManager.glTexCoord2f(1, 1); + GLStateManager.glVertex3f(5, 1, 0); + GLStateManager.glTexCoord2f(0, 1); + GLStateManager.glVertex3f(4, 1, 0); + GLStateManager.glEnd(); GLStateManager.glEndList(); - // Call the list to ensure it doesn't crash (verifies compilation succeeded) + // Call the list and verify color is restored to last value from second draw (yellow) + // Third draw has no color, so doesn't affect GL_CURRENT_COLOR GLStateManager.glCallList(displayList); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 1f, 0f, 1f}, + "After playback, color should be yellow (last color from second draw)"); + } + + /** + * Verifies that color is properly restored after immediate mode VBO playback. + * After glCallList, GL_CURRENT_COLOR should be the last color set in the display list. + */ + @Test + void testColorRestoredAfterImmediateModeVBOPlayback() { + // Set initial color to white + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 1f, 1f, 1f}, "Initial color should be white"); + + // Create display list with immediate mode that sets color to BLUE (0, 0, 1, 1) + + displayList = GL11.glGenLists(1); + GLStateManager.glNewList(displayList, GL11.GL_COMPILE); + + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Blue + GLStateManager.glVertex3f(0, 0, 0); + GLStateManager.glVertex3f(1, 0, 0); + GLStateManager.glVertex3f(1, 1, 0); + GLStateManager.glVertex3f(0, 1, 0); + GLStateManager.glEnd(); + + GLStateManager.glEndList(); + + // Call the display list + GLStateManager.glCallList(displayList); + + // After playback, GL_CURRENT_COLOR should be blue (the last color in the display list) + // AND the GLSM cache should also be blue (synced with GL) + verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f}, + "After display list playback, color should be blue (last color in the list)"); + + // Now set color to red - this should ACTUALLY change the color + GLStateManager.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 0f, 0f, 1f}, + "After setting color to red, color should be red"); } } 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 index 4bee58c0b..be4c7e333 100644 --- 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 @@ -69,7 +69,7 @@ class GLSM_DisplayList_Primitive_Test { // Execute: Create AccumulatedPrimitiveDraw (should deep copy) AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0); + primitives, identity(), positionOnly(), 0, 0); // Modify original originalLine.setX(0, 999.0f); @@ -96,7 +96,7 @@ class GLSM_DisplayList_Primitive_Test { // Execute: Create AccumulatedPrimitiveDraw (should deep copy) AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0); + primitives, identity(), positionOnly(), 0, 0); // Modify original originalTri.setX(0, 999.0f); @@ -119,7 +119,7 @@ class GLSM_DisplayList_Primitive_Test { // Execute AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, identity(), positionOnly(), 0); + primitives, identity(), positionOnly(), 0, 0); // Verify: All primitives copied correctly assertEquals(4, draw.primitives.size(), "Should have 4 primitives (2 lines + 2 triangles)"); @@ -143,7 +143,7 @@ class GLSM_DisplayList_Primitive_Test { // Execute AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( - primitives, originalTransform, positionOnly(), 0); + primitives, originalTransform, positionOnly(), 0, 0); // Modify original transform originalTransform.identity(); @@ -475,11 +475,11 @@ class GLSM_DisplayList_Primitive_Test { List lines1 = new ArrayList<>(); lines1.add(createSimpleLine()); - primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0)); + 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)); + primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1, 1)); List commands = new ArrayList<>(); diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java index bfec809e0..9e1be587d 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java @@ -16,18 +16,7 @@ import java.nio.FloatBuffer; import static org.junit.jupiter.api.Assertions.*; -/** - * Tests for transform collapsing optimization in display lists. - * - *

    The optimization collapses consecutive MODELVIEW transforms into single MultMatrix - * commands, emitting them at "barriers" (draws, CallList, exit). These tests verify:

    - *
      - *
    • Consecutive transforms collapse to single MultMatrix
    • - *
    • Matrix state is correct after execution
    • - *
    • Push/Pop maintain proper stack semantics
    • - *
    • Barriers (draws, CallList) correctly flush pending transforms
    • - *
    - */ +/** Tests for transform collapsing optimization in display lists. */ @ExtendWith(AngelicaExtension.class) class GLSM_DisplayList_TransformCollapsing_Test { @@ -268,9 +257,14 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glEndList(); CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); - Int2IntMap counts = compiled.getCommandCounts(); - int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0); + // If compiled is null, the list is empty (correct - no commands needed) + // If compiled exists, verify no MultMatrix commands + int multMatrixCount = 0; + if (compiled != null) { + Int2IntMap counts = compiled.getCommandCounts(); + multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0); + } assertEquals(0, multMatrixCount, "Identity-equivalent transforms should not emit MultMatrix"); @@ -503,7 +497,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glEndList(); - // Verify the LoadMatrixCmd is present + // Verify the LOAD_MATRIX command is present CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); assertNotNull(compiled, "Display list should be compiled"); @@ -645,4 +639,320 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glPopMatrix(); } + + // ==================== Immediate Mode with Transforms Tests ==================== + + @Test + void testImmediateModeDrawCommandStructure() { + // Verifies MultMatrix emitted before DrawRange, push/pop ordering correct + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + + GLStateManager.glPushMatrix(); + GLStateManager.glScalef(0.25f, 0.25f, 0.25f); + + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(2.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(2.0f, 2.0f, 0.0f); + GLStateManager.glVertex3f(0.0f, 2.0f, 0.0f); + GLStateManager.glEnd(); + + GLStateManager.glPopMatrix(); + GLStateManager.glEndList(); + + CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); + assertNotNull(compiled); + + IntList opcodes = compiled.getCommandOpcodes(); + int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX); + int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX); + int multMatrixIndex = opcodes.indexOf(GLCommand.MULT_MATRIX); + int drawRangeIndex = opcodes.indexOf(GLCommand.DRAW_RANGE); + + assertTrue(pushIndex < multMatrixIndex, "Push before MultMatrix"); + assertTrue(multMatrixIndex < drawRangeIndex, "MultMatrix before DrawRange"); + assertTrue(drawRangeIndex < popIndex, "DrawRange before Pop"); + } + + @Test + void testImmediateModeDrawMatrixValues() { + // Verifies matrix values correct after playback with translate + scale + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + + GLStateManager.glTranslatef(100.0f, 50.0f, 0.0f); + GLStateManager.glScalef(0.5f, 0.5f, 1.0f); + + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(16.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(16.0f, 16.0f, 0.0f); + GLStateManager.glVertex3f(0.0f, 16.0f, 0.0f); + GLStateManager.glEnd(); + + GLStateManager.glEndList(); + + // Verify transforms collapsed + CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); + Int2IntMap counts = compiled.getCommandCounts(); + assertEquals(1, counts.getOrDefault(GLCommand.MULT_MATRIX, 0), "Translate+Scale -> 1 MultMatrix"); + assertEquals(0, counts.getOrDefault(GLCommand.TRANSLATE, 0), "No individual Translate"); + assertEquals(0, counts.getOrDefault(GLCommand.SCALE, 0), "No individual Scale"); + + // Verify matrix values after playback + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glCallList(testList); + + FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + + assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X"); + assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y"); + assertEquals(1.0f, matrixBuf.get(10), 0.0001f, "Scale Z"); + assertEquals(100.0f, matrixBuf.get(12), 0.0001f, "Translate X"); + assertEquals(50.0f, matrixBuf.get(13), 0.0001f, "Translate Y"); + + GLStateManager.glPopMatrix(); + } + + // ==================== Cross-Mode Transform Collapsing Tests ==================== + + @Test + void testTransformsAcrossMatrixModeSwitch() { + // Transforms must not leak across matrix mode boundaries + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + + // Execute directly via GL to get expected results + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glTranslatef(1.0f, 0.0f, 0.0f); + GL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GL11.glScalef(2.0f, 2.0f, 2.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glTranslatef(3.0f, 0.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GL11.glTranslatef(5.0f, 0.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + + FloatBuffer expectedMV = BufferUtils.createFloatBuffer(16); + FloatBuffer expectedProj = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedMV); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, expectedProj); + + // Reset and test via display list + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); + GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glScalef(2.0f, 2.0f, 2.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glTranslatef(3.0f, 0.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glEndList(); + + GLStateManager.glCallList(testList); + + FloatBuffer actualMV = BufferUtils.createFloatBuffer(16); + FloatBuffer actualProj = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualMV); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, actualProj); + + for (int i = 0; i < 16; i++) { + assertEquals(expectedMV.get(i), actualMV.get(i), 0.0001f, "MODELVIEW[" + i + "]"); + assertEquals(expectedProj.get(i), actualProj.get(i), 0.0001f, "PROJECTION[" + i + "]"); + } + + // Cleanup + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + @Test + void testBarrierCommandsBetweenScaleAndDraw() { + // State commands between transform and draw must not break transform capture + for (int mode : new int[]{GL11.GL_COMPILE, GL11.GL_COMPILE_AND_EXECUTE}) { + if (testList > 0) { + GLStateManager.glDeleteLists(testList, 1); + } + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, mode); + + GLStateManager.glScalef(0.5f, 0.5f, 1.0f); + // Barrier commands between scale and draw + GLStateManager.glDepthMask(true); + GLStateManager.disableLighting(); + GLStateManager.enableTexture(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(1.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(1.0f, 1.0f, 0.0f); + GLStateManager.glVertex3f(0.0f, 1.0f, 0.0f); + GLStateManager.glEnd(); + + GLStateManager.glEndList(); + + CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); + assertNotNull(compiled); + + Int2IntMap counts = compiled.getCommandCounts(); + assertEquals(1, counts.getOrDefault(GLCommand.MULT_MATRIX, 0), "1 MultMatrix for mode " + mode); + assertEquals(1, counts.getOrDefault(GLCommand.DRAW_RANGE, 0), "1 DrawRange for mode " + mode); + + IntList opcodes = compiled.getCommandOpcodes(); + assertTrue(opcodes.indexOf(GLCommand.MULT_MATRIX) < opcodes.indexOf(GLCommand.DRAW_RANGE), + "MultMatrix before DrawRange for mode " + mode); + + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glCallList(testList); + + FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X for mode " + mode); + assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y for mode " + mode); + + GLStateManager.glPopMatrix(); + } + } + + // ==================== Optimizer Push/Pop Reset Tests ==================== + + @Test + void testOptimizerResetsAfterPushMatrix() { + // Optimizer must reset after PUSH_MATRIX to avoid spurious inverse transform emission + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + + // T1: transforms before push (collapsed) + GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); + GLStateManager.glScalef(2.0f, 2.0f, 2.0f); + + GLStateManager.glPushMatrix(); + + // T2: transforms after push (collapsed separately) + GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); + GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f); + + GLStateManager.glBegin(GL11.GL_QUADS); + GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(1.0f, 0.0f, 0.0f); + GLStateManager.glVertex3f(1.0f, 1.0f, 0.0f); + GLStateManager.glVertex3f(0.0f, 1.0f, 0.0f); + GLStateManager.glEnd(); + + GLStateManager.glPopMatrix(); + GLStateManager.glEndList(); + + CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList); + assertNotNull(compiled); + + Int2IntMap counts = compiled.getCommandCounts(); + IntList opcodes = compiled.getCommandOpcodes(); + + // Should have exactly 2 MULT_MATRIX (T1 before push, T2 after push) + // Bug would produce 3 (T1, T2, spurious T1^-1) + assertEquals(2, counts.getOrDefault(GLCommand.MULT_MATRIX, 0), + "2 MULT_MATRIX expected (T1 before push, T2 after push)"); + + // Verify ordering + int firstMultMatrix = opcodes.indexOf(GLCommand.MULT_MATRIX); + int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX); + int drawIndex = opcodes.indexOf(GLCommand.DRAW_RANGE); + int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX); + + assertTrue(firstMultMatrix < pushIndex, "T1 before PUSH"); + assertTrue(pushIndex < drawIndex, "PUSH before DRAW"); + assertTrue(drawIndex < popIndex, "DRAW before POP"); + + // Verify final matrix after pop = T1 + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glCallList(testList); + + FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + + assertEquals(2.0f, matrixBuf.get(0), 0.0001f, "Scale X after pop"); + assertEquals(2.0f, matrixBuf.get(5), 0.0001f, "Scale Y after pop"); + assertEquals(5.0f, matrixBuf.get(12), 0.0001f, "Translate X after pop"); + + GLStateManager.glPopMatrix(); + } + + @Test + void testTransformCollapsingEquivalence() { + // Core equivalence test: verify that collapsed transforms produce + // the exact same result as executing transforms sequentially. + // + // This tests the fundamental invariant of the optimization. + // Use axis-aligned rotations to minimize float/double precision differences. + + // Transform sequence: translate, rotate around Y, scale, rotate around X, translate + final float tx1 = 5.0f, ty1 = 3.0f, tz1 = -2.0f; + final float angle1 = 45.0f; + final float sx = 1.5f, sy = 0.8f, sz = 2.0f; + final float angle2 = 30.0f; + final float tx2 = -1.0f, ty2 = 4.0f, tz2 = 0.5f; + + // Execute directly via GL + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GL11.glTranslatef(tx1, ty1, tz1); + GL11.glRotatef(angle1, 0.0f, 1.0f, 0.0f); // Y-axis rotation + GL11.glScalef(sx, sy, sz); + GL11.glRotatef(angle2, 1.0f, 0.0f, 0.0f); // X-axis rotation + GL11.glTranslatef(tx2, ty2, tz2); + + FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedBuf); + + // Reset and execute via display list + GLStateManager.glLoadIdentity(); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + GLStateManager.glTranslatef(tx1, ty1, tz1); + GLStateManager.glRotatef(angle1, 0.0f, 1.0f, 0.0f); + GLStateManager.glScalef(sx, sy, sz); + GLStateManager.glRotatef(angle2, 1.0f, 0.0f, 0.0f); + GLStateManager.glTranslatef(tx2, ty2, tz2); + GLStateManager.glEndList(); + + GLStateManager.glCallList(testList); + + FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + + // Verify equivalence + for (int i = 0; i < 16; i++) { + assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f, + String.format("Matrix[%d]: collapsed transform must equal sequential execution", i)); + } + + GLStateManager.glLoadIdentity(); + } } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java index 6381dbae9..2d364ed02 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java @@ -17,6 +17,8 @@ import org.lwjgl.opengl.GL32; import java.nio.FloatBuffer; import java.util.ArrayList; +import static org.junit.jupiter.api.Assertions.assertEquals; + import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState; import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyIsEnabled; import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState; @@ -869,4 +871,307 @@ class GLSM_PushPop_UnitTest { GLStateManager.glPopAttrib(); verifyIsEnabled(GL11.GL_BLEND, false, "Blend - After pop to depth 0"); } + + // ==================== Display List + Push/Pop Interaction Tests ==================== + + @Test + void testDisplayListCallInsidePushPopAllAttribBits() { + // Tests the pattern: + // 1. Push ALL attrib bits + // 2. Switch to TEXTURE1, enable GL_TEXTURE_2D + // 3. Switch back to TEXTURE0 + // 4. Call a display list that changes texture state + // 5. Pop attrib + // 6. Verify state restored correctly + // + // This pattern is used by mods that wrap vanilla entity rendering. + + // Setup: create textures and verify initial state + final int texA = GL11.glGenTextures(); + final int texB = GL11.glGenTextures(); + final int texC = GL11.glGenTextures(); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "Initial binding unit 0"); + verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "Initial active unit"); + + // Verify unit 1 starts with no texture and TEXTURE_2D disabled + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "Initial binding unit 1"); + verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "Initial TEXTURE_2D state unit 1"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + // Create display list that changes texture state on multiple units + final int listId = GL11.glGenLists(1); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texC); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glEndList(); + + // === Begin pattern === + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + + // Switch to TEXTURE1, enable GL_TEXTURE_2D, switch back + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "TEXTURE_2D enabled on unit 1"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + // Call display list (simulates calling vanilla model/entity display lists) + DisplayListManager.glCallList(listId); + + // Verify state changed by display list + verifyState(GL11.GL_TEXTURE_BINDING_2D, texB, "After display list - unit 0 binding"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texC, "After display list - unit 1 binding"); + verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After display list - TEXTURE_2D still enabled on unit 1"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + // Pop attrib - should restore all state + GLStateManager.glPopAttrib(); + + // === CRITICAL VERIFICATIONS === + // If any of these fail, we've found the bug + + // Active texture unit should be restored + verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "After pop - active unit"); + + // Unit 0 binding should be restored to texA + verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After pop - unit 0 binding"); + + // Unit 1 state should be fully restored + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After pop - unit 1 binding"); + verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - TEXTURE_2D disabled on unit 1"); + + // Cleanup - reset all state to defaults + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texA); + GLStateManager.glDeleteTextures(texB); + GLStateManager.glDeleteTextures(texC); + GLStateManager.glDeleteLists(listId, 1); + } + + @Test + void testDisplayListWithNestedPushPopInsideOuterPushPop() { + // Tests nested push/pop where the display list itself contains push/pop + // Pattern: + // glPushAttrib(ALL) + // glCallList(...) // list contains: glPushAttrib, change state, glPopAttrib + // glPopAttrib() + + final int texA = GL11.glGenTextures(); + final int texB = GL11.glGenTextures(); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "Initial binding"); + + // Create display list with its own push/pop + final int listId = GL11.glGenLists(1); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); + GLStateManager.glPushAttrib(GL11.GL_TEXTURE_BIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB); + GLStateManager.glPopAttrib(); + GLStateManager.glEndList(); + + // Outer push + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + + // Change texture + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After unbind in outer push"); + + // Call display list with nested push/pop + DisplayListManager.glCallList(listId); + + // After display list's pop, should be back to 0 (what outer context had) + verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After display list with nested push/pop"); + + // Outer pop + GLStateManager.glPopAttrib(); + + // Should restore to original texA + verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After outer pop"); + + // Cleanup - reset state to defaults + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texA); + GLStateManager.glDeleteTextures(texB); + GLStateManager.glDeleteLists(listId, 1); + } + + @Test + void testTextureUnitSwitchingWithDisplayListModifyingDifferentUnit() { + // Tests: outer code works on unit 1, display list modifies unit 0 + // Verifies both units are correctly restored after pop + + final int texA = GL11.glGenTextures(); + final int texB = GL11.glGenTextures(); + final int texC = GL11.glGenTextures(); + + // Initial state: texA on unit 0, nothing on unit 1 + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA); + + // Create display list that only modifies unit 0 + final int listId = GL11.glGenLists(1); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texC); + GLStateManager.glEndList(); + + // Push, then work on unit 1 + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + + // Call display list - modifies unit 0 while we're "on" unit 1 + DisplayListManager.glCallList(listId); + + // Verify: unit 0 changed, unit 1 unchanged + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texC, "After list - unit 0 changed to texC"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texB, "After list - unit 1 still texB"); + verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After list - unit 1 still enabled"); + + // Pop + GLStateManager.glPopAttrib(); + + // Both units should be restored + verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "After pop - active unit"); + verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After pop - unit 0 restored to texA"); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After pop - unit 1 restored to 0"); + verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - unit 1 disabled"); + + // Cleanup - reset all state to defaults + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texA); + GLStateManager.glDeleteTextures(texB); + GLStateManager.glDeleteTextures(texC); + GLStateManager.glDeleteLists(listId, 1); + } + + @Test + void testColorStateWithDisplayListInsidePushPop() { + // Tests color state restoration - white screen could indicate color issue + // Pattern: push, set color, call display list that changes color, pop + + verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "Initial color white"); + + // Create display list that sets color to red + final int listId = GL11.glGenLists(1); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); + GLStateManager.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); + GLStateManager.glEndList(); + + // Push (note: GL_CURRENT_BIT includes color) + GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT); + + // Set color to green + GLStateManager.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{0.0f, 1.0f, 0.0f, 1.0f}, "After setting green"); + + // Call display list - sets to red + DisplayListManager.glCallList(listId); + verifyState(GL11.GL_CURRENT_COLOR, new float[]{1.0f, 0.0f, 0.0f, 1.0f}, "After display list - red"); + + // Pop - should restore to white (initial state before push) + GLStateManager.glPopAttrib(); + verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "After pop - restored to white"); + + // Cleanup - ensure color is reset to white + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glDeleteLists(listId, 1); + } + + @Test + void testBlendStateWithDisplayListInsidePushPop() { + // Tests blend state restoration - incorrect blend could cause visual issues + + verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "color should still be white"); + + verifyIsEnabled(GL11.GL_BLEND, false, "Initial blend disabled"); + verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "Initial blend src"); + verifyState(GL11.GL_BLEND_DST, GL11.GL_ZERO, "Initial blend dst"); + + // Create display list that enables blend with specific function + final int listId = GL11.glGenLists(1); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); + GLStateManager.glEndList(); + + // Push + GLStateManager.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT); + + // Set different blend state + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + // Call display list - changes blend function + DisplayListManager.glCallList(listId); + verifyIsEnabled(GL11.GL_BLEND, true, "After list - blend enabled"); + verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "After list - blend src ONE"); + verifyState(GL11.GL_BLEND_DST, GL11.GL_ONE, "After list - blend dst ONE"); + + // Pop + GLStateManager.glPopAttrib(); + verifyIsEnabled(GL11.GL_BLEND, false, "After pop - blend disabled"); + verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "After pop - blend src restored"); + verifyState(GL11.GL_BLEND_DST, GL11.GL_ZERO, "After pop - blend dst restored"); + + // Cleanup - ensure blend is reset to defaults + GLStateManager.disableBlend(); + GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO); + GLStateManager.glDeleteLists(listId, 1); + + // Verify GLSM cache matches actual GL state (exposes cache sync bugs) + verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "color should still be white"); + } + + @Test + void testTextureUnitPopAttribRestoresCorrectUnit() { + // Setup: Unit 0 ENABLED, Unit 1 disabled + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "Initial - Unit 0 enabled"); + + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + + // Modify ONLY unit 1 + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + GLStateManager.glPopAttrib(); + + // Unit 0 should still be enabled - bug causes it to be disabled + verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After pop - Unit 0 still enabled"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - Unit 1 disabled"); + + // Cleanup + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + } }