Support lines and triangles in tessellator & cleanup allocs (#222)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2025-12-05 15:50:06 -08:00
1 parent 628c003e3e
commit 542a1b051c
13 files changed
+2223 -238

No files matched your search

@@ -1,28 +0,0 @@
package com.gtnewhorizon.gtnhlib.client.renderer;
import java.util.List;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
/**
* Represents a single draw call captured during CAPTURING mode. Contains the quads and flags from that specific draw()
* call.
*/
public class CapturedDraw {
private final List<ModelQuadViewMutable> quads;
private final CapturingTessellator.Flags flags;
public CapturedDraw(List<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags) {
this.quads = quads;
this.flags = flags;
}
public List<ModelQuadViewMutable> quads() {
return quads;
}
public CapturingTessellator.Flags flags() {
return flags;
}
}
@@ -9,6 +9,7 @@ import static net.minecraft.util.MathHelper.clamp_int;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -18,10 +19,14 @@ import net.minecraft.client.renderer.Tessellator;
import org.joml.Matrix3f;
import org.joml.Vector3f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.Vector3dStack;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizon.gtnhlib.util.ObjectPooler;
@@ -35,8 +40,32 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@SuppressWarnings("unused")
public class CapturingTessellator extends Tessellator implements ITessellatorInstance {
final ObjectPooler<ModelQuad> quadBuf = new ObjectPooler<>(ModelQuad::new);
// Object pools reduce allocations over time by reusing primitive instances across multiple
// capture sessions. Not meant to avoid allocations within a single call, but to amortize
// allocation costs across the lifetime of the CapturingTessellator.
final ObjectPooler<ModelQuad> quadPool = new ObjectPooler<>(ModelQuad::new);
final ObjectPooler<ModelTriangle> triPool = new ObjectPooler<>(ModelTriangle::new);
final ObjectPooler<ModelLine> linePool = new ObjectPooler<>(ModelLine::new);
/**
* Stores ModelQuad objects for GL_QUADS and GL_TRIANGLES draw modes. Triangles are stored as "degenerate quads" via
* quadrangulation (v2 duplicated to v3) for backward compatibility with code expecting all geometry in this list.
* Populated by QuadExtractor.
*/
final List<ModelQuadViewMutable> collectedQuads = new ObjectArrayList<>();
/**
* Stores primitives from other draw modes: GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP (as ModelLine), GL_TRIANGLE_STRIP,
* GL_TRIANGLE_FAN (as ModelTriangle). These are converted to their base primitive types. Populated by
* PrimitiveExtractor.
*/
final List<ModelPrimitiveView> collectedPrimitives = new ObjectArrayList<>();
// Reusable lists for stopCapturingToGeometry to avoid allocations
final List<ModelLine> lineListCache = new ArrayList<>();
final List<ModelTriangle> triangleListCache = new ArrayList<>();
final List<ModelQuad> quadListCache = new ArrayList<>();
int shaderBlockId = -1;
// Any offset we need to the Tesselator's offset!
@@ -82,15 +111,34 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
return collectedQuads;
}
public List<ModelPrimitiveView> getPrimitives() {
return collectedPrimitives;
}
public void clearQuads() {
// noinspection ForLoopReplaceableByForEach
for (int i = 0; i < collectedQuads.size(); i++) {
final var quad = collectedQuads.get(i);
if (quad instanceof ModelQuad mq) quadBuf.releaseInstance(mq);
if (quad instanceof ModelQuad mq) quadPool.releaseInstance(mq);
}
collectedQuads.clear();
}
public void clearPrimitives() {
// noinspection ForLoopReplaceableByForEach
for (int i = 0; i < collectedPrimitives.size(); i++) {
final var prim = collectedPrimitives.get(i);
if (prim instanceof ModelQuad mq) {
quadPool.releaseInstance(mq);
} else if (prim instanceof ModelTriangle mt) {
triPool.releaseInstance(mt);
} else if (prim instanceof ModelLine ml) {
linePool.releaseInstance(ml);
}
}
collectedPrimitives.clear();
}
public static ByteBuffer quadsToBuffer(List<ModelQuadViewMutable> quads, VertexFormat format) {
if (!format.canWriteQuads()) {
throw new IllegalStateException("Vertex format has no quad writer: " + format);
@@ -242,6 +290,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
public boolean hasBrightness;
public boolean hasColor;
public boolean hasNormals;
public int drawMode = GL11.GL_QUADS;
public Flags(boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals) {
this.hasTexture = hasTexture;
@@ -258,6 +307,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
this.hasBrightness = other.hasBrightness;
this.hasColor = other.hasColor;
this.hasNormals = other.hasNormals;
this.drawMode = other.drawMode;
}
/**
@@ -270,18 +320,31 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
this.hasNormals = hasNormals;
}
/**
* Updates this Flags instance with new values including draw mode.
*/
public void copyFrom(boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals,
int drawMode) {
this.hasTexture = hasTexture;
this.hasBrightness = hasBrightness;
this.hasColor = hasColor;
this.hasNormals = hasNormals;
this.drawMode = drawMode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Flags flags)) return false;
return hasTexture == flags.hasTexture && hasBrightness == flags.hasBrightness
&& hasColor == flags.hasColor
&& hasNormals == flags.hasNormals;
&& hasNormals == flags.hasNormals
&& drawMode == flags.drawMode;
}
@Override
public int hashCode() {
return Objects.hash(hasTexture, hasBrightness, hasColor, hasNormals);
return Objects.hash(hasTexture, hasBrightness, hasColor, hasNormals, drawMode);
}
}
@@ -2,6 +2,7 @@ package com.gtnewhorizon.gtnhlib.client.renderer;
import java.util.List;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
/**
@@ -10,11 +11,20 @@ import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMuta
public interface DrawCallback {
/**
* Called after each Tessellator.draw() during compiling mode. The quads are pooled objects - caller MUST copy them
* if needed beyond this call. After this callback returns, the quads will be released back to the pool.
* Called after each Tessellator.draw() during compiling mode. The quads and primitives are pooled objects - caller
* MUST copy them if needed beyond this call. After this callback returns, they will be released back to the pool.
* <p>
* For any single draw call, typically only one list will have content:
* <ul>
* <li>GL_QUADS → quads list (as ModelQuad)</li>
* <li>GL_TRIANGLES → primitives list (as ModelTriangle)</li>
* <li>GL_LINES, GL_LINE_STRIP, etc. → primitives list (as ModelLine/ModelTriangle)</li>
* </ul>
*
* @param quads The quads from this specific draw call (sublist of collected quads)
* @param flags The tessellator flags (hasTexture, hasBrightness, hasColor, hasNormals) from this draw call
* @param quads The quads from GL_QUADS draw calls
* @param primitives The primitives from GL_TRIANGLES, GL_LINES, and other draw modes
* @param flags The tessellator flags (hasTexture, hasBrightness, hasColor, hasNormals, drawMode)
*/
void onDraw(List<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags);
void onDraw(List<ModelQuadViewMutable> quads, List<ModelPrimitiveView> primitives,
CapturingTessellator.Flags flags);
}
@@ -0,0 +1,409 @@
package com.gtnewhorizon.gtnhlib.client.renderer;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.util.ObjectPooler;
/**
* Utility class for extracting primitives (lines, triangles, quads) from Tessellator raw buffers. Supports GL_QUADS,
* GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN.
*/
public final class PrimitiveExtractor {
private static final Logger LOGGER = LogManager.getLogger("PrimitiveExtractor");
private PrimitiveExtractor() {}
/**
* Builds primitives from a Tessellator's raw buffer based on draw mode. Quads are extracted as ModelQuad objects.
*/
public static void buildPrimitivesFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture,
boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelQuad> quadPool, ObjectPooler<ModelTriangle> triPool,
ObjectPooler<ModelLine> linePool, List<ModelPrimitiveView> collectedPrimitives,
CapturingTessellator.Flags flags) {
buildPrimitivesFromBuffer(
rawBuffer,
vertexCount,
drawMode,
hasTexture,
hasBrightness,
hasColor,
hasNormals,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
quadPool,
triPool,
linePool,
collectedPrimitives,
flags,
false);
}
/**
* Builds primitives from a Tessellator's raw buffer based on draw mode.
*
* @param convertQuadsToTriangles If true, GL_QUADS are converted to GL_TRIANGLES (2 triangles per quad). Useful for
* modern OpenGL compatibility since GL_QUADS is deprecated in 3.1+.
*/
public static void buildPrimitivesFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture,
boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelQuad> quadPool, ObjectPooler<ModelTriangle> triPool,
ObjectPooler<ModelLine> linePool, List<ModelPrimitiveView> collectedPrimitives,
CapturingTessellator.Flags flags, boolean convertQuadsToTriangles) {
flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals, drawMode);
switch (drawMode) {
case GL11.GL_QUADS:
if (convertQuadsToTriangles) {
extractQuadsAsTriangles(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
triPool,
collectedPrimitives,
flags);
flags.drawMode = GL11.GL_TRIANGLES;
} else {
extractQuads(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
quadPool,
collectedPrimitives,
flags);
}
break;
case GL11.GL_TRIANGLES:
extractTriangles(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
triPool,
collectedPrimitives,
flags);
break;
case GL11.GL_LINES:
extractLines(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
linePool,
collectedPrimitives);
break;
case GL11.GL_LINE_STRIP:
extractLineStrip(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
linePool,
collectedPrimitives);
flags.drawMode = GL11.GL_LINES; // Converted to individual lines
break;
case GL11.GL_LINE_LOOP:
extractLineLoop(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
linePool,
collectedPrimitives);
flags.drawMode = GL11.GL_LINES;
break;
case GL11.GL_TRIANGLE_STRIP:
extractTriangleStrip(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
triPool,
collectedPrimitives,
flags);
flags.drawMode = GL11.GL_TRIANGLES;
break;
case GL11.GL_TRIANGLE_FAN:
extractTriangleFan(
rawBuffer,
vertexCount,
offsetX,
offsetY,
offsetZ,
shaderBlockId,
triPool,
collectedPrimitives,
flags);
flags.drawMode = GL11.GL_TRIANGLES;
break;
default:
LOGGER.warn(
"Unsupported draw mode: 0x{} ({} vertices) - primitives will not be captured",
Integer.toHexString(drawMode),
vertexCount);
break;
}
}
// ==================== QUADS ====================
private static void extractQuads(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelQuad> quadPool, List<ModelPrimitiveView> collected,
CapturingTessellator.Flags flags) {
final int numQuads = vertexCount / 4;
for (int i = 0; i < numQuads; i++) {
final int srcOffset = i * 4 * VERTEX_SIZE;
if (isEmptyPrimitive(rawBuffer, srcOffset, 4)) continue;
final ModelQuad quad = quadPool.getInstance();
quad.setState(rawBuffer, srcOffset, flags, GL11.GL_QUADS, offsetX, offsetY, offsetZ);
quad.setShaderBlockId(shaderBlockId);
collected.add(quad);
}
}
/**
* Converts quads to triangles. Each quad (v0,v1,v2,v3) becomes 2 triangles: (v0,v1,v2) and (v0,v2,v3).
*/
private static void extractQuadsAsTriangles(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelTriangle> triPool, List<ModelPrimitiveView> collected,
CapturingTessellator.Flags flags) {
final int numQuads = vertexCount / 4;
for (int i = 0; i < numQuads; i++) {
final int srcOffset = i * 4 * VERTEX_SIZE;
if (isEmptyPrimitive(rawBuffer, srcOffset, 4)) continue;
// Triangle 1: v0, v1, v2
final ModelTriangle tri1 = triPool.getInstance();
copyVertexToTriangle(rawBuffer, srcOffset + 0 * VERTEX_SIZE, tri1, 0);
copyVertexToTriangle(rawBuffer, srcOffset + 1 * VERTEX_SIZE, tri1, 1);
copyVertexToTriangle(rawBuffer, srcOffset + 2 * VERTEX_SIZE, tri1, 2);
if (!flags.hasColor) setDefaultTriangleColors(tri1);
tri1.setShaderBlockId(shaderBlockId);
tri1.applyOffset(offsetX, offsetY, offsetZ);
collected.add(tri1);
// Triangle 2: v0, v2, v3
final ModelTriangle tri2 = triPool.getInstance();
copyVertexToTriangle(rawBuffer, srcOffset + 0 * VERTEX_SIZE, tri2, 0);
copyVertexToTriangle(rawBuffer, srcOffset + 2 * VERTEX_SIZE, tri2, 1);
copyVertexToTriangle(rawBuffer, srcOffset + 3 * VERTEX_SIZE, tri2, 2);
if (!flags.hasColor) setDefaultTriangleColors(tri2);
tri2.setShaderBlockId(shaderBlockId);
tri2.applyOffset(offsetX, offsetY, offsetZ);
collected.add(tri2);
}
}
// ==================== TRIANGLES ====================
private static void extractTriangles(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelTriangle> triPool, List<ModelPrimitiveView> collected,
CapturingTessellator.Flags flags) {
final int numTris = vertexCount / 3;
for (int i = 0; i < numTris; i++) {
final int srcOffset = i * 3 * VERTEX_SIZE;
if (isEmptyPrimitive(rawBuffer, srcOffset, 3)) continue;
final ModelTriangle tri = triPool.getInstance();
tri.setState(rawBuffer, srcOffset, flags);
tri.setShaderBlockId(shaderBlockId);
tri.applyOffset(offsetX, offsetY, offsetZ);
collected.add(tri);
}
}
private static void extractTriangleStrip(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelTriangle> triPool, List<ModelPrimitiveView> collected,
CapturingTessellator.Flags flags) {
if (vertexCount < 3) return;
// Triangle strip: N vertices → N-2 triangles
// Even triangles: [i, i+1, i+2]
// Odd triangles: [i+1, i, i+2] (reversed winding)
for (int i = 0; i < vertexCount - 2; i++) {
final ModelTriangle tri = triPool.getInstance();
int v0, v1, v2;
if ((i & 1) == 0) {
v0 = i;
v1 = i + 1;
v2 = i + 2;
} else {
v0 = i + 1;
v1 = i;
v2 = i + 2;
}
copyVertexToTriangle(rawBuffer, v0 * VERTEX_SIZE, tri, 0);
copyVertexToTriangle(rawBuffer, v1 * VERTEX_SIZE, tri, 1);
copyVertexToTriangle(rawBuffer, v2 * VERTEX_SIZE, tri, 2);
if (!flags.hasColor) setDefaultTriangleColors(tri);
tri.setShaderBlockId(shaderBlockId);
tri.applyOffset(offsetX, offsetY, offsetZ);
collected.add(tri);
}
}
private static void extractTriangleFan(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelTriangle> triPool, List<ModelPrimitiveView> collected,
CapturingTessellator.Flags flags) {
if (vertexCount < 3) return;
// Triangle fan: All triangles share vertex 0
// Triangle i uses vertices [0, i+1, i+2]
for (int i = 0; i < vertexCount - 2; i++) {
final ModelTriangle tri = triPool.getInstance();
copyVertexToTriangle(rawBuffer, 0, tri, 0); // Center vertex
copyVertexToTriangle(rawBuffer, (i + 1) * VERTEX_SIZE, tri, 1);
copyVertexToTriangle(rawBuffer, (i + 2) * VERTEX_SIZE, tri, 2);
if (!flags.hasColor) setDefaultTriangleColors(tri);
tri.setShaderBlockId(shaderBlockId);
tri.applyOffset(offsetX, offsetY, offsetZ);
collected.add(tri);
}
}
// ==================== LINES ====================
private static void extractLines(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelLine> linePool, List<ModelPrimitiveView> collected) {
final int numLines = vertexCount / 2;
for (int i = 0; i < numLines; i++) {
final int srcOffset = i * 2 * VERTEX_SIZE;
if (isEmptyPrimitive(rawBuffer, srcOffset, 2)) continue;
final ModelLine line = linePool.getInstance();
line.setState(rawBuffer, srcOffset);
line.setShaderBlockId(shaderBlockId);
line.applyOffset(offsetX, offsetY, offsetZ);
collected.add(line);
}
}
private static void extractLineStrip(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelLine> linePool, List<ModelPrimitiveView> collected) {
if (vertexCount < 2) return;
// Line strip: N vertices → N-1 lines
for (int i = 0; i < vertexCount - 1; i++) {
final ModelLine line = linePool.getInstance();
copyVertexToLine(rawBuffer, i * VERTEX_SIZE, line, 0);
copyVertexToLine(rawBuffer, (i + 1) * VERTEX_SIZE, line, 1);
line.setShaderBlockId(shaderBlockId);
line.applyOffset(offsetX, offsetY, offsetZ);
collected.add(line);
}
}
private static void extractLineLoop(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelLine> linePool, List<ModelPrimitiveView> collected) {
if (vertexCount < 2) return;
// Line loop: Like strip + closing segment (but don't recurse - apply offsets inline)
for (int i = 0; i < vertexCount - 1; i++) {
final ModelLine line = linePool.getInstance();
copyVertexToLine(rawBuffer, i * VERTEX_SIZE, line, 0);
copyVertexToLine(rawBuffer, (i + 1) * VERTEX_SIZE, line, 1);
line.setShaderBlockId(shaderBlockId);
line.applyOffset(offsetX, offsetY, offsetZ);
collected.add(line);
}
// Add closing segment (last → first)
final ModelLine closingLine = linePool.getInstance();
copyVertexToLine(rawBuffer, (vertexCount - 1) * VERTEX_SIZE, closingLine, 0);
copyVertexToLine(rawBuffer, 0, closingLine, 1);
closingLine.setShaderBlockId(shaderBlockId);
closingLine.applyOffset(offsetX, offsetY, offsetZ);
collected.add(closingLine);
}
// ==================== HELPERS ====================
/**
* Copies a vertex from raw buffer to triangle. Delegates to ModelTriangle's optimized copy method.
*/
private static void copyVertexToTriangle(int[] rawBuffer, int srcOffset, ModelTriangle tri, int destIdx) {
tri.copyVertexFromBuffer(rawBuffer, srcOffset, destIdx);
}
/**
* Copies a vertex from raw buffer to line. Delegates to ModelLine's optimized copy method.
*/
private static void copyVertexToLine(int[] rawBuffer, int srcOffset, ModelLine line, int destIdx) {
line.copyVertexFromBuffer(rawBuffer, srcOffset, destIdx);
}
private static void setDefaultTriangleColors(ModelTriangle tri) {
tri.setColor(0, DEFAULT_COLOR);
tri.setColor(1, DEFAULT_COLOR);
tri.setColor(2, DEFAULT_COLOR);
}
/**
* Check if a primitive is degenerate (all vertices at the same position). Also returns true if buffer is malformed
* (insufficient size) to prevent ArrayIndexOutOfBoundsException.
*/
static boolean isEmptyPrimitive(int[] rawBuffer, int srcOffset, int vertexCount) {
// Bounds check: need srcOffset + (vertexCount-1)*VERTEX_SIZE + 2 (for Z axis)
final int requiredSize = srcOffset + (vertexCount - 1) * VERTEX_SIZE + 3; // +3 for X,Y,Z of last vertex
if (requiredSize > rawBuffer.length) return true; // Treat malformed buffer as empty
for (int axis = 0; axis < 3; axis++) {
final int firstVal = rawBuffer[srcOffset + axis];
for (int v = 1; v < vertexCount; v++) {
if (firstVal != rawBuffer[srcOffset + v * VERTEX_SIZE + axis]) {
return false;
}
}
}
return true;
}
}
@@ -1,7 +1,11 @@
package com.gtnewhorizon.gtnhlib.client.renderer;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
@@ -14,7 +18,7 @@ import com.gtnewhorizon.gtnhlib.util.ObjectPooler;
*/
public final class QuadExtractor {
private static final int VERTEX_STRIDE = 8; // ints per vertex in Tessellator raw buffer
private static final Logger LOGGER = LogManager.getLogger("QuadExtractor");
private QuadExtractor() {
// Utility class - no instantiation
@@ -35,46 +39,40 @@ public final class QuadExtractor {
* @param offsetY Y offset to apply to all vertices
* @param offsetZ Z offset to apply to all vertices
* @param shaderBlockId Shader block ID to assign to quads
* @param quadBuf Object pooler for ModelQuad instances
* @param quadPool Object pooler for ModelQuad instances
* @param collectedQuads List to add extracted quads to
* @param flags Flags object to update with vertex format information
*/
public static void buildQuadsFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture,
boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ,
int shaderBlockId, ObjectPooler<ModelQuad> quadBuf, List<ModelQuadViewMutable> collectedQuads,
int shaderBlockId, ObjectPooler<ModelQuad> quadPool, List<ModelQuadViewMutable> collectedQuads,
CapturingTessellator.Flags flags) {
flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals);
flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals, drawMode);
final int verticesPerPrimitive = drawMode == GL11.GL_QUADS ? 4 : 3;
// Only handle GL_QUADS and GL_TRIANGLES - skip unsupported draw modes to prevent buffer corruption
final int verticesPerPrimitive;
if (drawMode == GL11.GL_QUADS) {
verticesPerPrimitive = 4;
} else if (drawMode == GL11.GL_TRIANGLES) {
verticesPerPrimitive = 3;
} else {
// Unsupported draw mode (GL_LINES, GL_LINE_STRIP, etc.) - skip to avoid corrupting buffer reads
LOGGER.debug(
"Skipping unsupported draw mode: 0x{} ({} vertices)",
Integer.toHexString(drawMode),
vertexCount);
return;
}
for (int quadI = 0; quadI < vertexCount / verticesPerPrimitive; quadI++) {
final int srcOffset = quadI * (verticesPerPrimitive * VERTEX_STRIDE);
if (isEmptyQuad(rawBuffer, srcOffset)) continue;
final int srcOffset = quadI * (verticesPerPrimitive * VERTEX_SIZE);
if (PrimitiveExtractor.isEmptyPrimitive(rawBuffer, srcOffset, verticesPerPrimitive)) continue;
final ModelQuad quad = quadBuf.getInstance();
final ModelQuad quad = quadPool.getInstance();
quad.setState(rawBuffer, srcOffset, flags, drawMode, offsetX, offsetY, offsetZ);
quad.setShaderBlockId(shaderBlockId);
collectedQuads.add(quad);
}
}
/**
* Check if a quad is degenerate (all vertices at the same position). This filters out empty/collapsed quads that
* would be invisible. Compares raw float bits for exact equality.
*
* @param rawBuffer The tessellator's raw data buffer
* @param srcOffset Offset to the first vertex of the quad
* @return true if all 4 vertices have identical X, Y, and Z coordinates
*/
private static boolean isEmptyQuad(int[] rawBuffer, int srcOffset) {
// Check if all 4 vertices have identical X, Y, Z coordinates
for (int axis = 0; axis < 3; axis++) {
final int firstVal = rawBuffer[srcOffset + axis];
if (firstVal != rawBuffer[srcOffset + VERTEX_STRIDE + axis]) return false;
if (firstVal != rawBuffer[srcOffset + 2 * VERTEX_STRIDE + axis]) return false;
if (firstVal != rawBuffer[srcOffset + 3 * VERTEX_STRIDE + axis]) return false;
}
return true;
}
}
@@ -8,10 +8,15 @@ import net.minecraft.client.renderer.Tessellator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
@@ -30,7 +35,7 @@ public class TessellatorManager {
final CaptureMode mode;
final DrawCallback callback; // null for CAPTURING mode, non-null for COMPILING
final List<CapturedDraw> capturedDraws = new ArrayList<>(); // Stores per-draw quads+flags for nested CAPTURING
List<ModelQuadViewMutable> savedQuads; // Quads saved from parent when nesting starts
CaptureState(CaptureMode mode, DrawCallback callback) {
this.mode = mode;
@@ -38,6 +43,29 @@ public class TessellatorManager {
}
}
/**
* Captured geometry as a list of VBOs. Each VBO contains primitives of a single type (lines, triangles, or quads).
*/
@Desugar
public record CapturedGeometry(List<VertexBuffer> vbos) {
public boolean isEmpty() {
return vbos.isEmpty();
}
public void delete() {
for (int i = 0, size = vbos.size(); i < size; i++) {
vbos.get(i).delete();
}
}
public void renderAll() {
for (int i = 0, size = vbos.size(); i < size; i++) {
vbos.get(i).render();
}
}
}
private static final ThreadLocal<CapturingTessellator> capturingTessellator = ThreadLocal
.withInitial(CapturingTessellator::new);
@@ -125,21 +153,18 @@ public class TessellatorManager {
}
/**
* If parent state is CAPTURING and there are uncommitted quads, save them as a draw. This handles nesting: child
* captures need to preserve parent's pending work.
* If parent state is CAPTURING, save its quads before child starts. The child will use the same collectedQuads
* list, so we save parent's quads and clear for child use.
*/
private static void saveUncommittedQuadsIfNeeded(ArrayList<CaptureState> stack, CapturingTessellator tess) {
if (stack.isEmpty() || tess.getQuads().isEmpty()) {
private static void saveParentQuadsIfNeeded(ArrayList<CaptureState> stack, CapturingTessellator tess) {
if (stack.isEmpty()) {
return;
}
CaptureState parent = stack.get(stack.size() - 1);
if (parent.mode == CaptureMode.CAPTURING) {
// Deep copy quads before clearing (will be reused by child)
parent.capturedDraws.add(
new CapturedDraw(
ModelQuadUtil.deepCopyQuads(tess.getQuads()),
new CapturingTessellator.Flags(tess.flags)));
// Save parent's quads and clear for child
parent.savedQuads = new ArrayList<>(tess.getQuads());
tess.getQuads().clear();
}
}
@@ -152,8 +177,8 @@ public class TessellatorManager {
ArrayList<CaptureState> stack = captureStack.get();
final CapturingTessellator tess = capturingTessellator.get();
// Save any uncommitted quads if parent is CAPTURING
saveUncommittedQuadsIfNeeded(stack, tess);
// Save parent's quads if parent is CAPTURING
saveParentQuadsIfNeeded(stack, tess);
// Validate no orphan quads exist
if (!tess.getQuads().isEmpty()) {
@@ -166,9 +191,9 @@ public class TessellatorManager {
return tess;
}
/// Stop the CapturingTessellator and return the captured draws with per-draw flags.
/// The quads are pooled objects - caller MUST copy them if needed beyond their pool lifecycle.
public static List<CapturedDraw> stopCapturingToDraws() {
/// Stop the CapturingTessellator and return the pooled quads. The quads are valid until clearQuads() is called on
/// the CapturingTesselator, which must be done before starting capturing again.
public static List<ModelQuadViewMutable> stopCapturingToPooledQuads() {
CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!");
ArrayList<CaptureState> stack = captureStack.get();
@@ -177,38 +202,29 @@ public class TessellatorManager {
// Flush any pending draw
if (tess.isDrawing) tess.draw();
// Get the captured draws from the current level (already stored by processDrawForCapturingTessellator)
stack.remove(stack.size() - 1); // Pop
final List<CapturedDraw> draws = new ArrayList<>(currentState.capturedDraws);
tess.restoreTranslation();
// If nested inside another CAPTURING, we're done - parent's draws are already in parent's capturedDraws
// Note: tess.getQuads() should be empty since processDrawForCapturingTessellator clears after each draw
if (!stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING) {
// Child is done, parent continues (no restoration needed - parent draws already in parent.capturedDraws)
tess.getQuads().clear(); // Defensive clear
boolean isNested = !stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING;
List<ModelQuadViewMutable> quads;
if (currentState.savedQuads != null) {
// Had nested child - combine saved quads with any new quads
quads = currentState.savedQuads;
quads.addAll(tess.getQuads());
tess.getQuads().clear();
} else if (isNested) {
// We are a child - return copy of accumulated quads (will clear for parent)
quads = new ArrayList<>(tess.getQuads());
tess.getQuads().clear();
} else {
tess.discard();
// Non-nested common case - return accumulated quads directly
quads = tess.getQuads();
}
// Note: don't discard here - caller owns the pooled quads until clearQuads()
return draws;
}
/// Stop the CapturingTessellator and return the pooled quads. The quads are valid until clearQuads() is called on
/// the CapturingTesselator, which must be done before starting capturing again.
/// Note: This flattens all draws into a single list, losing per-draw flag information.
/// Use stopCapturingToDraws() if you need per-draw flags.
public static List<ModelQuadViewMutable> stopCapturingToPooledQuads() {
final List<CapturedDraw> draws = stopCapturingToDraws();
// Flatten all draws into a single quad list
final List<ModelQuadViewMutable> allQuads = new ArrayList<>();
for (int i = 0, size = draws.size(); i < size; i++) {
allQuads.addAll(draws.get(i).quads());
}
return allQuads;
return quads;
}
/// Stops the CapturingTessellator, stores the quads in a buffer (based on the VertexFormat provided), and clears
@@ -225,6 +241,151 @@ public class TessellatorManager {
return new VertexBuffer(format, GL11.GL_QUADS).upload(stopCapturingToBuffer(format));
}
/**
* Stops the CapturingTessellator and returns separate VBOs for each primitive type captured. This is the preferred
* method when capturing mixed geometry (lines, triangles, quads).
*
* @param format The vertex format for all VBOs
* @return CapturedGeometry with separate VBOs (null fields for types not captured)
*/
public static CapturedGeometry stopCapturingToGeometry(VertexFormat format) {
CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!");
ArrayList<CaptureState> stack = captureStack.get();
final CapturingTessellator tess = capturingTessellator.get();
// Flush any pending draw
if (tess.isDrawing) tess.draw();
stack.remove(stack.size() - 1); // Pop
tess.restoreTranslation();
// Group primitives by type using reusable lists from the tessellator
List<ModelLine> lines = tess.lineListCache;
List<ModelTriangle> triangles = tess.triangleListCache;
List<ModelQuad> quads = tess.quadListCache;
lines.clear();
triangles.clear();
quads.clear();
// Use indexed loops to avoid iterator allocation
List<ModelPrimitiveView> prims = tess.getPrimitives();
for (int i = 0, size = prims.size(); i < size; i++) {
ModelPrimitiveView prim = prims.get(i);
if (prim instanceof ModelLine ml) {
lines.add(ml);
} else if (prim instanceof ModelTriangle mt) {
triangles.add(mt);
}
// Note: Quads have been moved to collectedQuads by processDrawForCapturingTessellator
}
// Get quads from collectedQuads (where they were moved for backward compat)
List<ModelQuadViewMutable> collectedQuads = tess.getQuads();
for (int i = 0, size = collectedQuads.size(); i < size; i++) {
ModelQuadViewMutable quad = collectedQuads.get(i);
if (quad instanceof ModelQuad mq) {
quads.add(mq);
}
}
// Create VBOs for each type that has content
List<VertexBuffer> vbos = new ArrayList<>();
if (!lines.isEmpty()) vbos.add(createLineVBO(lines, format));
if (!triangles.isEmpty()) vbos.add(createTriangleVBO(triangles, format));
if (!quads.isEmpty()) vbos.add(createQuadVBO(quads, format));
// Clean up
tess.clearPrimitives();
tess.clearQuads();
if (!stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING) {
// Nested - parent continues
} else {
tess.discard();
}
return new CapturedGeometry(vbos);
}
private static VertexBuffer createLineVBO(List<ModelLine> lines, VertexFormat format) {
ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * lines.size() * 2);
for (int i = 0, size = lines.size(); i < size; i++) {
writePrimitiveToBuffer(lines.get(i), buffer, format);
}
buffer.rewind();
return new VertexBuffer(format, GL11.GL_LINES).upload(buffer);
}
private static VertexBuffer createTriangleVBO(List<ModelTriangle> triangles, VertexFormat format) {
ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * triangles.size() * 3);
for (int i = 0, size = triangles.size(); i < size; i++) {
writePrimitiveToBuffer(triangles.get(i), buffer, format);
}
buffer.rewind();
return new VertexBuffer(format, GL11.GL_TRIANGLES).upload(buffer);
}
private static VertexBuffer createQuadVBO(List<ModelQuad> quads, VertexFormat format) {
ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * quads.size() * 4);
for (int i = 0, size = quads.size(); i < size; i++) {
format.writeQuad(quads.get(i), buffer);
}
buffer.rewind();
return new VertexBuffer(format, GL11.GL_QUADS).upload(buffer);
}
/**
* Expected vertex size for primitive writing: pos(12) + color(4) + tex(8) + light(4) + normal(4) = 32 bytes
*/
private static final int EXPECTED_PRIMITIVE_VERTEX_SIZE = 32;
/**
* Writes a primitive's vertices to the buffer using the standard vertex layout.
* <p>
* <b>IMPORTANT:</b> This method assumes the vertex format matches the layout:
* <ul>
* <li>Position: 3 floats (12 bytes)</li>
* <li>Color: 1 int ABGR (4 bytes)</li>
* <li>Texture: 2 floats (8 bytes)</li>
* <li>Light: 1 int (4 bytes)</li>
* <li>Normal: 1 int (4 bytes)</li>
* </ul>
* Total: 32 bytes per vertex. The format's vertexSize must match.
*
* @throws IllegalArgumentException if format.getVertexSize() != 32
*/
private static void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer, VertexFormat format) {
if (format.getVertexSize() != EXPECTED_PRIMITIVE_VERTEX_SIZE) {
throw new IllegalArgumentException(
"writePrimitiveToBuffer requires vertex size of " + EXPECTED_PRIMITIVE_VERTEX_SIZE
+ " bytes, but format has "
+ format.getVertexSize()
+ ". Use a compatible format or implement a custom primitive writer.");
}
// Write each vertex of the primitive
for (int i = 0; i < prim.getVertexCount(); i++) {
// Position (always present)
buffer.putFloat(prim.getX(i));
buffer.putFloat(prim.getY(i));
buffer.putFloat(prim.getZ(i));
// Color (ABGR format for OpenGL)
buffer.putInt(prim.getColor(i));
// Texture coordinates
buffer.putFloat(prim.getTexU(i));
buffer.putFloat(prim.getTexV(i));
// Light (packed lightmap)
buffer.putInt(prim.getLight(i));
// Normal (packed)
buffer.putInt(prim.getForgeNormal(i));
}
}
/**
* Populates the passed-in VBO with the data from the CapturingTessellator. If the passed-in VBO is null, it will
* create & return a new one.
@@ -268,9 +429,11 @@ public class TessellatorManager {
}
/**
* Intercepts Tessellator.draw() during display list compilation. Extracts quads from the vanilla Tessellator's
* Intercepts Tessellator.draw() during display list compilation. Extracts geometry from the vanilla Tessellator's
* buffer and invokes the compiling callback. Only called when shouldInterceptDraw returns true. This is main-thread
* only (display list compilation happens on the main thread).
* <p>
* GL_QUADS go to collectedQuads; GL_TRIANGLES and other modes go to collectedPrimitives as proper primitives.
*
* @param tess The vanilla Tessellator instance
* @return The result that draw() should return
@@ -288,32 +451,55 @@ public class TessellatorManager {
throw new IllegalStateException("interceptDraw called but callback is null!");
}
// Build quads from vanilla tess's buffer using main thread capturing tessellator's infrastructure
// Build geometry from vanilla tess's buffer using main thread capturing tessellator's infrastructure
// COMPILING mode: Only GL_QUADS go to quads; triangles and other primitives stay as proper primitives
final CapturingTessellator helper = capturingTessellator.get();
QuadExtractor.buildQuadsFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
true, // Vanilla always has texture
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
0,
0,
0, // Vanilla has no offset
-1, // No shaderBlockId
helper.quadBuf,
helper.collectedQuads,
helper.flags);
if (tess.drawMode == GL11.GL_QUADS) {
QuadExtractor.buildQuadsFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
true, // Vanilla always has texture
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
0,
0,
0, // Vanilla has no offset
-1, // No shaderBlockId
helper.quadPool,
helper.collectedQuads,
helper.flags);
} else {
// GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, etc. → primitives (not quadrangulated)
PrimitiveExtractor.buildPrimitivesFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
true, // Vanilla always has texture
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
0,
0,
0, // Vanilla has no offset
-1, // No shaderBlockId
helper.quadPool,
helper.triPool,
helper.linePool,
helper.collectedPrimitives,
helper.flags);
}
// Invoke callback with collected quads (protect against recursion)
// Invoke callback with collected geometry (protect against recursion)
isInCompilingCallback = true;
try {
current.callback.onDraw(helper.collectedQuads, helper.flags);
current.callback.onDraw(helper.collectedQuads, helper.collectedPrimitives, helper.flags);
} finally {
isInCompilingCallback = false;
}
helper.clearQuads();
helper.clearPrimitives();
int result = tess.rawBufferIndex * 4;
((ITessellatorInstance) tess).discard();
@@ -322,42 +508,102 @@ public class TessellatorManager {
/**
* Helper for CapturingTessellator to process its draw() call using shared logic.
* <p>
* Mode-specific behavior:
* <ul>
* <li>COMPILING: Only GL_QUADS → quads; GL_TRIANGLES and other modes → primitives (proper triangles)</li>
* <li>CAPTURING: GL_QUADS and GL_TRIANGLES → quads (quadrangulated for backward compat); other modes →
* primitives</li>
* </ul>
*/
static int processDrawForCapturingTessellator(CapturingTessellator tess) {
CaptureState current = peekState();
final CaptureState current = peekState();
final boolean isCompiling = current != null && current.mode == CaptureMode.COMPILING;
QuadExtractor.buildQuadsFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
tess.hasTexture,
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
-tess.offset.x,
-tess.offset.y,
-tess.offset.z,
tess.shaderBlockId,
tess.quadBuf,
tess.collectedQuads,
tess.flags);
if (current != null) {
if (current.mode == CaptureMode.COMPILING) {
current.callback.onDraw(tess.collectedQuads, tess.flags);
tess.clearQuads();
} else if (current.mode == CaptureMode.CAPTURING) {
// Deep copy quads before pooling (tess.clearQuads releases them for reuse)
// Store per-draw quads+flags (deep copy to preserve across pool reuse)
current.capturedDraws.add(
new CapturedDraw(
ModelQuadUtil.deepCopyQuads(tess.collectedQuads),
new CapturingTessellator.Flags(tess.flags)));
tess.clearQuads();
if (isCompiling) {
// COMPILING: Only GL_QUADS to quads; triangles and other primitives stay as proper primitives
if (tess.drawMode == GL11.GL_QUADS) {
QuadExtractor.buildQuadsFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
tess.hasTexture,
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
-tess.offset.x,
-tess.offset.y,
-tess.offset.z,
tess.shaderBlockId,
tess.quadPool,
tess.collectedQuads,
tess.flags);
} else {
// GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, etc. → primitives (not quadrangulated)
PrimitiveExtractor.buildPrimitivesFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
tess.hasTexture,
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
-tess.offset.x,
-tess.offset.y,
-tess.offset.z,
tess.shaderBlockId,
tess.quadPool,
tess.triPool,
tess.linePool,
tess.collectedPrimitives,
tess.flags);
}
// Invoke callback and clear
current.callback.onDraw(tess.collectedQuads, tess.collectedPrimitives, tess.flags);
tess.clearQuads();
tess.clearPrimitives();
} else {
// CAPTURING: GL_QUADS and GL_TRIANGLES to quads (backward compat quadrangulation)
if (tess.drawMode == GL11.GL_QUADS || tess.drawMode == GL11.GL_TRIANGLES) {
QuadExtractor.buildQuadsFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
tess.hasTexture,
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
-tess.offset.x,
-tess.offset.y,
-tess.offset.z,
tess.shaderBlockId,
tess.quadPool,
tess.collectedQuads,
tess.flags);
} else {
// GL_LINES, GL_LINE_STRIP, etc. → primitives
PrimitiveExtractor.buildPrimitivesFromBuffer(
tess.rawBuffer,
tess.vertexCount,
tess.drawMode,
tess.hasTexture,
tess.hasBrightness,
tess.hasColor,
tess.hasNormals,
-tess.offset.x,
-tess.offset.y,
-tess.offset.z,
tess.shaderBlockId,
tess.quadPool,
tess.triPool,
tess.linePool,
tess.collectedPrimitives,
tess.flags);
}
// No callback - geometry stays until stop is called
}
int result = tess.rawBufferIndex * 4;
final int result = tess.rawBufferIndex * 4;
tess.discard();
return result;
}
@@ -381,6 +627,7 @@ public class TessellatorManager {
stack.clear();
tessellator.discard();
tessellator.clearQuads();
tessellator.clearPrimitives();
isInCompilingCallback = false;
}
@@ -0,0 +1,160 @@
package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.POSITION_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEXTURE_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.vertexOffset;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
/**
* A line primitive with 2 vertices. Supports full vertex attributes including position, color, texture coordinates,
* lightmap, and normals.
*/
public class ModelLine implements ModelPrimitiveView {
private final int[] data = new int[VERTEX_SIZE * 2];
private int shaderBlockId = -1;
@Override
public int getVertexCount() {
return 2;
}
@Override
public float getX(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX]);
}
@Override
public float getY(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 1]);
}
@Override
public float getZ(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 2]);
}
@Override
public int getColor(int idx) {
return data[vertexOffset(idx) + COLOR_INDEX];
}
@Override
public float getTexU(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX]);
}
@Override
public float getTexV(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX + 1]);
}
@Override
public int getLight(int idx) {
return data[vertexOffset(idx) + LIGHT_INDEX];
}
@Override
public int getForgeNormal(int idx) {
return data[vertexOffset(idx) + NORMAL_INDEX];
}
// Setters for building the line
public void setX(int idx, float x) {
data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x);
}
public void setY(int idx, float y) {
data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y);
}
public void setZ(int idx, float z) {
data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z);
}
public void setColor(int idx, int color) {
data[vertexOffset(idx) + COLOR_INDEX] = color;
}
public void setTexU(int idx, float u) {
data[vertexOffset(idx) + TEXTURE_INDEX] = Float.floatToRawIntBits(u);
}
public void setTexV(int idx, float v) {
data[vertexOffset(idx) + TEXTURE_INDEX + 1] = Float.floatToRawIntBits(v);
}
public void setLight(int idx, int light) {
data[vertexOffset(idx) + LIGHT_INDEX] = light;
}
public void setForgeNormal(int idx, int normal) {
data[vertexOffset(idx) + NORMAL_INDEX] = normal;
}
/**
* Sets vertex data from a raw tessellator buffer.
*
* @param rawBuffer The tessellator's raw int[] buffer
* @param srcOffset Offset to the first vertex in the source buffer
*/
public void setState(int[] rawBuffer, int srcOffset) {
System.arraycopy(rawBuffer, srcOffset, data, 0, VERTEX_SIZE * 2);
}
/**
* Copies a single vertex from a raw buffer directly to this line's data. Avoids int→float→int conversions by
* copying raw ints directly.
*
* @param rawBuffer The tessellator's raw int[] buffer
* @param srcOffset Offset to the vertex in the source buffer
* @param destIdx Destination vertex index (0 or 1)
*/
public void copyVertexFromBuffer(int[] rawBuffer, int srcOffset, int destIdx) {
System.arraycopy(rawBuffer, srcOffset, data, vertexOffset(destIdx), VERTEX_SIZE);
}
public int getShaderBlockId() {
return shaderBlockId;
}
public void setShaderBlockId(int shaderBlockId) {
this.shaderBlockId = shaderBlockId;
}
/**
* Applies a position offset to all vertices.
*
* @param offsetX X offset to add to all vertices
* @param offsetY Y offset to add to all vertices
* @param offsetZ Z offset to add to all vertices
*/
public void applyOffset(int offsetX, int offsetY, int offsetZ) {
if (offsetX == 0 && offsetY == 0 && offsetZ == 0) return;
for (int i = 0; i < 2; i++) {
final int offset = vertexOffset(i);
data[offset + POSITION_INDEX] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX]) + offsetX);
data[offset + POSITION_INDEX + 1] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 1]) + offsetY);
data[offset + POSITION_INDEX + 2] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 2]) + offsetZ);
}
}
/**
* Copy data from another ModelLine.
*/
public ModelLine copyFrom(ModelLine source) {
System.arraycopy(source.data, 0, this.data, 0, VERTEX_SIZE * 2);
this.shaderBlockId = source.shaderBlockId;
return this;
}
}
@@ -0,0 +1,53 @@
package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive;
/**
* Base interface for all primitive types (lines, triangles, quads). Provides common vertex accessors with variable
* vertex count.
*/
public interface ModelPrimitiveView {
/**
* @return The number of vertices in this primitive (2 for lines, 3 for triangles, 4 for quads)
*/
int getVertexCount();
/**
* @return The x-position of the vertex at index {@param idx}
*/
float getX(int idx);
/**
* @return The y-position of the vertex at index {@param idx}
*/
float getY(int idx);
/**
* @return The z-position of the vertex at index {@param idx}
*/
float getZ(int idx);
/**
* @return The integer-encoded color of the vertex at index {@param idx}
*/
int getColor(int idx);
/**
* @return The texture x-coordinate for the vertex at index {@param idx}
*/
float getTexU(int idx);
/**
* @return The texture y-coordinate for the vertex at index {@param idx}
*/
float getTexV(int idx);
/**
* @return The packed lightmap coordinates for the vertex at index {@param idx}
*/
int getLight(int idx);
/**
* @return The packed normal vector for the vertex at index {@param idx}
*/
int getForgeNormal(int idx);
}
@@ -260,9 +260,9 @@ public class ModelQuad implements ModelQuadViewMutable {
private void clearLightmap() {
setLight(0, DEFAULT_LIGHTMAP);
setLight(0, DEFAULT_LIGHTMAP);
setLight(0, DEFAULT_LIGHTMAP);
setLight(0, DEFAULT_LIGHTMAP);
setLight(1, DEFAULT_LIGHTMAP);
setLight(2, DEFAULT_LIGHTMAP);
setLight(3, DEFAULT_LIGHTMAP);
}
/**
@@ -1,16 +1,24 @@
package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFlags;
/**
* Provides a read-only view of a model quad. For mutable access to a model quad, see {@link ModelQuadViewMutable}.
* Extends {@link ModelPrimitiveView} for compatibility with the primitive rendering pipeline.
*/
public interface ModelQuadView {
public interface ModelQuadView extends ModelPrimitiveView {
@Override
default int getVertexCount() {
return 4;
}
/**
* @return The x-position of the vertex at index {@param idx}
*/
@Override
float getX(int idx);
/**
@@ -0,0 +1,226 @@
package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_LIGHTMAP;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.POSITION_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEXTURE_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.vertexOffset;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
/**
* A triangle primitive with 3 vertices. Supports full vertex attributes including position, color, texture coordinates,
* lightmap, and normals.
*/
public class ModelTriangle implements ModelPrimitiveView {
private final int[] data = new int[VERTEX_SIZE * 3];
private int computedNormal;
private int shaderBlockId = -1;
@Override
public int getVertexCount() {
return 3;
}
@Override
public float getX(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX]);
}
@Override
public float getY(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 1]);
}
@Override
public float getZ(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 2]);
}
@Override
public int getColor(int idx) {
return data[vertexOffset(idx) + COLOR_INDEX];
}
@Override
public float getTexU(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX]);
}
@Override
public float getTexV(int idx) {
return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX + 1]);
}
@Override
public int getLight(int idx) {
return data[vertexOffset(idx) + LIGHT_INDEX];
}
@Override
public int getForgeNormal(int idx) {
return data[vertexOffset(idx) + NORMAL_INDEX];
}
// Setters
public void setX(int idx, float x) {
data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x);
computedNormal = 0; // Invalidate cached normal
}
public void setY(int idx, float y) {
data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y);
computedNormal = 0;
}
public void setZ(int idx, float z) {
data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z);
computedNormal = 0;
}
public void setColor(int idx, int color) {
data[vertexOffset(idx) + COLOR_INDEX] = color;
}
public void setTexU(int idx, float u) {
data[vertexOffset(idx) + TEXTURE_INDEX] = Float.floatToRawIntBits(u);
}
public void setTexV(int idx, float v) {
data[vertexOffset(idx) + TEXTURE_INDEX + 1] = Float.floatToRawIntBits(v);
}
public void setLight(int idx, int light) {
data[vertexOffset(idx) + LIGHT_INDEX] = light;
}
public void setForgeNormal(int idx, int normal) {
data[vertexOffset(idx) + NORMAL_INDEX] = normal;
}
/**
* Sets vertex data from a raw tessellator buffer.
*
* @param rawBuffer The tessellator's raw int[] buffer
* @param srcOffset Offset to the first vertex in the source buffer
* @param flags Vertex format flags
*/
public void setState(int[] rawBuffer, int srcOffset, CapturingTessellator.Flags flags) {
System.arraycopy(rawBuffer, srcOffset, data, 0, VERTEX_SIZE * 3);
if (!flags.hasColor) clearColors();
if (!flags.hasNormals) clearNormals();
if (!flags.hasBrightness) clearLightmap();
computedNormal = 0;
}
/**
* Copies a single vertex from a raw buffer directly to this triangle's data. Avoids int→float→int conversions by
* copying raw ints directly.
*
* @param rawBuffer The tessellator's raw int[] buffer
* @param srcOffset Offset to the vertex in the source buffer
* @param destIdx Destination vertex index (0, 1, or 2)
*/
public void copyVertexFromBuffer(int[] rawBuffer, int srcOffset, int destIdx) {
System.arraycopy(rawBuffer, srcOffset, data, vertexOffset(destIdx), VERTEX_SIZE);
}
/**
* Calculate the face normal from the triangle's vertices.
*/
public int getComputedFaceNormal() {
if (computedNormal != 0) return computedNormal;
final float x0 = getX(0), y0 = getY(0), z0 = getZ(0);
final float x1 = getX(1), y1 = getY(1), z1 = getZ(1);
final float x2 = getX(2), y2 = getY(2), z2 = getZ(2);
// Cross product of (v1-v0) x (v2-v0)
final float dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0;
final float dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0;
float nx = dy1 * dz2 - dz1 * dy2;
float ny = dz1 * dx2 - dx1 * dz2;
float nz = dx1 * dy2 - dy1 * dx2;
float len = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
if (len != 0) {
nx /= len;
ny /= len;
nz /= len;
}
computedNormal = NormI8.pack(nx, ny, nz);
return computedNormal;
}
private void clearColors() {
setColor(0, DEFAULT_COLOR);
setColor(1, DEFAULT_COLOR);
setColor(2, DEFAULT_COLOR);
}
private void clearNormals() {
computedNormal = 0;
data[vertexOffset(0) + NORMAL_INDEX] = 0;
data[vertexOffset(1) + NORMAL_INDEX] = 0;
data[vertexOffset(2) + NORMAL_INDEX] = 0;
}
private void clearLightmap() {
setLight(0, DEFAULT_LIGHTMAP);
setLight(1, DEFAULT_LIGHTMAP);
setLight(2, DEFAULT_LIGHTMAP);
}
public int getShaderBlockId() {
return shaderBlockId;
}
public void setShaderBlockId(int shaderBlockId) {
this.shaderBlockId = shaderBlockId;
}
/**
* Applies a position offset to all vertices. More efficient than calling setX/setY/setZ individually as it
* invalidates the computed normal only once.
*
* @param offsetX X offset to add to all vertices
* @param offsetY Y offset to add to all vertices
* @param offsetZ Z offset to add to all vertices
*/
public void applyOffset(int offsetX, int offsetY, int offsetZ) {
if (offsetX == 0 && offsetY == 0 && offsetZ == 0) return;
for (int i = 0; i < 3; i++) {
final int offset = vertexOffset(i);
data[offset + POSITION_INDEX] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX]) + offsetX);
data[offset + POSITION_INDEX + 1] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 1]) + offsetY);
data[offset + POSITION_INDEX + 2] = Float
.floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 2]) + offsetZ);
}
computedNormal = 0; // Invalidate once at the end
}
/**
* Copy data from another ModelTriangle.
*/
public ModelTriangle copyFrom(ModelTriangle source) {
System.arraycopy(source.data, 0, this.data, 0, VERTEX_SIZE * 3);
this.computedNormal = source.computedNormal;
this.shaderBlockId = source.shaderBlockId;
return this;
}
}