Display List Overhaul (#1200)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2025-12-24 20:30:48 -08:00
1 parent d3366ad31a
commit ee6c79802a
46 files changed
+3795 -1671

No files matched your search

@@ -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<CapturingTessellator.Flags, CompiledFormatBuffer> 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<CapturingTessellator.Flags, CompiledFormatBuffer> 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<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Collect per-draw ranges (no merging) sorted by command index
final List<DrawRangeWithBuffer> 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<DrawRangeWithBuffer> collectDrawRanges(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, true);
}
/** Collect unmerged draw ranges for debug mode. */
static List<DrawRangeWithBuffer> collectDrawRangesUnoptimized(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, false);
}
private static List<DrawRangeWithBuffer> collectDrawRangesInternal(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
boolean useMerged) {
final List<DrawRangeWithBuffer> 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<VertexBuffer> 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());
}
}
}
@@ -14,7 +14,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
* </ul>
*/
@Desugar
record CompiledLineBuffer(
public record CompiledLineBuffer(
VertexBuffer vbo,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
@@ -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,
File diff suppressed because it is too large. Load diff
@@ -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.
*
* <p>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);
}
}
@@ -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;
}
}
}
@@ -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.
* <p>
* Tracks two types of ranges:
* <ul>
* <li><b>mergedRanges</b>: Consecutive same-transform draws merged for optimized path</li>
* <li><b>perDrawRanges</b>: One range per input draw for unoptimized path (1:1 with addDraw calls)</li>
* </ul>
* 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();
File diff suppressed because it is too large. Load diff
@@ -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;
}
}
@@ -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<DrawRange> 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;
}
}
@@ -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:
* <ul>
* <li>accumulated: total relative transform (what GL matrix should be)</li>
@@ -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() {
@@ -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<String> LINE_LOGGER = LOGGER::debug;
private static final Set<String> 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);
@@ -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<ModelQuadViewMutable> 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<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) {
this(quads, transform, flags, commandIndex, matrixGeneration, 0, null);
}
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) {
this(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration, null);
}
public AccumulatedDraw(List<ModelQuadViewMutable> 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");
}
}
@@ -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<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
this(lines, transform, flags, commandIndex, 0);
}
public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> 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
@@ -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<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) {
this(primitives, transform, flags, commandIndex, matrixGeneration, 0);
}
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> 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);
}
@@ -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);
@@ -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;
@@ -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.
*
* <p>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).</p>
*/
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<Matrix4f> 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);
}
@@ -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++;
}
@@ -22,6 +22,12 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
* <p>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;
}
@@ -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 + ")";
};
@@ -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<ModelQuadViewMutable> quads, List<LineVertex> lines, CapturingTessellator.Flags flags) {}
public record Result(
List<ModelQuadViewMutable> quads,
List<LineVertex> 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.
@@ -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
}
}
@@ -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 + ")";
}
}
@@ -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.
*
* <p>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).</p>
*
* <p>Commands like PushAttribCmd with only GL_COLOR_BUFFER_BIT don't need
* transform sync because they don't interact with the matrix stack.</p>
*
* @return true if transform must be synced to accumulated before this barrier
*/
default boolean needsTransformSync() {
return false;
}
/**
* Handle this command during display list optimization.
*
@@ -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));
}
}
@@ -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.
*
* <p>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.</p>
*/
@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);
}
}
@@ -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);
}
@@ -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()";
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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;
}
}
@@ -27,13 +27,11 @@ public class BooleanState implements ISettableState<BooleanState> {
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);
}
}
}
@@ -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];
}