Compare commits

..
Author SHA1 Message Date
sisyphussy e17f60308d Display List Refactor (#1360) 2026-02-04 10:39:20 -08:00
Kotmatross 1dd98978ad [Hotfix] Fix NTM:Space mixin targets for X5593_H261 (#1356) 2026-02-02 10:02:36 -08:00
Jason Mitchell dae986eb0b Fix crash with clearBufferSubData (#1355) 2026-02-01 12:41:53 -08:00
Jason Mitchell 5fdf84edd0 Camera and Menu Tweaks (#1354) 2026-02-01 12:14:32 -08:00
Jason Mitchell b19d023c11 Bump gtnhgradle 2026-02-01 09:26:19 -08:00
Jason Mitchell 41eafbd151 GLSL Downgrading (#1348) 2026-01-31 13:23:02 -08:00
sisyphussy dd970b4c6a Fix nested display lists rendering twice (#1349)
* Fix nested display lists rendering twice

* cleanup
2026-01-31 05:45:48 -08:00
Eclipse-Sol f79ad7f22a Fix arrows inheriting item material IDs (#1347) 2026-01-30 18:35:04 -08:00
Jason Mitchell 6947ffa3e2 Add IS_IRIS define as an option. 2026-01-30 18:10:27 -08:00
Jason Mitchell 969d2c3710 Backports tessellation shader support, safe zone shadow culling, and shader pack rendering directives. 2026-01-30 18:10:27 -08:00
Jason Mitchell c5988d29c3 Fix camera position and nether portal 3rd party rendering 2026-01-30 18:10:27 -08:00
Jason Mitchell dc68c2c265 Fix end portal w/ Shaders 2026-01-30 18:10:27 -08:00
Jason Mitchell 51533a81ec Misc Shaderpack loading fixes (#1343) 2026-01-30 14:53:41 -08:00
Eclipse-Sol 90eabb5d40 Add hardcoded entities and player_cape (#1327) 2026-01-30 14:53:26 -08:00
sisyphussyandJason Mitchell 74843cb1f9 Glc redirects (#1340)
Co-authored-by: Jason Mitchell <[email protected]>
2026-01-30 14:50:54 -08:00
Death Fuel 5e0344a529 remove unnecessary resource refresh (#1342) 2026-01-30 14:40:51 -08:00
Jason Mitchell 3cdd934987 First pass at setup/begin pass support (#1335) 2026-01-29 07:53:04 -08:00
Léa Gris 9d90ff137c fix(render): adapt hodgepodge fixBottomFaceUV (#1334) 2026-01-28 10:55:53 -08:00
Jason Mitchell bee9541797 Shadow Compute Shaders (#1333) 2026-01-28 00:03:04 -08:00
Jason Mitchell b75a5d8f7d Ya that won't work (#1332) 2026-01-27 15:32:42 -08:00
157 changed files with 4372 additions and 5247 deletions

No files matched your search

+5 -3
View File
@@ -71,9 +71,10 @@ dependencies {
// Iris Shaders
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.9.6:dev")
api("com.github.GTNewHorizons:GTNHLib:0.9.9:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-25.g3a943bb") {
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-26.g5ee7d96-GTNH") {
exclude module: "antlr4" // we only want to shadow the runtime module
}
shadowImplementation("org.antlr:antlr4-runtime:4.13.2")
@@ -110,11 +111,12 @@ dependencies {
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly(rfg.deobf("curse.maven:ntm-space-1121235:6974420"))
compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5593_H261"))
compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675"))
compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684"))
compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228"))
compileOnly(rfg.deobf("curse.maven:et-futurum-requiem-441392:5873837"))
// runtimeOnlyNonPublishable("com.github.GTNewHorizons:CoreTweaks:0.3.3.6-GTNH")
// For testing alternative splash screens, can be sourced from https://github.com/MalTeeez/ModernSplash/releases
+1 -1
View File
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.18")
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.19")
}
@@ -1,19 +1,21 @@
package com.gtnewhorizons.angelica;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import com.gtnewhorizons.angelica.proxy.CommonProxy;
import com.gtnewhorizons.angelica.utils.AnimationMode;
import com.gtnewhorizons.angelica.utils.ManagedEnum;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
@Mod(
modid = MOD_ID,
@@ -33,6 +35,15 @@ public class AngelicaMod {
public static final String MOD_ID = "angelica";
public static final Logger LOGGER = LogManager.getLogger("Angelica");
private static SodiumGameOptions CONFIG;
public static SodiumGameOptions options() {
if (CONFIG == null) {
CONFIG = SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
return CONFIG;
}
@SidedProxy(clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", serverSide = "com.gtnewhorizons.angelica.proxy.CommonProxy")
public static CommonProxy proxy;
@@ -72,7 +72,6 @@ public class FontStrategist {
DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap);
List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks();
defaultResourcePacks.add(fontResourcePack);
Minecraft.getMinecraft().refreshResources();
}
/**
@@ -114,7 +114,7 @@ public class ModdedBiomeDetector {
}
// lotr
if (lotrBiomeClass.isInstance(biome)) {
if (lotrBiomeClass!= null && lotrBiomeClass.isInstance(biome)) {
return detectLOTRBiome(biome);
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.compat.toremove;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
@@ -147,7 +147,7 @@ public abstract class RenderPhase {
FOG = new Fog("fog", () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.enableFog();
}, GLStateManager::disableFog);
BLACK_FOG = new Fog("black_fog", () -> {
@@ -156,7 +156,7 @@ public abstract class RenderPhase {
}, () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.disableFog();
});
MAIN_TARGET = new Target("main_target", () -> {
@@ -164,7 +164,7 @@ public abstract class RenderPhase {
});
OUTLINE_TARGET = new Target("outline_target", () -> {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
//MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false);
}, () -> {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
@@ -172,7 +172,7 @@ public abstract class RenderPhase {
TRANSLUCENT_TARGET = new Target("translucent_target", () -> {
if (Minecraft.isFancyGraphicsEnabled()) {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the translucent framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the translucent framebuffer");
// MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false);
}
@@ -345,7 +345,7 @@ public abstract class RenderPhase {
super("lightmap", () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - enable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - enable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable();
@@ -354,7 +354,7 @@ public abstract class RenderPhase {
}, () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - disable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - disable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable();
}
@@ -217,6 +217,10 @@ public class AngelicaConfig {
@Config.DefaultBoolean(false)
public static boolean enableHardcodedCustomUniforms;
@Config.Comment("Define IS_IRIS in shader macros.")
@Config.DefaultBoolean(true)
public static boolean defineIsIris;
@Config.Comment("Renders chunks before neighbors are ready. Improves loading at render distance edges, useful for low render distance servers.")
@Config.DefaultBoolean(false)
public static boolean useVanillaChunkTracking;
@@ -19,7 +19,7 @@ import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glEnableClientState;
import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER;
import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW;
import static org.lwjgl.opengl.GL15.glBindBuffer;
import static com.gtnewhorizons.angelica.glsm.GLStateManager.glBindBuffer;
import static org.lwjgl.opengl.GL15.glBufferData;
import static org.lwjgl.opengl.GL15.glGenBuffers;
import static org.lwjgl.opengl.GL20.glDisableVertexAttribArray;
@@ -171,7 +171,7 @@ public class AngelicaGLStateManagerService implements GLStateManagerService {
@Override
public void glBindBuffer(int target, int buffer) {
GL15.glBindBuffer(target, buffer);
GLStateManager.glBindBuffer(target, buffer);
}
@Override
@@ -1,238 +1,67 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor.BufferTransformOptimizer;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Builds final command buffers from raw command buffers and compiled VBO data.
* Transforms are already collapsed to MultMatrix during recording; the optimizer
* tracks transform state to emit deltas when draws need a different transform.
* Bridges the gap between VBO compilation (glsm types) and buffer processing (recording types).
*/
public final class CommandBufferBuilder {
private static final Logger LOGGER = LogManager.getLogger("CommandBufferBuilder");
private CommandBufferBuilder() {}
/** Build with transform delta optimization and merged draw ranges. */
public static void buildOptimizedFromRawBuffer(
/**
* Build commands with transform collapsing optimization.
* Accumulates MODELVIEW transforms and emits MultMatrix at barriers (draws, CallList).
* Uses mergedRanges where consecutive same-transform draws are combined.
*/
public static void buildFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
final CompiledLineBuffer compiledLineBuffer,
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
int glListId,
List<AccumulatedDraw> accumulatedDraws,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Buffer optimizer state
final BufferTransformOptimizer opt = new BufferTransformOptimizer();
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
AccumulatedDraw draw;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Read and process the command
final int opcode = rawBuffer.readInt();
CommandBufferProcessor.processCommandForOptimization(opcode, rawBuffer, opt, finalBuffer);
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Emit residual transform if not identity
if (!opt.isIdentity()) {
opt.emitPendingTransform(finalBuffer);
}
}
/** Debug build: no optimizations, 1:1 draw commands. */
public static void buildUnoptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect per-draw ranges (no merging) sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRangesUnoptimized(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
// Copy the command directly
CommandBufferProcessor.copyCommand(rawBuffer, finalBuffer);
// Emit draw ranges at this command position
while (rangeIndex < accumulatedDraws.size() && (draw = accumulatedDraws.get(rangeIndex)).commandIndex == cmdIndex) {
emitDrawRangeToBuffer(draw, finalBuffer, rangeIndex);
rangeIndex++;
}
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
while (rangeIndex < accumulatedDraws.size()) {
emitDrawRangeToBuffer(accumulatedDraws.get(rangeIndex), finalBuffer, rangeIndex);
rangeIndex++;
}
}
/** Collect merged draw ranges, sorted by command index. */
static List<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<>();
// Add quad ranges
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int b = 0; b < quadBufferArray.length; b++) {
final CompiledFormatBuffer compiledBuffer = quadBufferArray[b];
final DrawRange[] ranges = useMerged ? compiledBuffer.mergedRanges() : compiledBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags(),
DrawRangeWithBuffer.DrawSource.TESSELLATOR_QUADS));
}
}
// Add immediate mode line ranges
// Lines use a minimal flags (color only, no texture/brightness/normals)
if (compiledLineBuffer != null) {
final CapturingTessellator.Flags lineFlags = new CapturingTessellator.Flags(false, false, true, false);
final DrawRange[] ranges = useMerged ? compiledLineBuffer.mergedRanges() : compiledLineBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), lineFlags,
DrawRangeWithBuffer.DrawSource.IMMEDIATE_MODE_LINES));
}
}
// Add tessellator primitive ranges (lines and triangles) - grouped by format
if (compiledPrimitiveBuffers != null && !compiledPrimitiveBuffers.isEmpty()) {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int p = 0; p < primBufferArray.length; p++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[p];
final CapturingTessellator.Flags primFlags = primBuffers.flags();
// Tessellator lines
if (primBuffers.hasLines()) {
final DrawRange[] ranges = useMerged ? primBuffers.lineMergedRanges() : primBuffers.linePerDrawRanges();
final VertexBuffer vbo = primBuffers.lineVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_LINES));
}
}
// Tessellator triangles
if (primBuffers.hasTriangles()) {
final DrawRange[] ranges = useMerged ? primBuffers.triangleMergedRanges() : primBuffers.trianglePerDrawRanges();
final VertexBuffer vbo = primBuffers.triangleVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_TRIANGLES));
}
}
}
}
allRanges.sort(Comparator.comparingInt(r -> r.range().commandIndex()));
return allRanges;
}
/** Emit draw range with delta transform. Uses writeDrawRangeRestore for immediate mode. */
/**
* Emit a draw range to the output buffer, with transform if needed.
*/
private static void emitDrawRangeToBuffer(
DrawRangeWithBuffer drb,
BufferTransformOptimizer opt,
AccumulatedDraw draw,
CommandBuffer out,
Object2IntMap<VertexBuffer> vboIndexMap) {
int vboIdx) {
// Emit transform to reach the draw's expected transform
opt.emitTransformTo(out, drb.range().transform());
if (draw.restoreData != null) {
out.writeDrawRangeRestore(vboIdx, draw.restoreData);
return;
}
// Write the draw range command
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
final var restoreData = drb.range().restoreData();
if (restoreData != null) {
// Immediate mode draw with attribute restoration
final var flags = drb.flags();
out.writeDrawRangeRestore(
vboIdx, drb.range().startVertex(), drb.range().vertexCount(),
drb.hasBrightness(), flags.hasColor, flags.hasNormals, flags.hasTexture,
restoreData.lastColorR(), restoreData.lastColorG(),
restoreData.lastColorB(), restoreData.lastColorA(),
restoreData.lastNormalX(), restoreData.lastNormalY(), restoreData.lastNormalZ(),
restoreData.lastTexCoordS(), restoreData.lastTexCoordT()
);
} else {
// Regular tessellator draw (no restoration needed)
out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
out.writeDrawRange(vboIdx);
}
}
@@ -1,23 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO with its associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
public record CompiledFormatBuffer(
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO containing all line geometry with associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
public record CompiledLineBuffer(
VertexBuffer vbo,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
@@ -1,31 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Compiled VBOs containing tessellator primitives (lines and triangles) for a single vertex format.
* Separate VBOs are used for lines (GL_LINES) and triangles (GL_TRIANGLES) since they have different draw modes.
* <p>
* Contains range arrays for both optimized (merged) and unoptimized (per-draw) paths.
* Similar to CompiledFormatBuffer but handles primitives instead of quads.
*/
@Desugar
public record CompiledPrimitiveBuffers(
CapturingTessellator.Flags flags,
VertexBuffer lineVbo,
DrawRange[] lineMergedRanges,
DrawRange[] linePerDrawRanges,
VertexBuffer triangleVbo,
DrawRange[] triangleMergedRanges,
DrawRange[] trianglePerDrawRanges
) {
public boolean hasLines() {
return lineVbo != null;
}
public boolean hasTriangles() {
return triangleVbo != null;
}
}
@@ -1,26 +1,20 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VBOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBO;
import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBOBuilder;
import com.gtnewhorizons.angelica.glsm.recording.GLCommand;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.glsm.recording.commands.OptimizationContext;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.Getter;
@@ -38,9 +32,9 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
/**
* VBO-based display list emulation with command recording, transform collapsing, and format-based batching.
@@ -49,8 +43,8 @@ import java.util.Map;
* emitted at barriers (draws, CallList, exit). Vertices stay canonical in VBOs. Handles nested
* display lists correctly and maintains Push/Pop semantics.
*
* <p><b>Format-Based Batching:</b> Draws with same vertex format share a VBO via {@link FormatBuffer}.
* Each draw's position is tracked as a {@link DrawRange}. Consecutive same-transform draws merge.
* <p><b>Format-Based Batching:</b> Draws with same vertex format share a VBO via {@link DisplayListVBO}.
* Consecutive same-transform draws merge.
* Delta transforms handled via {@link TransformOptimizer}.
*/
@UtilityClass
@@ -92,28 +86,16 @@ public class DisplayListManager {
// Display list compilation state (current/active context)
private static int glListMode = 0;
private static int glListId = -1;
private static boolean tessellatorCompiling = false; // Track if we started compiling
private static CommandRecorder currentRecorder = null; // Command recorder (null when not recording)
private static volatile Thread recordingThread = null; // Thread that started recording (for thread-safety)
private static List<AccumulatedDraw> accumulatedDraws = null; // Accumulates quad draws for batching
private static List<AccumulatedLineDraw> accumulatedLineDraws = null; // Accumulates immediate mode line draws
private static List<AccumulatedPrimitiveDraw> accumulatedPrimitiveDraws = null; // Accumulates tessellator primitive draws (lines, triangles)
private static Matrix4fStack relativeTransform = null; // Tracks delta from current GL state (reset to I after each flush)
/**
* -- GETTER --
* Get the current matrix generation (for draw batching).
*/
@Getter
private static int matrixGeneration = 0; // Increments when relativeTransform changes; used for draw batching
private static int lastFlushedGeneration = -1; // Generation at last flush; draws trigger flush when gen changes
private static Matrix4fStack relativeTransform = null; // Tracks relative transforms during compilation (with push/pop support)
/**
* -- GETTER --
* Get the current state generation (for draw merging).
*/
@Getter
private static int stateGeneration = 0; // Increments at draw barriers (state commands); used for draw merging
private static Matrix4f lastFlushedTransform = null; // The transform that was flushed; consecutive same-gen draws share this
@Getter private static ImmediateModeRecorder immediateModeRecorder = null; // Records glBegin/glEnd/glVertex during compilation
private static StackTraceElement[] compilationStackTrace = null; // For logging: captured at glNewList()
// Debug logging: track sources of MULT_MATRIX commands and draw origins; only populated when LOG_DISPLAY_LIST_COMPILATION is true
@@ -140,11 +122,7 @@ public class DisplayListManager {
int listMode,
CommandRecorder recorder,
List<AccumulatedDraw> draws,
List<AccumulatedLineDraw> lineDraws,
List<AccumulatedPrimitiveDraw> primitiveDraws,
Matrix4fStack transform,
boolean wasTessellatorCompiling,
ImmediateModeRecorder immediateRecorder,
StackTraceElement[] stackTrace,
// Debug logging fields (only used when LOG_DISPLAY_LIST_COMPILATION)
@@ -169,16 +147,19 @@ public class DisplayListManager {
return glListMode == GL11.GL_COMPILE_AND_EXECUTE;
}
/** Emit accumulated transform as MultMatrix if non-identity, then reset. */
public static boolean flushMatrix() {
/**
* Emit accumulated transform as MultMatrix if non-identity, then reset.
*/
public static void flushMatrix() {
if (relativeTransform == null || isIdentity(relativeTransform)) {
// Clear pending ops even if we don't emit - they were no-ops (identity)
if (pendingTransformOps != null) {
pendingTransformOps.clear();
}
return false;
return;
}
// Save pending transform ops for logging (before we clear them)
if (multMatrixSources != null && pendingTransformOps != null) {
if (pendingTransformOps.isEmpty()) {
@@ -193,6 +174,7 @@ public class DisplayListManager {
// Record the collapsed MultMatrix command (for playback)
if (currentRecorder != null) {
currentRecorder.recordMultMatrix(relativeTransform);
stateGeneration++;
}
// COMPILE_AND_EXECUTE: execute now. Bypass GLSM to avoid re-entering recording path.
@@ -206,7 +188,6 @@ public class DisplayListManager {
// Reset to identity - we're now synchronized with GL
relativeTransform.identity();
return true;
}
public static void matrixBarrier() {
@@ -232,7 +213,7 @@ public class DisplayListManager {
}
// Draw barriers: state commands that prevent draw merging
private static void drawBarrier() {
static void drawBarrier() {
stateGeneration++;
}
@@ -369,8 +350,6 @@ public class DisplayListManager {
// Flush any pending delta, then record pop.
flushMatrix();
currentRecorder.recordPopMatrix();
// Invalidate cached transform
matrixGeneration++;
}
public static void recordViewport(int x, int y, int width, int height) {
@@ -592,6 +571,18 @@ public class DisplayListManager {
if (currentRecorder != null) currentRecorder.recordLoadIdentity();
}
public static void recordDrawArrays(int mode, int start, int count) {
if (currentRecorder != null) currentRecorder.recordDrawArrays(mode, start, count);
}
public static void recordDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
if (currentRecorder != null) currentRecorder.recordDrawElements(mode, indices_count, type, indices_buffer_offset);
}
public static void recordBindVBO(int vbo) { if (currentRecorder != null) currentRecorder.recordBindVBO(vbo); }
public static void recordBindVAO(int vao) { if (currentRecorder != null) currentRecorder.recordBindVAO(vao); }
// recordOrtho/recordFrustum removed - these now accumulate into relativeTransform
// via updateRelativeTransformOrtho/updateRelativeTransformFrustum
@@ -603,51 +594,13 @@ public class DisplayListManager {
* an AccumulatedDraw that will be interleaved correctly with other commands
* during display list playback.
*
* @param result The immediate mode result containing quads, lines, and flags
*/
public static void addImmediateModeDraw(ImmediateModeRecorder.Result result) {
if (accumulatedDraws == null || result == null) {
return;
}
if (matrixGeneration != lastFlushedGeneration) {
if (lastFlushedTransform == null) {
lastFlushedTransform = new Matrix4f();
}
lastFlushedTransform.set(relativeTransform);
flushMatrix();
lastFlushedGeneration = matrixGeneration;
}
final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform);
final int currentGeneration = matrixGeneration;
final int currentBatchId = stateGeneration;
final int cmdIndex = getCommandCount();
if (!result.quads().isEmpty()) {
final var flags = result.flags();
final AccumulatedDraw.RestoreData restoreData;
if (flags.hasColor || flags.hasNormals || flags.hasTexture) {
restoreData = new AccumulatedDraw.RestoreData(
result.lastColorR(), result.lastColorG(), result.lastColorB(), result.lastColorA(),
result.lastNormalX(), result.lastNormalY(), result.lastNormalZ(),
result.lastTexCoordS(), result.lastTexCoordT()
);
} else {
restoreData = null; // Position-only draw, no attributes to restore
}
final AccumulatedDraw quadDraw = new AccumulatedDraw(
result.quads(), currentTransform, flags,
cmdIndex, currentGeneration, currentBatchId, restoreData
);
accumulatedDraws.add(quadDraw);
}
// Add line draw if we have lines
if (!result.lines().isEmpty()) {
final AccumulatedLineDraw lineDraw = new AccumulatedLineDraw(result.lines(), currentTransform, result.flags(), getCommandCount(), currentBatchId);
accumulatedLineDraws.add(lineDraw);
public static void addImmediateModeDraw(DirectTessellator tessellator) {
if (!tessellator.isEmpty()) {
// Get relative transform (changes since glNewList, not absolute matrix state)
addAccumulatedDraw(tessellator, tessellator.getVertexFormat() != DefaultVertexFormat.POSITION);
}
tessellator.reset();
}
private static void applyTransformOp(Matrix4f m, float x, float y, float z, TransformOp op, Vector3f axis) {
@@ -675,7 +628,6 @@ public class DisplayListManager {
}
applyTransformOp(relativeTransform, x, y, z, op, rotationAxis);
matrixGeneration++;
if (pendingTransformOps != null) {
final String log = switch (op) {
@@ -716,7 +668,6 @@ public class DisplayListManager {
}
relativeTransform.mul(matrix);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add("glMultMatrixf(...)");
@@ -744,7 +695,6 @@ public class DisplayListManager {
}
relativeTransform.mul(orthoFrustumTemp);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add(String.format("glOrtho(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar));
}
@@ -768,7 +718,6 @@ public class DisplayListManager {
}
relativeTransform.mul(orthoFrustumTemp);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add(String.format("glFrustum(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar));
}
@@ -821,11 +770,6 @@ public class DisplayListManager {
* GL_COMPILE_AND_EXECUTE: Commands are recorded AND executed (GLSM cache updated)
*/
public static void glNewList(int list, int mode) {
// Assert main thread for display list compilation
if (!Thread.currentThread().equals(GLStateManager.getMainThread())) {
throw new IllegalStateException("Display list compilation must happen on main thread");
}
// Handle nested compilation - push current context onto stack
final boolean isNested = glListMode > 0;
@@ -833,10 +777,8 @@ public class DisplayListManager {
// Nested display list compilation violates OpenGL spec, but some of our optimizations require it
// Save current compilation context and start fresh for nested list
final CompilationContext parentContext = new CompilationContext(
glListId, glListMode, currentRecorder, accumulatedDraws, accumulatedLineDraws,
accumulatedPrimitiveDraws, relativeTransform,
tessellatorCompiling, immediateModeRecorder, compilationStackTrace,
pendingTransformOps, multMatrixSources, drawRangeSources
glListId, glListMode, currentRecorder, accumulatedDraws, relativeTransform,
compilationStackTrace, pendingTransformOps, multMatrixSources, drawRangeSources
);
compilationStack.push(parentContext);
}
@@ -846,15 +788,9 @@ public class DisplayListManager {
glListMode = mode;
recordingThread = Thread.currentThread(); // Track which thread is recording
currentRecorder = new CommandRecorder(); // Create command recorder
accumulatedDraws = new ArrayList<>(64); // Fewer draws than commands typically
accumulatedLineDraws = new ArrayList<>(16); // Immediate mode line draws are less common
accumulatedPrimitiveDraws = new ArrayList<>(16); // Tessellator primitive draws are less common
accumulatedDraws = new ArrayList<>(16); // Fewer draws than commands typically
relativeTransform = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH);
relativeTransform.identity(); // Delta from current GL state, starts at identity
lastFlushedGeneration = -1; // Reset so first draw triggers flush
lastFlushedTransform = null; // Will be set on first flush
stateGeneration = 0; // Reset state generation for fresh list
immediateModeRecorder = new ImmediateModeRecorder(); // For glBegin/glEnd/glVertex
compilationStackTrace = LOG_DISPLAY_LIST_COMPILATION ? Thread.currentThread().getStackTrace() : null;
// Initialize debug logging fields (only when logging enabled)
@@ -868,44 +804,12 @@ public class DisplayListManager {
drawRangeSources = null;
}
// Start compiling mode with per-draw callback (works for both root and nested lists now)
// Callback receives quads (GL_QUADS) and primitives (GL_TRIANGLES, GL_LINES, etc.)
TessellatorManager.setCompiling((quads, primitives, flags) -> {
final boolean hasQuads = !quads.isEmpty();
final boolean hasPrimitives = !primitives.isEmpty();
// Early exit to avoid allocations when nothing to accumulate
if (!hasQuads && !hasPrimitives) {
return;
}
if (matrixGeneration != lastFlushedGeneration) {
if (lastFlushedTransform == null) {
lastFlushedTransform = new Matrix4f();
}
lastFlushedTransform.set(relativeTransform);
flushMatrix();
lastFlushedGeneration = matrixGeneration;
}
final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform);
final int currentGeneration = matrixGeneration;
final int currentBatchId = stateGeneration;
final int cmdIndex = getCommandCount();
// Accumulate quads for batching at glEndList()
if (hasQuads) {
accumulatedDraws.add(new AccumulatedDraw(quads, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId));
}
// Accumulate primitives (lines, triangles) for batching at glEndList()
if (hasPrimitives) {
accumulatedPrimitiveDraws.add(new AccumulatedPrimitiveDraw(primitives, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId));
TessellatorManager.startCapturingDirect((tessellator) -> {
if (!tessellator.isEmpty()) {
addAccumulatedDraw(tessellator, false);
}
return true;
});
tessellatorCompiling = true;
// We hijack display list compilation completely - no GL11.glNewList() calls
}
/**
@@ -919,44 +823,26 @@ public class DisplayListManager {
final boolean isNested = !compilationStack.isEmpty();
// Stop compiling mode (works for both root and nested lists now)
if (tessellatorCompiling) {
TessellatorManager.stopCompiling();
tessellatorCompiling = false;
}
TessellatorManager.stopCapturingDirect();
final CompiledDisplayList compiled;
// Create CompiledDisplayList with both unoptimized and optimized versions
final CommandBuffer rawCommandBuffer = currentRecorder != null ? currentRecorder.getBuffer() : null;
final boolean hasCommands = rawCommandBuffer != null && rawCommandBuffer.size() > 0;
final CommandBuffer rawCommandBuffer = currentRecorder.getBuffer();
final boolean hasCommands = !rawCommandBuffer.isEmpty();
final boolean hasDraws = accumulatedDraws != null && !accumulatedDraws.isEmpty();
final boolean hasLineDraws = accumulatedLineDraws != null && !accumulatedLineDraws.isEmpty();
final boolean hasPrimitiveDraws = accumulatedPrimitiveDraws != null && !accumulatedPrimitiveDraws.isEmpty();
if (hasCommands || hasDraws || hasLineDraws || hasPrimitiveDraws) {
if (hasCommands || hasDraws) {
// Phase 1: Compile format-based VBOs (shared by both optimized and unoptimized paths)
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws);
// Phase 2: Compile immediate mode line VBO (shared by both paths)
final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws);
// Phase 3: Compile tessellator primitive VBOs (lines, triangles) - grouped by format
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws);
// Collect all owned VBOs (quads + immediate mode lines + tessellator primitives)
final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
final DisplayListVBO compiledBuffers = new DisplayListVBOBuilder().addDraws(accumulatedDraws).build();
// Build to CommandBuffer - optimize raw buffer to final buffer
final CommandBuffer finalBuffer = new CommandBuffer();
if (DEBUG_DISPLAY_LISTS) {
CommandBufferBuilder.buildUnoptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, finalBuffer);
} else {
CommandBufferBuilder.buildOptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, glListId, finalBuffer);
}
CommandBufferBuilder.buildFromRawBuffer(rawCommandBuffer, accumulatedDraws, finalBuffer);
// Free the recorder (and its buffer) after optimization
currentRecorder.free();
compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), ownedVbos);
compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), compiledBuffers);
} else {
// Free the recorder even if empty
if (currentRecorder != null) {
@@ -982,11 +868,7 @@ public class DisplayListManager {
glListMode = parentContext.listMode;
currentRecorder = parentContext.recorder;
accumulatedDraws = parentContext.draws;
accumulatedLineDraws = parentContext.lineDraws;
accumulatedPrimitiveDraws = parentContext.primitiveDraws;
relativeTransform = parentContext.transform;
tessellatorCompiling = parentContext.wasTessellatorCompiling;
immediateModeRecorder = parentContext.immediateRecorder;
compilationStackTrace = parentContext.stackTrace;
pendingTransformOps = parentContext.pendingOps;
multMatrixSources = parentContext.matrixSources;
@@ -999,10 +881,7 @@ public class DisplayListManager {
currentRecorder = null;
recordingThread = null;
accumulatedDraws = null;
accumulatedLineDraws = null;
accumulatedPrimitiveDraws = null;
relativeTransform = null;
immediateModeRecorder = null;
compilationStackTrace = null;
pendingTransformOps = null;
multMatrixSources = null;
@@ -1012,6 +891,31 @@ public class DisplayListManager {
}
}
private static void addAccumulatedDraw(DirectTessellator tessellator, boolean copyLast) {
final int cmdIndex = getCommandCount();
matrixBarrier();
if (accumulatedDraws.isEmpty()) {
accumulatedDraws.add(
new AccumulatedDraw(
tessellator, cmdIndex, stateGeneration, copyLast
)
);
return;
}
// Merge the previous draw call if possible
final AccumulatedDraw previous = accumulatedDraws.get(accumulatedDraws.size() - 1);
if (previous.format == tessellator.getVertexFormat() && previous.stateGeneration == stateGeneration) {
previous.mergeDraw(tessellator, copyLast);
return;
}
accumulatedDraws.add(
new AccumulatedDraw(tessellator, cmdIndex, stateGeneration, copyLast)
);
}
/**
* Execute a compiled display list.
*/
@@ -1019,11 +923,22 @@ public class DisplayListManager {
if (currentRecorder != null) {
recordCallList(list);
if (glListMode == GL11.GL_COMPILE) {
return;
if (getListMode() != GL11.GL_COMPILE) {
// Don't record the GL calls, we already recorded glCallList
final CommandRecorder recorder = currentRecorder;
currentRecorder = null;
executeDisplayList(list);
currentRecorder = recorder;
}
return;
}
executeDisplayList(list);
}
private static void executeDisplayList(int list) {
final CompiledDisplayList compiled = displayListCache.get(list);
if (compiled != null) {
final int prevList = currentRenderingList;
@@ -1056,326 +971,19 @@ public class DisplayListManager {
CompiledDisplayList compiled = displayListCache.remove(i);
if (compiled != null) {
compiled.delete();
} else {
GL11.glDeleteLists(i, 1);
}
}
// Also call legacy glDeleteLists for any lists we didn't handle
GL11.glDeleteLists(list, range);
}
/**
* Compile format-based VBOs from accumulated draws.
* Groups draws by vertex format and compiles each format's geometry into a single VBO.
* Both optimized and unoptimized paths share these VBOs.
*
* @param accumulatedDraws The accumulated draws to compile
* @return Map from format flags to compiled buffers (VBO + ranges)
*/
private static Map<CapturingTessellator.Flags, CompiledFormatBuffer> compileFormatBasedVBOs(
List<AccumulatedDraw> accumulatedDraws) {
if (accumulatedDraws == null || accumulatedDraws.isEmpty()) {
return Collections.emptyMap();
}
// Group draws by vertex format
final Map<CapturingTessellator.Flags, FormatBuffer> formatBuffers = new HashMap<>();
for (AccumulatedDraw draw : accumulatedDraws) {
formatBuffers.computeIfAbsent(draw.flags, FormatBuffer::new).addDraw(draw);
}
// Compile each format's geometry into a single VBO
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiled = new HashMap<>();
for (var entry : formatBuffers.entrySet()) {
compiled.put(entry.getKey(), entry.getValue().finish());
}
return compiled;
}
/**
* Compile line draws into a shared VBO.
*
* @param lineDraws The accumulated line draws
* @return Compiled line buffer, or null if no lines
*/
private static CompiledLineBuffer compileLineBuffer(List<AccumulatedLineDraw> lineDraws) {
if (lineDraws == null || lineDraws.isEmpty()) {
return null;
}
final LineBuffer buffer = new LineBuffer();
for (AccumulatedLineDraw draw : lineDraws) {
buffer.addDraw(draw);
}
return buffer.finish();
}
/**
* Extract owned VBOs from compiled buffers (quads + lines).
* These VBOs are shared by both optimized and unoptimized paths.
*
* @param compiledQuadBuffers The compiled quad format buffers
* @param compiledLineBuffer The compiled line buffer (may be null)
* @return Array of VBOs that need to be deleted when the display list is deleted
*/
private static VertexBuffer[] extractOwnedVbos(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
final List<VertexBuffer> vbos = new ArrayList<>();
// Add quad VBOs
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int i = 0; i < quadBufferArray.length; i++) {
vbos.add(quadBufferArray[i].vbo());
}
// Add immediate mode line VBO if present
if (compiledLineBuffer != null) {
vbos.add(compiledLineBuffer.vbo());
}
// Add tessellator primitive VBOs if present (one per format, separate for lines/triangles)
if (!compiledPrimitiveBuffers.isEmpty()) {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int i = 0; i < primBufferArray.length; i++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[i];
if (primBuffers.hasLines()) {
vbos.add(primBuffers.lineVbo());
}
if (primBuffers.hasTriangles()) {
vbos.add(primBuffers.triangleVbo());
}
}
}
return vbos.toArray(new VertexBuffer[0]);
}
/**
* Compile tessellator primitives (lines, triangles) into format-based VBOs.
* Groups draws by vertex format for optimal memory usage.
*
* @param primitiveDraws The accumulated primitive draws from tessellator callback
* @return Map of flags to compiled primitive buffers, empty map if no primitives
*/
private static Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compilePrimitiveBuffers(
List<AccumulatedPrimitiveDraw> primitiveDraws) {
if (primitiveDraws == null || primitiveDraws.isEmpty()) {
return Collections.emptyMap();
}
// Group draws by vertex format
final Map<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> formatBuffers = new HashMap<>();
final int size = primitiveDraws.size();
for (int i = 0; i < size; i++) {
final AccumulatedPrimitiveDraw draw = primitiveDraws.get(i);
formatBuffers.computeIfAbsent(draw.flags, TessellatorPrimitiveBuffer::new).addDraw(draw);
}
// Compile each format's geometry into VBOs
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiled = new HashMap<>();
@SuppressWarnings("unchecked")
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer>[] entries =
formatBuffers.entrySet().toArray(new Map.Entry[0]);
for (int i = 0; i < entries.length; i++) {
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> entry = entries[i];
final CompiledPrimitiveBuffers result = entry.getValue().finish();
if (result != null) {
compiled.put(entry.getKey(), result);
}
}
return compiled;
}
// ==================== Buffer-to-Buffer Optimization ====================
/**
* Build optimized command list using pre-compiled VBOs.
* Uses mergedRanges (consecutive same-transform draws combined) and collapses MODELVIEW transforms.
* (Package-private for testing)
*
* @param currentCommands Original matrix/state commands
* @param compiledQuadBuffers Pre-compiled format-based quad VBOs
* @param compiledLineBuffer Pre-compiled line VBO (may be null)
* @param glListId Display list ID for logging
* @return Optimized command array
*/
static DisplayListCommand[] buildOptimizedCommands(
List<DisplayListCommand> currentCommands,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
int glListId) {
final List<DisplayListCommand> optimized = new ArrayList<>();
final TransformOptimizer transformOpt = new TransformOptimizer(glListId);
// Collect all merged draw ranges (quads + lines + primitives) sorted by command index
final List<DrawRangeWithBuffer> allRanges = CommandBufferBuilder.collectDrawRanges(
compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Process command stream with interleaved draws
final OptimizationContextImpl ctx = new OptimizationContextImpl(transformOpt, optimized);
int rangeIndex = 0;
for (int i = 0; i < currentCommands.size(); i++) {
// Emit draw ranges (quads and lines) at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == i) {
emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized);
}
// Process the original command
final DisplayListCommand cmd = currentCommands.get(i);
if (cmd.handleOptimization(ctx)) {
optimized.add(cmd);
}
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized);
}
// Emit residual transform to match expected GL state
if (!transformOpt.isIdentity()) {
transformOpt.emitPendingTransform(optimized);
}
return optimized.toArray(new DisplayListCommand[0]);
}
/**
* Build optimized display list: batches draws with same flags, collapses MODELVIEW transforms.
* Instead of baking transforms into vertices, we emit collapsed MultMatrix commands at barriers.
* This properly handles nested display lists (CallList) which need GL state to be correct.
*
* <p>Transform collapsing strategy:
* <ul>
* <li>Track accumulated MODELVIEW transform during command stream analysis</li>
* <li>At barriers (Draw, CallList), emit a single MultMatrix if transform changed</li>
* <li>Push/Pop maintain proper stack semantics</li>
* <li>Vertices stay canonical (untransformed) in VBOs</li>
* </ul>
*/
// Package-private for testing
static OptimizedListResult buildOptimizedDisplayList(
List<DisplayListCommand> currentCommands,
List<AccumulatedDraw> accumulatedDraws,
List<AccumulatedPrimitiveDraw> accumulatedPrimitiveDraws,
int glListId) {
// Compile quad VBOs
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws);
// Compile tessellator primitive VBOs (lines, triangles) - grouped by format
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws);
// Extract owned VBOs (quads + primitives, no immediate mode lines in test path)
final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, null, compiledPrimitiveBuffers);
// Build optimized commands using the new unified path
final DisplayListCommand[] optimized = buildOptimizedCommands(currentCommands, compiledQuadBuffers, null, compiledPrimitiveBuffers, glListId);
return new OptimizedListResult(optimized, ownedVbos);
}
/**
* Emit a draw range command for the legacy path (testing).
* Uses delta-based transform emission via TransformOptimizer.
*/
private static void emitDrawRangeLegacy(DrawRangeWithBuffer drwb, TransformOptimizer transformOpt,
List<DisplayListCommand> output) {
final DrawRange range = drwb.range();
// Delta-based: only emit MultMatrix if transform differs from last emitted
if (transformOpt.needsTransformForDraw(range.transform())) {
transformOpt.emitTransformTo(output, range.transform());
}
output.add(new com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd(
drwb.vbo(),
range.startVertex(),
range.vertexCount(),
drwb.hasBrightness()
));
}
/**
* Implementation of OptimizationContext that wraps transform optimizer.
*/
@Desugar
private record OptimizationContextImpl(
TransformOptimizer transformOpt,
List<DisplayListCommand> output
) implements OptimizationContext {
@Override public Matrix4f getAccumulatedTransform() { return transformOpt.getAccumulated(); }
@Override public void loadIdentity() { transformOpt.loadIdentity(); }
@Override public void pushTransform() { transformOpt.pushTransform(); }
@Override public void popTransform() { transformOpt.popTransform(); }
@Override public void emitPendingTransform() { transformOpt.emitPendingTransform(output); }
@Override public void emitTransformTo(Matrix4f target) { transformOpt.emitTransformTo(output, target); }
@Override public void emit(DisplayListCommand cmd) { output.add(cmd); }
@Override public void markAbsoluteMatrix() { transformOpt.markAbsoluteMatrix(); }
@Override public boolean checkAndClearAbsoluteMatrix() { return transformOpt.checkAndClearAbsoluteMatrix(); }
}
/**
* Selects the optimal VertexFormat from GTNHLib defaults based on actual attribute usage.
* This reduces memory usage by excluding unused attributes.
*/
static VertexFormat selectOptimalFormat(CapturingTessellator.Flags flags) {
final boolean hasColor = flags.hasColor;
final boolean hasTexture = flags.hasTexture;
final boolean hasBrightness = flags.hasBrightness;
final boolean hasNormals = flags.hasNormals;
final VertexFormat format;
// Map flags to GTNHLib formats, ordered by guess at frequency/likelihood
if (!hasColor && hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE; // Entity models, common
} else if (!hasColor && !hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION; // Sky rendering, simple geometry
} else if (hasColor && hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR_TEXTURE; // Colored blocks/UI
} else if (!hasColor && hasTexture && hasBrightness && hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE_LIGHT_NORMAL; // BuildCraft fluids
} else if (!hasColor && hasTexture && !hasBrightness && hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE_NORMAL; // Lit geometry with normals
} else if (hasColor && hasTexture && hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP; // Colored lit blocks
} else if (hasColor && !hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR; // Colored lines/particles
} else {
format = DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL; // Full format fallback
}
return format;
}
/**
* Compile captured Tessellator quads into a VertexBuffer (VAO or VBO).
* Uses VertexBuffer for proper compatibility with fixed-function pipeline.
*
* @param quads The quads to compile
* @param flags The vertex attribute flags
* @return The uploaded VertexBuffer
*/
static VertexBuffer compileQuads(List<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags) {
// Select optimal predefined format from GTNHLib
final VertexFormat format = selectOptimalFormat(flags);
// Use VAOManager to create VAO with optimal format (falls back to VBO if unsupported)
final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_QUADS);
final ByteBuffer buffer = CapturingTessellator.quadsToBuffer(quads, format);
vao.upload(buffer);
return vao;
}
// ==================== DEBUG LOGGING ====================
private static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) {
public static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) {
LOGGER.debug(getCompiledDisplayListString(listId, compiled, stackTrace));
}
public static String getCompiledDisplayListString(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) {
final StringBuilder sb = new StringBuilder();
sb.append("\n========== Display List Compiled: ID=").append(listId).append(" ==========\n");
@@ -1391,7 +999,7 @@ public class DisplayListManager {
sb.append("Contents: No commands\n");
} else {
sb.append("Commands (").append(buffer.limit()).append(" bytes):\n");
dumpCommandBuffer(buffer, compiled.getComplexObjects(), compiled.getOwnedVbos(), sb);
dumpCommandBuffer(buffer, compiled.getComplexObjects(), sb);
}
}
@@ -1406,7 +1014,7 @@ public class DisplayListManager {
}
sb.append("========== End Display List ").append(listId).append(" ==========\n");
LOGGER.debug(sb.toString());
return sb.toString();
}
private static String identifySourceFromStackTrace(StackTraceElement[] stackTrace) {
@@ -1487,143 +1095,97 @@ public class DisplayListManager {
return className;
}
private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos, StringBuilder sb) {
private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, StringBuilder sb) {
if (buffer == null) return;
final long basePtr = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress(buffer);
final long basePtr = memAddress(buffer);
long ptr = basePtr;
final long end = basePtr + buffer.limit();
int cmdNum = 0;
int multMatrixIdx = 0; // Index into multMatrixSources for source tracking
int drawRangeIdx = 0; // Index into drawRangeSources for source tracking
while (ptr < end) {
final int opcode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr);
final int opcode = memGetInt(ptr);
final String cmdName = GLCommand.getName(opcode);
sb.append(" ").append(cmdNum++).append(": ").append(cmdName);
// Add command-specific details
switch (opcode) {
case GLCommand.ENABLE, GLCommand.DISABLE -> {
final int cap = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int cap = memGetInt(ptr + 4);
sb.append("(").append(GLDebug.getCapabilityName(cap)).append(")");
ptr += 8;
}
case GLCommand.BIND_TEXTURE -> {
final int target = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int texture = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
final int target = memGetInt(ptr + 4);
final int texture = memGetInt(ptr + 8);
sb.append("(target=").append(target).append(", texture=").append(texture).append(")");
ptr += 12;
}
case GLCommand.DRAW_RANGE -> {
final int vboIdx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int start = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
final int brightness = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16);
sb.append("(vbo=").append(vboIdx).append(", start=").append(start)
.append(", count=").append(count).append(", brightness=").append(brightness != 0).append(")");
final int vboIdx = memGetInt(ptr + 4);
sb.append("(vbo=").append(vboIdx).append(")");
// Show draw source if available
if (drawRangeSources != null && drawRangeIdx < drawRangeSources.size()) {
sb.append(" [from: ").append(drawRangeSources.get(drawRangeIdx)).append("]");
}
drawRangeIdx++;
}
case GLCommand.DRAW_RANGE_RESTORE -> {
final int vboIdx = memGetInt(ptr + 4);
final int start = memGetInt(ptr + 8);
final int count = memGetInt(ptr + 12);
final int brightness = memGetInt(ptr + 16);
sb.append("(vbo=").append(vboIdx).append(", start=").append(start)
.append(", count=").append(count).append(", brightness=").append(brightness != 0).append(")");
// Show draw source if available
if (drawRangeSources != null && drawRangeIdx < drawRangeSources.size()) {
sb.append(" [from: ").append(drawRangeSources.get(drawRangeIdx)).append("]");
}
drawRangeIdx++;
ptr += 20;
}
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> {
// Show source ops if available (only for MULT_MATRIX from recording phase)
if (opcode == GLCommand.MULT_MATRIX && multMatrixSources != null && multMatrixIdx < multMatrixSources.size()) {
final List<String> sources = multMatrixSources.get(multMatrixIdx);
sb.append(" [from: ").append(String.join(" -> ", sources)).append("]");
sb.append("(");
for (int i = 0; i < 16; i++) {
float value = MemoryUtilities.memGetFloat(ptr + 4 + i * 4);
sb.append(i == 0 ? value : ", " + value);
}
multMatrixIdx++;
ptr += 68; // cmd + 16 floats
sb.append(")");
}
case GLCommand.COLOR -> {
final float r = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4));
final float g = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8));
final float b = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12));
final float a = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16));
final float r = Float.intBitsToFloat(memGetInt(ptr + 4));
final float g = Float.intBitsToFloat(memGetInt(ptr + 8));
final float b = Float.intBitsToFloat(memGetInt(ptr + 12));
final float a = Float.intBitsToFloat(memGetInt(ptr + 16));
sb.append("(").append(r).append(", ").append(g).append(", ").append(b).append(", ").append(a).append(")");
ptr += 20;
}
case GLCommand.DEPTH_MASK -> {
final int flag = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int flag = memGetInt(ptr + 4);
sb.append("(").append(flag != 0).append(")");
ptr += 8;
}
case GLCommand.BLEND_FUNC -> {
final int srcRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int dstRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
final int srcAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
final int dstAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16);
final int srcRgb = memGetInt(ptr + 4);
final int dstRgb = memGetInt(ptr + 8);
final int srcAlpha = memGetInt(ptr + 12);
final int dstAlpha = memGetInt(ptr + 16);
sb.append("(srcRgb=").append(srcRgb).append(", dstRgb=").append(dstRgb)
.append(", srcAlpha=").append(srcAlpha).append(", dstAlpha=").append(dstAlpha).append(")");
ptr += 20;
}
case GLCommand.CALL_LIST -> {
final int calledList = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int calledList = memGetInt(ptr + 4);
sb.append("(").append(calledList).append(")");
ptr += 8;
}
case GLCommand.MATRIX_MODE -> {
final int mode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int mode = memGetInt(ptr + 4);
sb.append("(").append(mode == GL11.GL_MODELVIEW ? "MODELVIEW" : mode == GL11.GL_PROJECTION ? "PROJECTION" : mode).append(")");
ptr += 8;
}
case GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.LOAD_IDENTITY -> ptr += 4;
case GLCommand.COMPLEX_REF -> {
final int idx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int idx = memGetInt(ptr + 4);
final Object obj = complexObjects != null && idx < complexObjects.length ? complexObjects[idx] : null;
sb.append("(idx=").append(idx).append(", type=").append(obj != null ? obj.getClass().getSimpleName() : "null").append(")");
ptr += 8;
}
default -> {
// Skip based on command size (from CompiledDisplayList.getCommandSize logic)
ptr += getCommandSize(opcode, ptr);
}
}
ptr += GLCommand.getCommandSize(opcode, ptr);
sb.append("\n");
}
}
/**
* Get the size of a command in bytes for buffer iteration.
*/
private static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_BUFFER -> 8;
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI, GLCommand.CLEAR_DEPTH -> 12;
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI, GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF,
GLCommand.NORMAL -> 16;
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR,
GLCommand.DRAW_RANGE -> 20;
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28;
case GLCommand.ROTATE -> 36;
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52;
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68;
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
yield 16 + count * 4;
}
case GLCommand.DRAW_BUFFERS -> 40;
default -> 8; // Default to 8 bytes to avoid infinite loop
};
}
}
@@ -1,25 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
/**
* Represents a vertex range within a shared VBO, along with its transform.
* Used during format-based batching to track where each draw's vertices are stored.
*
* <p>The restoreData field holds last vertex attributes for GL state restoration
* after VBO rendering (immediate mode draws only). Null for tessellator draws.
*/
@Desugar
public record DrawRange(
int startVertex,
int vertexCount,
Matrix4f transform,
int commandIndex,
AccumulatedDraw.RestoreData restoreData
) {
DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {
this(startVertex, vertexCount, transform, commandIndex, null);
}
}
@@ -1,43 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Helper record pairing a DrawRange with its VBO and vertex format flags.
* Used for sorting ranges by command index while retaining VBO reference.
* Works for both quad ranges (from CompiledFormatBuffer) and line ranges (from CompiledLineBuffer).
*/
@Desugar
record DrawRangeWithBuffer(
DrawRange range,
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawSource source
) {
boolean hasBrightness() {
return flags != null && flags.hasBrightness;
}
/**
* Source of a draw command for debug logging.
*/
enum DrawSource {
TESSELLATOR_QUADS("tessellator quads"),
TESSELLATOR_LINES("tessellator lines"),
TESSELLATOR_TRIANGLES("tessellator triangles"),
IMMEDIATE_MODE_LINES("immediate mode lines");
private final String description;
DrawSource(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
}
@@ -1,106 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates geometry for a single vertex format during display list compilation.
* Tracks merged ranges (same-transform draws combined) and per-draw ranges (1:1).
*/
class FormatBuffer {
final CapturingTessellator.Flags flags;
final List<ModelQuadViewMutable> allQuads = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingGeneration = -1;
private int pendingStateGen = -1;
// Track last restore data for merged draws (uses the LAST draw's data)
private AccumulatedDraw.RestoreData pendingRestoreData = null;
FormatBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/** Add a draw, tracking both merged and per-draw ranges. */
void addDraw(AccumulatedDraw draw) {
final int vertexCount = draw.quads.size() * 4; // 4 vertices per quad
// Always track per-draw range for unoptimized path (includes restoreData)
perDrawRanges.add(new DrawRange(
currentVertexOffset, vertexCount, draw.transform, draw.commandIndex, draw.restoreData
));
// Merge logic for optimized path:
// - same matrixGeneration = same matrix transform context
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingGeneration != -1
&& pendingGeneration == draw.matrixGeneration
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
// Update restoreData to the LAST draw's data (used after merged draw completes)
pendingRestoreData = draw.restoreData;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingGeneration = draw.matrixGeneration;
pendingStateGen = draw.stateGeneration;
pendingRestoreData = draw.restoreData;
}
allQuads.addAll(draw.quads);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingGeneration != -1) {
mergedRanges.add(new DrawRange(
pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex, pendingRestoreData
));
pendingTransform = null;
pendingGeneration = -1;
pendingStateGen = -1;
pendingRestoreData = null;
}
}
/** Compile accumulated quads into a VBO. */
CompiledFormatBuffer finish() {
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = DisplayListManager.compileQuads(allQuads, flags);
return new CompiledFormatBuffer(
vbo,
flags,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
}
@@ -553,6 +553,57 @@ public final class GLDebug {
};
}
public static String getFramebufferStatusName(int status) {
return switch (status) {
case GL30.GL_FRAMEBUFFER_COMPLETE -> "COMPLETE";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "INCOMPLETE_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "INCOMPLETE_MISSING_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER -> "INCOMPLETE_DRAW_BUFFER";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER -> "INCOMPLETE_READ_BUFFER";
case GL30.GL_FRAMEBUFFER_UNSUPPORTED -> "UNSUPPORTED";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE -> "INCOMPLETE_MULTISAMPLE";
case 0 -> "NO_FRAMEBUFFER_BOUND";
default -> String.format("UNKNOWN(0x%X)", status);
};
}
public static String getInternalFormatName(int format) {
return switch (format) {
// Basic
case GL11.GL_RGBA -> "RGBA";
case GL11.GL_RGB -> "RGB";
// 8-bit normalized
case GL30.GL_R8 -> "R8";
case GL30.GL_RG8 -> "RG8";
case GL11.GL_RGB8 -> "RGB8";
case GL11.GL_RGBA8 -> "RGBA8";
// 8-bit signed normalized
case 0x8F94 -> "R8_SNORM";
case 0x8F95 -> "RG8_SNORM";
case 0x8F96 -> "RGB8_SNORM";
case 0x8F97 -> "RGBA8_SNORM";
// 16-bit normalized
case GL30.GL_R16 -> "R16";
case GL30.GL_RG16 -> "RG16";
case GL11.GL_RGB16 -> "RGB16";
case GL11.GL_RGBA16 -> "RGBA16";
// 16-bit float
case GL30.GL_R16F -> "R16F";
case GL30.GL_RG16F -> "RG16F";
case GL30.GL_RGB16F -> "RGB16F";
case GL30.GL_RGBA16F -> "RGBA16F";
// 32-bit float
case GL30.GL_R32F -> "R32F";
case GL30.GL_RG32F -> "RG32F";
case GL30.GL_RGB32F -> "RGB32F";
case GL30.GL_RGBA32F -> "RGBA32F";
// Packed
case GL30.GL_R11F_G11F_B10F -> "R11F_G11F_B10F";
case GL11.GL_RGB10_A2 -> "RGB10_A2";
default -> String.format("0x%X", format);
};
}
private static DebugState debugState;
private interface DebugState {
@@ -1,8 +1,10 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import com.gtnewhorizons.angelica.glsm.recording.commands.TexImage2DCmd;
@@ -23,7 +25,6 @@ import com.gtnewhorizons.angelica.glsm.stacks.MatrixModeStack;
import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack;
import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack;
import com.gtnewhorizons.angelica.glsm.states.ClientArrayState;
import com.gtnewhorizons.angelica.glsm.states.Color4;
@@ -57,14 +58,17 @@ import org.joml.Vector3d;
import org.joml.Vector3f;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.APPLEVertexArrayObject;
import org.lwjgl.opengl.ARBMultitexture;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.Display;
@@ -89,6 +93,8 @@ import static com.gtnewhorizons.angelica.glsm.Vendor.MESA;
import static com.gtnewhorizons.angelica.glsm.Vendor.NVIDIA;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import static com.gtnewhorizon.gtnhlib.client.opengl.GLCaps.*;
/**
* OpenGL State Manager - Provides cached state tracking and management for OpenGL operations.
*
@@ -331,6 +337,9 @@ public class GLStateManager {
@Getter protected static int activeProgram = 0;
@Getter protected static int listBase = 0;
@Getter protected static int boundVBO;
@Getter protected static int boundVAO;
public static void reset() {
runningSplash = true;
while(!attribs.isEmpty()) {
@@ -812,15 +821,21 @@ public class GLStateManager {
case GL11.GL_MATRIX_MODE -> matrixMode.getMode();
case GL11.GL_SHADE_MODEL -> shadeModelState.getValue();
case GL11.GL_TEXTURE_BINDING_2D -> getBoundTextureForServerState();
case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue();
case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue();
case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix);
case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix);
case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha();
case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb();
case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha();
case GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb();
case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue();
case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue();
case GL15.GL_ARRAY_BUFFER_BINDING -> boundVBO;
case GL20.GL_CURRENT_PROGRAM -> activeProgram;
case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix);
case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix);
case GL30.GL_VERTEX_ARRAY_BINDING -> boundVAO;
default -> GL11.glGetInteger(pname);
};
@@ -1064,42 +1079,34 @@ public class GLStateManager {
throw new UnsupportedOperationException("Not yet implemented (" + name + ")");
}
}
// Records glBegin/glEnd/glVertex and compiles them to a VBO
// Currently only used inside of display lists
public static void glNormal3b(byte nx, byte ny, byte nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(b2f(nx), b2f(ny), b2f(nz));
}
ImmediateModeRecorder.setNormal(b2f(nx), b2f(ny), b2f(nz));
return;
}
GL11.glNormal3b(nx, ny, nz);
}
public static void glNormal3d(double nx, double ny, double nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz);
return;
}
GL11.glNormal3d(nx, ny, nz);
}
public static void glNormal3f(float nx, float ny, float nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(nx, ny, nz);
}
ImmediateModeRecorder.setNormal(nx, ny, nz);
return;
}
GL11.glNormal3f(nx, ny, nz);
}
public static void glNormal3i(int nx, int ny, int nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz);
return;
}
GL11.glNormal3i(nx, ny, nz);
@@ -1535,80 +1542,56 @@ public class GLStateManager {
public static void glTexCoord1f(float s) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, 0.0f);
}
ImmediateModeRecorder.setTexCoord(s, 0.0f);
return;
}
GL11.glTexCoord1f(s);
}
public static void glTexCoord1d(double s) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, 0.0f);
}
ImmediateModeRecorder.setTexCoord((float) s, 0.0f);
return;
}
GL11.glTexCoord1d(s);
}
public static void glTexCoord2f(float s, float t) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t);
}
ImmediateModeRecorder.setTexCoord(s, t);
return;
}
GL11.glTexCoord2f(s, t);
}
public static void glTexCoord2d(double s, double t) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
ImmediateModeRecorder.setTexCoord((float) s, (float) t);
return;
}
GL11.glTexCoord2d(s, t);
}
public static void glTexCoord3f(float s, float t, float r) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t); // Only track s,t for 2D textures
}
ImmediateModeRecorder.setTexCoord(s, t); // Only track s,t for 2D textures
return;
}
GL11.glTexCoord3f(s, t, r);
}
public static void glTexCoord3d(double s, double t, double r) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
ImmediateModeRecorder.setTexCoord((float) s, (float) t);
return;
}
GL11.glTexCoord3d(s, t, r);
}
public static void glTexCoord4f(float s, float t, float r, float q) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t);
}
ImmediateModeRecorder.setTexCoord(s, t);
return;
}
GL11.glTexCoord4f(s, t, r, q);
}
public static void glTexCoord4d(double s, double t, double r, double q) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
ImmediateModeRecorder.setTexCoord((float) s, (float) t);
return;
}
GL11.glTexCoord4d(s, t, r, q);
@@ -1748,10 +1731,7 @@ public class GLStateManager {
public static void glBegin(int mode) {
if (DisplayListManager.isRecording()) {
// Record to immediate mode recorder
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.begin(mode);
}
ImmediateModeRecorder.begin(mode);
return; // Don't call actual GL during recording
}
GL11.glBegin(mode);
@@ -1760,14 +1740,10 @@ public class GLStateManager {
public static void glEnd() {
if (DisplayListManager.isRecording()) {
// Record to immediate mode recorder and flush geometry immediately
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
// end() returns quads immediately (like tessellator callback)
final ImmediateModeRecorder.Result result = recorder.end();
if (result != null) {
// Add draw at current command position for correct interleaving
DisplayListManager.addImmediateModeDraw(result);
}
final DirectTessellator result = ImmediateModeRecorder.end();
if (result != null) {
// Add draw at current command position for correct interleaving
DisplayListManager.addImmediateModeDraw(result);
}
return; // Don't call actual GL during recording
}
@@ -1779,10 +1755,7 @@ public class GLStateManager {
public static void glVertex2f(float x, float y) {
final boolean recording = DisplayListManager.isRecording();
if (recording) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex(x, y, 0.0f);
}
ImmediateModeRecorder.vertex(x, y, 0.0f);
return;
}
GL11.glVertex2f(x, y);
@@ -1790,10 +1763,7 @@ public class GLStateManager {
public static void glVertex2d(double x, double y) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex((float) x, (float) y, 0.0f);
}
ImmediateModeRecorder.vertex((float) x, (float) y, 0.0f);
return;
}
GL11.glVertex2d(x, y);
@@ -1801,10 +1771,7 @@ public class GLStateManager {
public static void glVertex3f(float x, float y, float z) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex(x, y, z);
}
ImmediateModeRecorder.vertex(x, y, z);
return;
}
GL11.glVertex3f(x, y, z);
@@ -1812,10 +1779,7 @@ public class GLStateManager {
public static void glVertex3d(double x, double y, double z) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex((float) x, (float) y, (float) z);
}
ImmediateModeRecorder.vertex((float) x, (float) y, (float) z);
return;
}
GL11.glVertex3d(x, y, z);
@@ -1841,13 +1805,6 @@ public class GLStateManager {
GL11.glDrawElements(mode, indices);
}
public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset);
}
public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
@@ -1855,6 +1812,21 @@ public class GLStateManager {
GL11.glDrawElements(mode, count, type, indices);
}
public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
if (isVAOBound()) {
DisplayListManager.recordDrawElements(mode, indices_count, type, indices_buffer_offset);
} else {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
if (recordMode == RecordMode.COMPILE) {
return;
}
}
GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset);
}
public static void glDrawBuffer(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
@@ -1868,12 +1840,13 @@ public class GLStateManager {
public static void glDrawArrays(int mode, int first, int count) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
final ImmediateModeRecorder.Result result = recorder.processDrawArrays(mode, first, count);
if (result != null) {
DisplayListManager.addImmediateModeDraw(result);
}
if (isVAOBound() || isVBOBound()) { // TODO VBO rendering needs to be replaced with proper VAO compilation
DisplayListManager.recordDrawArrays(mode, first, count);
return;
}
final DirectTessellator result = ImmediateModeRecorder.processDrawArrays(mode, first, count);
if (result != null) {
DisplayListManager.addImmediateModeDraw(result);
}
return;
}
@@ -1884,52 +1857,70 @@ public class GLStateManager {
// State is tracked globally in clientArrayState, which ImmediateModeRecorder reads from directly.
public static void glVertexPointer(int size, int stride, FloatBuffer pointer) {
clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer);
if (!isVAOBound()) {
clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer);
}
GL11.glVertexPointer(size, stride, pointer);
}
public static void glVertexPointer(int size, int type, int stride, ByteBuffer pointer) {
clientArrayState.setVertexPointer(size, type, stride, pointer);
if (!isVAOBound()) {
clientArrayState.setVertexPointer(size, type, stride, pointer);
}
GL11.glVertexPointer(size, type, stride, pointer);
}
public static void glVertexPointer(int size, int type, int stride, long pointer_buffer_offset) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setVertexPointer(size, type, stride, null);
if (!isVAOBound()) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setVertexPointer(size, type, stride, null);
}
GL11.glVertexPointer(size, type, stride, pointer_buffer_offset);
}
public static void glColorPointer(int size, int stride, FloatBuffer pointer) {
clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer);
if (!isVAOBound()) {
clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer);
}
GL11.glColorPointer(size, stride, pointer);
}
public static void glColorPointer(int size, int type, int stride, ByteBuffer pointer) {
clientArrayState.setColorPointer(size, type, stride, pointer);
if (!isVAOBound()) {
clientArrayState.setColorPointer(size, type, stride, pointer);
}
GL11.glColorPointer(size, type, stride, pointer);
}
public static void glColorPointer(int size, boolean unsigned, int stride, ByteBuffer pointer) {
final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE;
clientArrayState.setColorPointer(size, type, stride, pointer);
if (!isVAOBound()) {
final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE;
clientArrayState.setColorPointer(size, type, stride, pointer);
}
GL11.glColorPointer(size, unsigned, stride, pointer);
}
public static void glColorPointer(int size, int type, int stride, long pointer_buffer_offset) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setColorPointer(size, type, stride, null);
if (!isVAOBound()) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setColorPointer(size, type, stride, null);
}
GL11.glColorPointer(size, type, stride, pointer_buffer_offset);
}
public static void glEnableClientState(int cap) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true);
if (!isVAOBound()) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true);
}
GL11.glEnableClientState(cap);
}
public static void glDisableClientState(int cap) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false);
if (!isVAOBound()) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false);
}
GL11.glDisableClientState(cap);
}
@@ -2816,7 +2807,7 @@ public class GLStateManager {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameteri called during display list recording with no cached TextureInfo for texture %d. " +
"Cannot query OpenGL state during compilation!", texture));
"Cannot query OpenGL state during compilation!", texture));
}
return defaultSupplier.getAsInt();
}
@@ -2832,7 +2823,7 @@ public class GLStateManager {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameteri called during display list recording with uncached pname 0x%s for texture %d. " +
"Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture));
"Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture));
}
yield defaultSupplier.getAsInt();
}
@@ -3771,6 +3762,46 @@ public class GLStateManager {
}
}
public static void glBindBuffer(int target, int buffer) {
if (target == GL15.GL_ARRAY_BUFFER) {
// if (boundVBO == buffer) return; TODO figure out why this breaks switching async occlusion mode
boundVBO = buffer;
}
GL15.glBindBuffer(target, buffer);
}
public static void glBindVertexArray(int array) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordBindVAO(array);
// Since the vao needs to be bound to do stuff like state setup & data upload, it'll still execute the bind call.
// This is technically wrong, but I'm not sure if there's a better solution here.
}
if (boundVAO != array) {
boundVAO = array;
GL30.glBindVertexArray(array);
}
}
public static void glBindVertexArrayAPPLE(int array) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordBindVAO(array);
// Since the vao needs to be bound to do stuff like state setup & data upload, it'll still execute the bind call.
// This is technically wrong, but I'm not sure if there's a better solution here.
}
if (boundVAO != array) {
boundVAO = array;
APPLEVertexArrayObject.glBindVertexArrayAPPLE(array);
}
}
public static boolean isVBOBound() {
return boundVBO != 0;
}
public static boolean isVAOBound() {
return boundVAO != 0;
}
public static boolean vendorIsAMD() {
return VENDOR == AMD;
}
@@ -3835,6 +3866,12 @@ public class GLStateManager {
}
}
private static void checkMismatch(int cap) {
if (GLStateManager.glGetInteger(cap) != GL11.glGetInteger(cap)) {
throw new IllegalStateException("GLSM Mismatch! Cached: " + GLStateManager.glGetInteger(cap) + ", actual: " + GL11.glGetInteger(cap));
}
}
public static boolean isFramebufferEnabled() {
return OpenGlHelper.framebufferSupported && Minecraft.getMinecraft().gameSettings.fboEnable;
}
@@ -1,134 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates line geometry during display list compilation.
* All line draws are collected here, then compiled into a single VBO.
* <p>
* Lines all use the same format (POSITION_COLOR), so no format-based grouping needed.
* <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>
*/
class LineBuffer {
final List<ImmediateModeRecorder.LineVertex> allVertices = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingStateGen = -1;
/**
* Add a line draw to this buffer.
* Tracks both merged (for optimized) and per-draw (for unoptimized) ranges.
*/
void addDraw(AccumulatedLineDraw draw) {
int vertexCount = draw.lines.size(); // Each LineVertex is one vertex, lines come in pairs
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTransform != null
&& pendingTransform.equals(draw.transform)
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingStateGen = draw.stateGeneration;
}
allVertices.addAll(draw.lines);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
pendingTransform = null;
pendingStateGen = -1;
}
}
/**
* Compile all accumulated line vertices into a single VBO.
* @return The compiled buffer with VBO and both range types, or null if empty
*/
CompiledLineBuffer finish() {
if (allVertices.isEmpty()) {
return null;
}
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = compileLinesToVBO(allVertices);
return new CompiledLineBuffer(
vbo,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
/**
* Compile line vertices into a VertexBuffer (VAO or VBO).
* Lines use POSITION_COLOR format (x, y, z, color).
*/
private static VertexBuffer compileLinesToVBO(List<ImmediateModeRecorder.LineVertex> lines) {
final VertexFormat format = DefaultVertexFormat.POSITION_COLOR;
final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_LINES);
// POSITION_COLOR format: 3 floats (12 bytes) + 4 bytes color = 16 bytes per vertex
final int vertexSize = format.getVertexSize();
final ByteBuffer buffer = org.lwjgl.BufferUtils.createByteBuffer(vertexSize * lines.size());
for (ImmediateModeRecorder.LineVertex v : lines) {
buffer.putFloat(v.x);
buffer.putFloat(v.y);
buffer.putFloat(v.z);
buffer.putInt(v.color);
}
buffer.flip();
vao.upload(buffer);
return vao;
}
}
@@ -1,12 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
/**
* Result of building an optimized display list.
* Contains both the commands and the shared VBOs that need lifecycle management.
*/
@Desugar
record OptimizedListResult(DisplayListCommand[] commands, VertexBuffer[] ownedVbos) {}
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.dsa.DSAARB;
import com.gtnewhorizons.angelica.glsm.dsa.DSAAccess;
import com.gtnewhorizons.angelica.glsm.dsa.DSACore;
import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
@@ -28,6 +29,8 @@ import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.GL44;
import org.lwjgl.opengl.NVXGpuMemoryInfo;
import net.coderbot.iris.gl.shader.StandardMacros;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
@@ -44,9 +47,12 @@ public class RenderSystem {
private static boolean supportsSSBO;
private static boolean supportsBufferStorage;
private static boolean supportsClearTexture;
private static boolean supportsTesselation;
private static boolean supportsSamplerObjects;
private static int maxImageUnits;
private static int maxSSBOBindings;
private static int maxGlslVersion;
private static boolean supportsGpuShader4;
// Sampler object state tracking (null if unsupported)
private static int[] samplers;
@@ -73,6 +79,7 @@ public class RenderSystem {
}
supportsCompute = supportsCompute();
supportsTesselation = GLStateManager.capabilities.GL_ARB_tessellation_shader || GLStateManager.capabilities.OpenGL40;
supportsImageLoadStore = GLStateManager.capabilities.OpenGL42 || GLStateManager.capabilities.GL_ARB_shader_image_load_store || GLStateManager.capabilities.GL_EXT_shader_image_load_store;
supportsSSBO = GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_shader_storage_buffer_object;
@@ -110,6 +117,10 @@ public class RenderSystem {
samplers = new int[GL11.glGetInteger(GL20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS)];
}
maxGlslVersion = Integer.parseInt(StandardMacros.getGlVersion(GL20.GL_SHADING_LANGUAGE_VERSION));
supportsGpuShader4 = GLStateManager.capabilities.GL_EXT_gpu_shader4;
LOGGER.info("Max GLSL version: {}, GPU Shader4: {}", maxGlslVersion, supportsGpuShader4);
LOGGER.info("Image Load/Store: {}, Max Image Units: {}", supportsImageLoadStore, maxImageUnits);
LOGGER.info("SSBO: {}, Max SSBO Bindings: {}", supportsSSBO, maxSSBOBindings);
LOGGER.info("Buffer Storage: {}, Clear Texture: {}, Sampler Objects: {}", supportsBufferStorage, supportsClearTexture, supportsSamplerObjects);
@@ -124,8 +135,11 @@ public class RenderSystem {
}
public static void texImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) {
GL11.glBindTexture(target, texture);
GLStateManager.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
if (target == GL11.GL_TEXTURE_2D && level == 0) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
}
public static void uniformMatrix4fv(int location, boolean transpose, FloatBuffer matrix) {
@@ -318,7 +332,7 @@ public class RenderSystem {
}
public static void bindBuffer(int target, int buffer) {
GL15.glBindBuffer(target, buffer);
GLStateManager.glBindBuffer(target, buffer);
}
public static void memoryBarrier(int barriers) {
@@ -407,10 +421,12 @@ public class RenderSystem {
}
public static void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, int[] data) {
final ByteBuffer buf = BufferUtils.createByteBuffer(data.length * 4);
buf.asIntBuffer().put(data);
if (GLStateManager.capabilities.OpenGL43) {
GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, (ByteBuffer) null);
GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
} else if (GLStateManager.capabilities.GL_ARB_clear_buffer_object) {
ARBClearBufferObject.glClearBufferSubData(target, internalFormat, offset, size, format, type, (ByteBuffer) null);
ARBClearBufferObject.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
}
}
@@ -447,6 +463,26 @@ public class RenderSystem {
dsaState.textureStorage3D(texture, target, levels, internalFormat, width, height, depth);
}
public static int getMaxGlslVersion() {
return maxGlslVersion;
}
public static boolean supportsGpuShader4() {
return supportsGpuShader4;
}
public static boolean supportsSnormFormats() {
return GLStateManager.capabilities.OpenGL31;
}
public static boolean supportsPackedFloatRenderable() {
return GLStateManager.capabilities.OpenGL30 && maxGlslVersion >= 130;
}
public static boolean supportsTesselation() {
return supportsTesselation;
}
public static boolean supportsSamplerObjects() {
return supportsSamplerObjects;
}
@@ -1,246 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates tessellator primitives (lines, triangles) for a single vertex format during display list compilation.
* Similar to FormatBuffer but handles ModelPrimitiveView instances instead of quads.
* <p>
* Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color),
* this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size.
* <p>
* Primitives are separated by draw mode (GL_LINES, GL_TRIANGLES) into separate VBOs.
*/
class TessellatorPrimitiveBuffer {
final CapturingTessellator.Flags flags;
// Accumulated primitives separated by type
final List<ModelLine> allLines = new ArrayList<>();
final List<ModelTriangle> allTriangles = new ArrayList<>();
// Ranges for lines
final List<DrawRange> lineMergedRanges = new ArrayList<>();
final List<DrawRange> linePerDrawRanges = new ArrayList<>();
int currentLineVertexOffset = 0;
private int pendingLineStartVertex = -1;
private int pendingLineVertexCount = 0;
private Matrix4f pendingLineTransform = null;
private int pendingLineCommandIndex = -1;
private int pendingLineStateGen = -1;
// Ranges for triangles
final List<DrawRange> triangleMergedRanges = new ArrayList<>();
final List<DrawRange> trianglePerDrawRanges = new ArrayList<>();
int currentTriangleVertexOffset = 0;
private int pendingTriangleStartVertex = -1;
private int pendingTriangleVertexCount = 0;
private Matrix4f pendingTriangleTransform = null;
private int pendingTriangleCommandIndex = -1;
private int pendingTriangleStateGen = -1;
TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/**
* Add a primitive draw to this buffer.
* Separates lines and triangles, tracking ranges for both merged and per-draw paths.
*/
void addDraw(AccumulatedPrimitiveDraw draw) {
final List<ModelPrimitiveView> primitives = draw.primitives;
final int size = primitives.size();
// Single pass: count and collect primitives by type
int lineCount = 0;
int triangleCount = 0;
for (int i = 0; i < size; i++) {
final ModelPrimitiveView prim = primitives.get(i);
if (prim instanceof ModelLine ml) {
allLines.add(ml);
lineCount++;
} else if (prim instanceof ModelTriangle mt) {
allTriangles.add(mt);
triangleCount++;
}
}
// Process lines
if (lineCount > 0) {
final int lineVertexCount = lineCount * 2; // 2 vertices per line
linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingLineTransform != null
&& pendingLineTransform.equals(draw.transform)
&& pendingLineStateGen == draw.stateGeneration;
if (canMerge) {
pendingLineVertexCount += lineVertexCount;
} else {
flushPendingLineRange();
pendingLineStartVertex = currentLineVertexOffset;
pendingLineVertexCount = lineVertexCount;
pendingLineTransform = new Matrix4f(draw.transform);
pendingLineCommandIndex = draw.commandIndex;
pendingLineStateGen = draw.stateGeneration;
}
currentLineVertexOffset += lineVertexCount;
}
// Process triangles
if (triangleCount > 0) {
final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle
trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTriangleTransform != null
&& pendingTriangleTransform.equals(draw.transform)
&& pendingTriangleStateGen == draw.stateGeneration;
if (canMerge) {
pendingTriangleVertexCount += triangleVertexCount;
} else {
flushPendingTriangleRange();
pendingTriangleStartVertex = currentTriangleVertexOffset;
pendingTriangleVertexCount = triangleVertexCount;
pendingTriangleTransform = new Matrix4f(draw.transform);
pendingTriangleCommandIndex = draw.commandIndex;
pendingTriangleStateGen = draw.stateGeneration;
}
currentTriangleVertexOffset += triangleVertexCount;
}
}
private void flushPendingLineRange() {
if (pendingLineTransform != null) {
lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex));
pendingLineTransform = null;
pendingLineStateGen = -1;
}
}
private void flushPendingTriangleRange() {
if (pendingTriangleTransform != null) {
triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex));
pendingTriangleTransform = null;
pendingTriangleStateGen = -1;
}
}
/**
* Compile all accumulated primitives into VBOs using optimal vertex format.
* @return The compiled buffers with separate VBOs for lines and triangles, or null if empty
*/
CompiledPrimitiveBuffers finish() {
flushPendingLineRange();
flushPendingTriangleRange();
if (allLines.isEmpty() && allTriangles.isEmpty()) {
return null;
}
// Use optimal format based on flags (same logic as quads)
final VertexFormat format = DisplayListManager.selectOptimalFormat(flags);
final VertexBuffer lineVbo = allLines.isEmpty() ? null : compileLinesToVBO(format);
final VertexBuffer triangleVbo = allTriangles.isEmpty() ? null : compileTrianglesToVBO(format);
return new CompiledPrimitiveBuffers(
flags,
lineVbo,
lineMergedRanges.toArray(new DrawRange[0]),
linePerDrawRanges.toArray(new DrawRange[0]),
triangleVbo,
triangleMergedRanges.toArray(new DrawRange[0]),
trianglePerDrawRanges.toArray(new DrawRange[0])
);
}
private VertexBuffer compileLinesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allLines.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 2);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allLines.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_LINES);
vbo.upload(buffer);
return vbo;
}
private VertexBuffer compileTrianglesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allTriangles.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 3);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allTriangles.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_TRIANGLES);
vbo.upload(buffer);
return vbo;
}
/**
* Write a primitive's vertices to the buffer using the format specified by flags.
* Only writes attributes that are present in the format.
*/
private void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer) {
final int vertexCount = prim.getVertexCount();
final boolean hasTexture = flags.hasTexture;
final boolean hasBrightness = flags.hasBrightness;
final boolean hasColor = flags.hasColor;
final boolean hasNormals = flags.hasNormals;
for (int i = 0; i < vertexCount; i++) {
// Position (always present) - 12 bytes
buffer.putFloat(prim.getX(i));
buffer.putFloat(prim.getY(i));
buffer.putFloat(prim.getZ(i));
// Color (4 bytes, ABGR) - if present
if (hasColor) {
buffer.putInt(prim.getColor(i));
}
// Texture (2 floats = 8 bytes) - if present
if (hasTexture) {
buffer.putFloat(prim.getTexU(i));
buffer.putFloat(prim.getTexV(i));
}
// Light/Brightness (4 bytes, packed) - if present
if (hasBrightness) {
buffer.putInt(prim.getLight(i));
}
// Normal (4 bytes, packed) - if present
if (hasNormals) {
buffer.putInt(prim.getForgeNormal(i));
}
}
}
}
@@ -124,9 +124,9 @@ public class DSAUnsupported implements DSAAccess {
@Override
public int bufferStorage(int target, FloatBuffer data, int usage) {
final int buffer = GL15.glGenBuffers();
GL15.glBindBuffer(target, buffer);
GLStateManager.glBindBuffer(target, buffer);
RenderSystem.bufferData(target, data, usage);
GL15.glBindBuffer(target, 0);
GLStateManager.glBindBuffer(target, 0);
return buffer;
}
@@ -1,11 +1,10 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import org.joml.Matrix4f;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
@@ -13,54 +12,53 @@ import java.util.List;
* Matrix-as-Data Architecture: Stores untransformed vertices + captured matrix.
* The matrix will be applied at runtime, not baked into vertices.
*/
public class AccumulatedDraw {
public final List<ModelQuadViewMutable> quads;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final class AccumulatedDraw {
public final VertexFormat format;
public final List<ByteBuffer> drawBuffers;
public final int drawMode;
public final int commandIndex; // Position in command list for state tracking
public final int matrixGeneration; // For batching: same generation = same transform context
public final int stateGeneration; // Same value = no state commands between draws, can merge
public final int stateGeneration; // Position in command list for state tracking
public RestoreData restoreData;
/**
* Last vertex restoration data for immediate mode draws.
* Null for tessellator draws (no restoration needed).
*/
public final RestoreData restoreData;
public AccumulatedDraw(DirectTessellator tessellator, int commandIndex, int stateGeneration, boolean copyLast) {
this.format = tessellator.getVertexFormat();
this.drawMode = tessellator.drawMode;
this.drawBuffers = new ArrayList<>();
this.drawBuffers.add(tessellator.allocateBufferCopy());
this.commandIndex = commandIndex;
this.stateGeneration = stateGeneration;
if (copyLast) {
this.restoreData = new RestoreData(tessellator);
}
}
public void mergeDraw(DirectTessellator tessellator, boolean copyLast) {
this.drawBuffers.add(tessellator.allocateBufferCopy());
if (copyLast) {
this.restoreData = new RestoreData(tessellator);
}
}
/**
* Holds last vertex attribute values for GL state restoration after VBO draw.
* Used to sync GLSM cache with actual GL state after VBO rendering.
*/
@Desugar
public record RestoreData(
float lastColorR, float lastColorG, float lastColorB, float lastColorA,
float lastNormalX, float lastNormalY, float lastNormalZ,
float lastTexCoordS, float lastTexCoordT) {}
public static final class RestoreData {
public final int lastColor;
public final int lastNormal;
public final float lastTexCoordU;
public final float lastTexCoordV;
public final int flags;
public AccumulatedDraw(List<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, matrixGen=%d, stateGen=%d, flags=C%dT%dL%dN%d, restore=%s]",
quads.size(), commandIndex, matrixGeneration, stateGeneration, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0,
restoreData != null ? "yes" : "no");
public RestoreData(DirectTessellator tessellator) {
this.lastColor = tessellator.getPackedColor();
this.lastNormal = tessellator.getPackedNormal();
this.lastTexCoordU = (float) tessellator.getLastTextureU();
this.lastTexCoordV = (float) tessellator.getLastTextureV();
this.flags = tessellator.getVertexFormat().getVertexFlags();
}
}
}
@@ -1,39 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an accumulated line draw call during display list compilation.
* Similar to AccumulatedDraw but for line primitives.
* Stores untransformed line vertices + captured matrix.
*/
public class AccumulatedLineDraw {
public final List<ImmediateModeRecorder.LineVertex> lines;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex; // Position in command list for state tracking
public final int stateGeneration; // Same value = no state commands between draws, can merge
public AccumulatedLineDraw(List<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
public String toString() {
return String.format("AccumulatedLineDraw[lines=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]",
lines.size() / 2, commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
}
}
@@ -1,66 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an accumulated primitive draw call during display list compilation.
* Stores primitives (lines, triangles) from tessellator callback with their transform.
* <p>
* Unlike AccumulatedLineDraw which stores ImmediateModeRecorder.LineVertex (16-byte: pos+color),
* this stores ModelPrimitiveView (32-byte: pos+color+tex+light+normal) from the tessellator.
*/
public class AccumulatedPrimitiveDraw {
public final List<ModelPrimitiveView> primitives;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex;
public final int matrixGeneration; // For batching: same generation = same transform context
public final int stateGeneration; // Same value = no state commands between draws, can merge
public AccumulatedPrimitiveDraw(List<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;
}
/**
* Creates deep copies of all primitives in the list.
* Required because CapturingTessellator pools and reuses primitive objects.
*/
private static List<ModelPrimitiveView> deepCopyPrimitives(List<ModelPrimitiveView> source) {
final int size = source.size();
final List<ModelPrimitiveView> copies = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
final ModelPrimitiveView prim = source.get(i);
if (prim instanceof ModelLine ml) {
copies.add(new ModelLine().copyFrom(ml));
} else if (prim instanceof ModelTriangle mt) {
copies.add(new ModelTriangle().copyFrom(mt));
}
}
return copies;
}
@Override
public String toString() {
return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, mode=%d, flags=C%dT%dL%dN%d]",
primitives.size(), commandIndex, matrixGeneration, stateGeneration, flags.drawMode,
flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0,
flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
}
}
@@ -14,12 +14,6 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
public final class CommandBuffer {
private static final int DEFAULT_CAPACITY = 4096; // Guess at typical display list size
// Flag bits for DRAW_RANGE_RESTORE command
public static final int FLAG_HAS_BRIGHTNESS = 1 << 0;
public static final int FLAG_HAS_COLOR = 1 << 1;
public static final int FLAG_HAS_NORMALS = 1 << 2;
public static final int FLAG_HAS_TEXTURE = 1 << 3;
private ByteBuffer buffer;
private long basePointer;
private long writePointer;
@@ -42,6 +36,11 @@ public final class CommandBuffer {
writePointer += 4;
}
private void writeLong(long value) {
memPutLong(writePointer, value);
writePointer += 8;
}
private void writeFloat(float value) {
memPutFloat(writePointer, value);
writePointer += 4;
@@ -548,13 +547,10 @@ public final class CommandBuffer {
// === Draw commands ===
public void writeDrawRange(int vboIndex, int startVertex, int vertexCount, boolean hasBrightness) {
ensureCapacity(20);
public void writeDrawRange(int vboIndex) {
ensureCapacity(8);
writeInt(GLCommand.DRAW_RANGE);
writeInt(vboIndex);
writeInt(startVertex);
writeInt(vertexCount);
writeInt(hasBrightness ? 1 : 0);
}
/**
@@ -562,51 +558,21 @@ public final class CommandBuffer {
* Used for immediate mode VBOs to restore GL_CURRENT_COLOR, GL_CURRENT_NORMAL, GL_CURRENT_TEXTURE_COORDS.
*
* @param vboIndex Index into ownedVbos array
* @param startVertex First vertex to draw
* @param vertexCount Number of vertices to draw
* @param hasBrightness True if VBO has brightness/lightmap data
* @param hasColor True if color should be restored after draw
* @param hasNormals True if normal should be restored after draw
* @param hasTexture True if texcoord should be restored after draw
* @param lastColorR Last vertex's red color component
* @param lastColorG Last vertex's green color component
* @param lastColorB Last vertex's blue color component
* @param lastColorA Last vertex's alpha color component
* @param lastNormalX Last vertex's normal X
* @param lastNormalY Last vertex's normal Y
* @param lastNormalZ Last vertex's normal Z
* @param lastTexS Last vertex's texture S coordinate
* @param lastTexT Last vertex's texture T coordinate
*/
public void writeDrawRangeRestore(
int vboIndex, int startVertex, int vertexCount,
boolean hasBrightness, boolean hasColor, boolean hasNormals, boolean hasTexture,
float lastColorR, float lastColorG, float lastColorB, float lastColorA,
float lastNormalX, float lastNormalY, float lastNormalZ,
float lastTexS, float lastTexT
int vboIndex, AccumulatedDraw.RestoreData restoreData
) {
ensureCapacity(56);
ensureCapacity(28);
writeInt(GLCommand.DRAW_RANGE_RESTORE);
writeInt(vboIndex);
writeInt(startVertex);
writeInt(vertexCount);
int flags = (hasBrightness ? FLAG_HAS_BRIGHTNESS : 0)
| (hasColor ? FLAG_HAS_COLOR : 0)
| (hasNormals ? FLAG_HAS_NORMALS : 0)
| (hasTexture ? FLAG_HAS_TEXTURE : 0);
writeInt(flags);
// Last color (4 floats = 16 bytes)
writeFloat(lastColorR);
writeFloat(lastColorG);
writeFloat(lastColorB);
writeFloat(lastColorA);
// Last normal (3 floats = 12 bytes)
writeFloat(lastNormalX);
writeFloat(lastNormalY);
writeFloat(lastNormalZ);
writeInt(restoreData.flags);
// Last color (4 bytes)
writeInt(restoreData.lastColor);
// Last normal (4 bytes)
writeInt(restoreData.lastNormal);
// Last texcoord (2 floats = 8 bytes)
writeFloat(lastTexS);
writeFloat(lastTexT);
writeFloat(restoreData.lastTexCoordU);
writeFloat(restoreData.lastTexCoordV);
}
public void writeCallList(int listId) {
@@ -615,6 +581,35 @@ public final class CommandBuffer {
writeInt(listId);
}
public void writeDrawArrays(int mode, int start, int count) {
ensureCapacity(16);
writeInt(GLCommand.DRAW_ARRAYS);
writeInt(mode);
writeInt(start);
writeInt(count);
}
public void writeDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
ensureCapacity(24);
writeInt(GLCommand.DRAW_ELEMENTS);
writeInt(mode);
writeInt(indices_count);
writeInt(type);
writeLong(indices_buffer_offset);
}
public void writeBindVBO(int vbo) {
ensureCapacity(8);
writeInt(GLCommand.BIND_VBO);
writeInt(vbo);
}
public void writeBindVAO(int vao) {
ensureCapacity(8);
writeInt(GLCommand.BIND_VAO);
writeInt(vao);
}
public void writeDrawBuffer(int mode) {
ensureCapacity(8);
writeInt(GLCommand.DRAW_BUFFER);
@@ -685,6 +680,12 @@ public final class CommandBuffer {
return value;
}
public long readLong() {
final long value = memGetLong(readPointer);
readPointer += 8;
return value;
}
/**
* Read a float from the current position.
*/
@@ -1,17 +1,19 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import static com.gtnewhorizons.angelica.glsm.recording.CommandBuffer.*;
/**
* Executes commands from a CommandBuffer
@@ -34,7 +36,7 @@ public final class CommandBufferExecutor {
* @param complexObjects Array of complex objects (TexImage2DCmd, etc.)
* @param ownedVbos Array of VBOs owned by the display list (indexed by DrawRange commands)
*/
public static void execute(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos) {
public static void execute(ByteBuffer buffer, Object[] complexObjects, DisplayListVBO ownedVbos) {
long ptr = memAddress(buffer);
final long end = ptr + buffer.limit();
@@ -450,48 +452,39 @@ public final class CommandBufferExecutor {
// === Draw commands ===
case GLCommand.DRAW_RANGE -> {
final int vboIndex = memGetInt(ptr);
final int start = memGetInt(ptr + 4);
final int count = memGetInt(ptr + 8);
final boolean hasBrightness = memGetInt(ptr + 12) != 0;
ptr += 16;
final VertexBuffer vbo = ownedVbos[vboIndex];
vbo.setupState();
vbo.draw(start, count);
vbo.cleanupState();
ptr += 4;
ownedVbos.render(vboIndex);
}
case GLCommand.DRAW_RANGE_RESTORE -> {
// Draw VBO range then restore GL current state from last vertex attributes
final int vboIndex = memGetInt(ptr);
final int start = memGetInt(ptr + 4);
final int count = memGetInt(ptr + 8);
final int flags = memGetInt(ptr + 12);
final int flags = memGetInt(ptr + 4);
// Draw the VBO
final VertexBuffer vbo = ownedVbos[vboIndex];
vbo.setupState();
vbo.draw(start, count);
vbo.cleanupState();
ownedVbos.render(vboIndex);
// Restore attributes based on flags
if ((flags & FLAG_HAS_COLOR) != 0) {
final float r = memGetFloat(ptr + 16);
final float g = memGetFloat(ptr + 20);
final float b = memGetFloat(ptr + 24);
final float a = memGetFloat(ptr + 28);
GLStateManager.glColor4f(r, g, b, a);
if ((flags & VertexFlags.COLOR_BIT) != 0) {
final int color = memGetInt(ptr + 8);
byte a = (byte) ((color >> 24) & 0xFF);
byte r = (byte) ((color >> 16) & 0xFF);
byte g = (byte) ((color >> 8) & 0xFF);
byte b = (byte) ((color & 0xFF));
GLStateManager.glColor4ub(r, g, b, a);
}
if ((flags & FLAG_HAS_NORMALS) != 0) {
final float nx = memGetFloat(ptr + 32);
final float ny = memGetFloat(ptr + 36);
final float nz = memGetFloat(ptr + 40);
if ((flags & VertexFlags.NORMAL_BIT) != 0) {
final int normal = memGetInt(ptr + 12);
float nx = (byte)(normal) / 127.0f;
float ny = (byte)(normal >> 8) / 127.0f;
float nz = (byte)(normal >> 16) / 127.0f;
GLStateManager.glNormal3f(nx, ny, nz);
}
if ((flags & FLAG_HAS_TEXTURE) != 0) {
final float s = memGetFloat(ptr + 44);
final float t = memGetFloat(ptr + 48);
if ((flags & VertexFlags.TEXTURE_BIT) != 0) {
final float s = memGetFloat(ptr + 16);
final float t = memGetFloat(ptr + 20);
GLStateManager.glTexCoord2f(s, t);
}
ptr += 52; // Skip full command size (56 - 4 for cmd already read)
ptr += 24; // Skip full command size (28 - 4 for cmd already read)
}
case GLCommand.CALL_LIST -> {
final int listId = memGetInt(ptr);
@@ -513,6 +506,22 @@ public final class CommandBufferExecutor {
ptr += 4 * MAX_DRAW_BUFFERS;
GLStateManager.glDrawBuffers(DRAW_BUFFERS_BUFFER);
}
case GLCommand.DRAW_ARRAYS -> {
GLStateManager.glDrawArrays(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8));
ptr += 12;
}
case GLCommand.DRAW_ELEMENTS -> {
GLStateManager.glDrawElements(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8), memGetLong(ptr + 12));
ptr += 20;
}
case GLCommand.BIND_VBO -> {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, memGetInt(ptr));
ptr += 4;
}
case GLCommand.BIND_VAO -> {
VAOManager.VAO.glBindVertexArray(memGetInt(ptr));
ptr += 4;
}
// === Complex object reference ===
case GLCommand.COMPLEX_REF -> {
@@ -17,73 +17,6 @@ public final class CommandBufferProcessor {
private CommandBufferProcessor() {}
public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) {
switch (opcode) {
// === MultMatrix - already collapsed transforms from flushMatrix() ===
case GLCommand.MULT_MATRIX -> {
raw.readMatrix4f(tempMatrix);
opt.multMatrix(tempMatrix); // accumulated = accumulated * tempMatrix
out.writeMultMatrix(tempMatrix); // Copy to output
opt.markLastEmittedAsAccumulated(); // lastEmitted = accumulated (what GL now has)
}
// === Load commands - flush pending, emit, reset accumulator ===
case GLCommand.LOAD_IDENTITY -> {
opt.emitPendingTransform(out); // Emit any pending transforms first
out.writeLoadIdentity(); // Always emit LoadIdentity
opt.loadIdentity(); // Reset accumulated to identity
opt.resetLastEmitted(); // Reset lastEmitted to identity
opt.checkAndClearAbsoluteMatrix(); // Clear the flag if set
}
case GLCommand.LOAD_MATRIX -> {
raw.readMatrix4f(tempMatrix);
opt.emitPendingTransform(out);
out.writeLoadMatrix(tempMatrix);
opt.loadIdentity();
opt.resetLastEmitted(); // Reset lastEmitted to identity
opt.markAbsoluteMatrix();
}
// === Stack operations - flush/update optimizer state and copy ===
case GLCommand.PUSH_MATRIX -> {
opt.emitPendingTransform(out);
opt.push();
// Reset accumulated/lastEmitted to identity after push.
opt.loadIdentity();
opt.resetLastEmitted();
out.writePushMatrix();
}
case GLCommand.POP_MATRIX -> {
opt.pop();
out.writePopMatrix();
}
// === Barriers - emit pending transform before copying ===
case GLCommand.MATRIX_MODE -> {
final int mode = raw.readInt();
opt.emitPendingTransform(out); // Pending transforms apply to OLD mode
out.writeMatrixMode(mode);
opt.loadIdentity(); // Reset accumulated for new mode
opt.resetLastEmitted(); // Reset lastEmitted for new mode
}
case GLCommand.CALL_LIST -> {
final int listId = raw.readInt();
opt.emitPendingTransform(out);
out.writeCallList(listId);
}
case GLCommand.PUSH_ATTRIB -> {
final int mask = raw.readInt();
if ((mask & GL11.GL_TRANSFORM_BIT) != 0) {
opt.emitPendingTransform(out);
}
out.writePushAttrib(mask);
}
// === All other commands - just copy ===
default -> copyCommandData(opcode, raw, out);
}
}
/**
* Copy a complete command (opcode already read) from raw to final buffer.
*/
@@ -210,8 +143,12 @@ public final class CommandBufferProcessor {
}
// Draw/call commands
case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt() != 0);
case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt());
case GLCommand.CALL_LIST -> out.writeCallList(raw.readInt());
case GLCommand.DRAW_ARRAYS -> out.writeDrawArrays(raw.readInt(), raw.readInt(), raw.readInt());
case GLCommand.DRAW_ELEMENTS -> out.writeDrawElements(raw.readInt(), raw.readInt(), raw.readInt(), raw.readLong());
case GLCommand.BIND_VBO -> out.writeBindVBO(raw.readInt());
case GLCommand.BIND_VAO -> out.writeBindVAO(raw.readInt());
// Complex object reference - transfer the object to output buffer
case GLCommand.COMPLEX_REF -> {
@@ -223,94 +160,4 @@ public final class CommandBufferProcessor {
default -> LOGGER.warn("[CommandBufferProcessor] Unknown opcode in buffer copy: {}", opcode);
}
}
/**
* Lightweight transform optimizer for buffer-to-buffer processing.
* Tracks accumulated transform (mode-agnostic) and emits MultMatrix commands when needed.
*
* <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;
public BufferTransformOptimizer() {
accumulated.identity();
lastEmitted.identity();
}
public void multMatrix(Matrix4f m) {
accumulated.mul(m);
}
public void loadIdentity() {
accumulated.identity();
}
public void push() {
stack.push(new Matrix4f(accumulated));
}
public void pop() {
if (!stack.isEmpty()) {
accumulated.set(stack.pop());
lastEmitted.set(accumulated);
} else {
accumulated.identity();
lastEmitted.identity();
}
}
public boolean isIdentity() {
return DisplayListManager.isIdentity(accumulated);
}
public void markAbsoluteMatrix() {
absoluteMatrixFlag = true;
}
public boolean checkAndClearAbsoluteMatrix() {
final boolean was = absoluteMatrixFlag;
absoluteMatrixFlag = false;
return was;
}
public void resetLastEmitted() {
lastEmitted.identity();
}
public void setLastEmitted(Matrix4f m) {
lastEmitted.set(m);
}
public void markLastEmittedAsAccumulated() {
lastEmitted.set(accumulated);
}
public void emitPendingTransform(CommandBuffer out) {
if (!accumulated.equals(lastEmitted)) {
emitTransformTo(out, accumulated);
}
}
public void emitTransformTo(CommandBuffer out, Matrix4f target) {
if (target.equals(lastEmitted)) {
return;
}
if (DisplayListManager.isIdentity(lastEmitted)) {
out.writeMultMatrix(target);
} else {
delta.set(lastEmitted).invert().mul(target);
out.writeMultMatrix(delta);
}
lastEmitted.set(target);
}
}
}
@@ -9,7 +9,7 @@ import java.nio.IntBuffer;
/**
* Records GL commands to a CommandBuffer during display list compilation.
*/
public class CommandRecorder {
public final class CommandRecorder {
private final CommandBuffer buffer;
private int commandCount;
@@ -337,6 +337,26 @@ public class CommandRecorder {
commandCount++;
}
public void recordDrawArrays(int mode, int start, int count) {
buffer.writeDrawArrays(mode, start, count);
commandCount++;
}
public void recordDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
buffer.writeDrawElements(mode, indices_count, type, indices_buffer_offset);
commandCount++;
}
public void recordBindVBO(int vbo) {
buffer.writeBindVBO(vbo);
commandCount++;
}
public void recordBindVAO(int vao) {
buffer.writeBindVAO(vao);
commandCount++;
}
public void recordComplexCommand(DisplayListCommand cmd) {
buffer.writeComplexRef(cmd);
commandCount++;
@@ -1,6 +1,6 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
@@ -30,9 +30,9 @@ public final class CompiledDisplayList {
private final ByteBuffer commandBuffer; // Off-heap command storage, must be freed
private final Object[] complexObjects; // Complex commands (TexImage2D, etc.)
private final VertexBuffer[] ownedVbos; // GPU resources referenced by index
private final DisplayListVBO ownedVbos; // GPU resources referenced by index
public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, VertexBuffer[] ownedVbos) {
public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, DisplayListVBO ownedVbos) {
this.commandBuffer = commandBuffer;
this.complexObjects = complexObjects;
this.ownedVbos = ownedVbos;
@@ -62,11 +62,7 @@ public final class CompiledDisplayList {
// Close VBOs
if (ownedVbos != null) {
for (VertexBuffer vbo : ownedVbos) {
if (vbo != null) {
vbo.close();
}
}
ownedVbos.delete();
}
// Free the command buffer (off-heap memory)
@@ -89,10 +85,7 @@ public final class CompiledDisplayList {
return complexObjects;
}
/**
* Get owned VBOs for inlining into another display list.
*/
public VertexBuffer[] getOwnedVbos() {
public DisplayListVBO getOwnedVbos() {
return ownedVbos;
}
@@ -112,7 +105,7 @@ public final class CompiledDisplayList {
while (ptr < end) {
final int cmd = memGetInt(ptr);
counts.mergeInt(cmd, 1, Integer::sum);
ptr += getCommandSize(cmd, ptr);
ptr += GLCommand.getCommandSize(cmd, ptr);
}
return counts;
}
@@ -131,74 +124,13 @@ public final class CompiledDisplayList {
while (ptr < end) {
final int cmd = memGetInt(ptr);
opcodes.add(cmd);
ptr += getCommandSize(cmd, ptr);
ptr += GLCommand.getCommandSize(cmd, ptr);
}
return opcodes;
}
/**
* Get size of a command in bytes (including the opcode).
*/
private static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
// Opcode-only commands (4 bytes)
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
// Single int commands (8 bytes)
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8;
// Two int commands (12 bytes)
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12;
// Three int commands (16 bytes)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16;
// Four int commands (20 bytes)
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR,
GLCommand.DRAW_RANGE -> 20;
// DRAW_RANGE_RESTORE: 56 bytes
// [cmd:4][vboIndex:4][start:4][count:4][flags:4][color:16f][normal:12f][texcoord:8f]
case GLCommand.DRAW_RANGE_RESTORE -> 56;
// DRAW_BUFFER: 8 bytes [cmd:4][mode:4]
case GLCommand.DRAW_BUFFER -> 8;
// DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8]
case GLCommand.DRAW_BUFFERS -> 40;
// Double commands
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles
case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double
case GLCommand.ROTATE -> 36; // cmd + 4 doubles
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles
// Matrix commands
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats
// Buffer commands (variable, read count)
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
final int count = memGetInt(ptr + 8); // pname at +4, count at +8
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
yield 16 + count * 4;
}
default -> throw new IllegalStateException("Unknown command: " + cmd);
};
@Override
public String toString() {
return DisplayListManager.getCompiledDisplayListString(0, this, null);
}
}
@@ -0,0 +1,60 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import org.lwjgl.opengl.GL15;
/**
* A class that stores multiple vertex formats & their corresponding buffers.
*/
public final class DisplayListVBO {
private final SubVBO[] vbos;
DisplayListVBO(SubVBO[] vbos) {
this.vbos = vbos;
}
public void delete() {
for (SubVBO vbo : vbos) {
vbo.delete();
}
}
public SubVBO[] getVBOs() {
return vbos;
}
public void render(int index) {
vbos[index].render();
}
public static final class SubVBO {
private final IVertexArrayObject vao;
private final int drawMode;
private final int start;
private final int count;
public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count) {
this.vao = vao;
this.drawMode = drawMode;
this.start = start;
this.count = count;
}
public void delete() {
vao.delete();
}
public void render() {
vao.bind();
vao.draw(drawMode, start, count);
vao.unbind();
}
public IVertexArrayObject getVAO() {
return vao;
}
}
}
@@ -0,0 +1,127 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
/**
* Compiles multiple ByteBuffers of the same Vertex format into a VBO. Any buffer added to the builder will be freed afterward.
*/
public final class DisplayListVBOBuilder {
// Removes the need for a HashMap. Since it's only an array of 16 values, this should be faster
private final List<FormatData>[] formats = new List[VertexFlags.BITSET_SIZE];
private int count;
public DisplayListVBOBuilder addDraw(VertexFormat format, int drawMode, List<ByteBuffer> buffers) {
List<FormatData> data = formats[format.getVertexFlags()];
if (data == null) {
data = new ArrayList<>();
formats[format.getVertexFlags()] = data;
}
data.add(new FormatData(buffers, drawMode, count));
count++;
return this;
}
public DisplayListVBOBuilder addDraws(List<AccumulatedDraw> draws) {
for (AccumulatedDraw draw : draws) {
addDraw(draw.format, draw.drawMode, draw.drawBuffers);
}
return this;
}
public DisplayListVBO build() {
final DisplayListVBO.SubVBO[] vbos = new DisplayListVBO.SubVBO[count];
final ArrayList<ByteBuffer> allBuffers = new ArrayList<>();
for (int i = 0; i < VertexFlags.BITSET_SIZE; i++) {
List<FormatData> formatData = formats[i];
if (formatData == null) continue;
final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[i];
int start = 0;
final IVertexArrayObject vao = VAOManager.createStorageVAO(format, -1, 0); // drawMode will be ignored
final IVertexBuffer vbo = vao.getVBO();
for (FormatData data : formatData) {
int vertexCount;
final List<ByteBuffer> drawBuffers = data.buffers;
if (drawBuffers.size() == 1) {
final ByteBuffer buffer = drawBuffers.get(0);
allBuffers.add(buffer);
vertexCount = format.getVertexCount(buffer);
} else {
allBuffers.addAll(drawBuffers);
int size = 0;
for (ByteBuffer buffer : drawBuffers) {
size += buffer.remaining();
}
vertexCount = format.getVertexCount(size);
}
if (data.drawMode == GL11.GL_QUADS) {
IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount));
vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6);
} else {
vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount);
}
start += vertexCount;
}
ByteBuffer bigBuffer = mergeAndDelete(allBuffers);
vbo.allocate(bigBuffer, start);
memFree(bigBuffer);
allBuffers.clear();
}
return new DisplayListVBO(vbos);
}
private static ByteBuffer mergeAndDelete(List<ByteBuffer> buffers) {
if (buffers.size() == 1) {
return buffers.get(0);
}
int needed = 0;
for (ByteBuffer buffer : buffers) {
needed += buffer.remaining();
}
ByteBuffer out = memAlloc(needed);
long dst = memAddress0(out);
for (ByteBuffer buffer : buffers) {
final int len = buffer.limit();
final long address = memAddress0(buffer);
memCopy(address, dst, len);
dst += len;
nmemFree(address);
}
out.limit(needed);
return out;
}
private static final class FormatData {
private final List<ByteBuffer> buffers;
private final int drawMode;
private final int drawIndex;
public FormatData(List<ByteBuffer> buffers, int drawMode, int drawIndex) {
this.buffers = buffers;
this.drawMode = drawMode;
this.drawIndex = drawIndex;
}
}
}
@@ -1,5 +1,7 @@
package com.gtnewhorizons.angelica.glsm.recording;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
/**
* Command opcodes for ByteBuffer-based display list serialization.
* Each command has a fixed layout described in comments.
@@ -88,16 +90,24 @@ public final class GLCommand {
public static final int MATERIAL = 93; // [cmd:4][face:4][pname:4][count:4][params:16f] = 32 bytes
// === Draw commands ===
public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4][start:4][count:4][hasBrightness:4] = 20 bytes
public static final int CALL_LIST = 101; // [cmd:4][listId:4] = 8 bytes
public static final int DRAW_BUFFER = 102; // [cmd:4][mode:4] = 8 bytes
public static final int DRAW_BUFFERS = 103; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers)
public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4] = 8 bytes
public static final int DRAW_RANGE_RESTORE = 101; // [cmd:4][vboIndex:4][flags:4][color:4][normal:4][lastTexCoord:8f] = 28 bytes
public static final int CALL_LIST = 102; // [cmd:4][listId:4] = 8 bytes
public static final int DRAW_ARRAYS = 110; // [cmd:4][drawMode:4][start:4][count:4] = 20 bytes
public static final int DRAW_ELEMENTS = 111; // [cmd:4][mode:4][indices_count:4][type:4][indices_buffer_offset:8] = 28 bytes
public static final int DRAW_BUFFER = 112; // [cmd:4][mode:4] = 8 bytes
public static final int DRAW_BUFFERS = 113; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers)
/**
* Draw VBO range with attribute restoration after draw.
* Used for immediate mode VBOs to restore GL current state (color, normal, texcoord).
*/
public static final int DRAW_RANGE_RESTORE = 104; // [cmd:4][vboIndex:4][start:4][count:4][flags:4]
// [lastColor:16f][lastNormal:12f][lastTexCoord:8f] = 56 bytes
// === Bind commands ===
public static final int BIND_VBO = 120;
public static final int BIND_VAO = 121;
// === Complex object reference ===
public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes
@@ -171,9 +181,78 @@ public final class GLCommand {
case CALL_LIST -> "CALL_LIST";
case DRAW_BUFFER -> "DRAW_BUFFER";
case DRAW_BUFFERS -> "DRAW_BUFFERS";
case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE";
case COMPLEX_REF -> "COMPLEX_REF";
case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE";
case BIND_VAO -> "BIND_VAO";
case BIND_VBO -> "BIND_VBO";
default -> "UNKNOWN(" + opcode + ")";
};
}
/**
* Get size of a command in bytes (including the opcode).
*/
public static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
// Opcode-only commands (4 bytes)
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
// Single int commands (8 bytes)
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_RANGE, GLCommand.BIND_VBO,
GLCommand.BIND_VAO -> 8;
// Two int commands (12 bytes)
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12;
// Three int commands (16 bytes)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF, GLCommand.DRAW_ARRAYS -> 16;
// Four int commands (20 bytes)
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR -> 20;
case GLCommand.DRAW_ELEMENTS -> 24;
// DRAW_RANGE_RESTORE: 28 bytes
case GLCommand.DRAW_RANGE_RESTORE -> 28;
// DRAW_BUFFER: 8 bytes [cmd:4][mode:4]
case GLCommand.DRAW_BUFFER -> 8;
// DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8]
case GLCommand.DRAW_BUFFERS -> 40;
// Double commands
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles
case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double
case GLCommand.ROTATE -> 36; // cmd + 4 doubles
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles
// Matrix commands
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats
// Buffer commands (variable, read count)
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
final int count = memGetInt(ptr + 8); // pname at +4, count at +8
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
yield 16 + count * 4;
}
default -> throw new IllegalStateException("Unknown command: " + cmd);
};
}
}
@@ -1,156 +1,58 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.glsm.states.ClientArrayState;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Records immediate mode GL calls (glBegin/glEnd/glVertex) during display list compilation.
* Converts immediate mode geometry to ModelQuad format for VBO compilation.
*
* <p>Tracks current immediate mode state:
* <ul>
* <li>TexCoord: Set by glTexCoord* calls</li>
* <li>Normal: Set by glNormal* calls</li>
* <li>Color: Read from GLStateManager.getColor() at vertex emission time</li>
* </ul>
*
* <p>Supported primitive types:
* <ul>
* <li>GL_QUADS: 4 vertices per quad (native support)</li>
* <li>GL_TRIANGLES: 3 vertices per triangle (converted to degenerate quad)</li>
* <li>GL_TRIANGLE_FAN: Fan of triangles (converted to individual quads)</li>
* <li>GL_TRIANGLE_STRIP: Strip of triangles (converted to individual quads)</li>
* <li>GL_QUAD_STRIP: Strip of quads (converted to individual quads)</li>
* <li>GL_POLYGON: Polygon (treated as triangle fan)</li>
* </ul>
*
* <p>Unsupported primitive types (logged warning, geometry discarded):
* <ul>
* <li>GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP: Line primitives</li>
* <li>GL_POINTS: Point primitives</li>
* </ul>
* Converts immediate mode geometry to ByteBuffer directly via {@link DirectTessellator}
* <p>
* Currently only used for display list compilation, should be perfectly usable outside of display lists too though.
*/
public class ImmediateModeRecorder {
private static final Logger LOGGER = LogManager.getLogger("ImmediateModeRecorder");
public final class ImmediateModeRecorder {
private static final DirectTessellator tessellator = new DirectTessellator(TessellatorManager.DEFAULT_BUFFER_SIZE);
// Accumulated quads from completed primitives
private final List<ModelQuadViewMutable> quads = new ArrayList<>();
private ImmediateModeRecorder() {
// Accumulated line vertices (pairs of vertices for GL_LINES)
private final List<LineVertex> lineVertices = new ArrayList<>();
// Current primitive state
private int currentPrimitiveType = -1;
private boolean inPrimitive = false;
// Vertices for current primitive (cleared on glEnd)
private final List<ImmediateVertex> currentVertices = new ArrayList<>();
// Current immediate mode state (set by glTexCoord*, glNormal*)
private float texCoordS = 0.0f;
private float texCoordT = 0.0f;
private float normalX = 0.0f;
private float normalY = 0.0f;
private float normalZ = 1.0f; // Default normal points +Z
// Track which attributes have been set (for flags)
private boolean hasTexCoord = false;
private boolean hasNormal = false;
private boolean hasColor = false;
/**
* Represents a single vertex captured during immediate mode.
*/
private static class ImmediateVertex {
float x, y, z; // Position
int color; // Packed ABGR color
float texU, texV; // Texture coordinates
int normal; // Packed normal
ImmediateVertex(float x, float y, float z, int color, float texU, float texV, int normal) {
this.x = x;
this.y = y;
this.z = z;
this.color = color;
this.texU = texU;
this.texV = texV;
this.normal = normal;
}
}
/**
* Represents a vertex for line primitives.
* Simpler than ImmediateVertex - just position and color.
*/
public static class LineVertex {
public final float x, y, z;
public final int color; // Packed ABGR color
public LineVertex(float x, float y, float z, int color) {
this.x = x;
this.y = y;
this.z = z;
this.color = color;
}
}
public ImmediateModeRecorder() {
// Recorder is ready to capture geometry
public static DirectTessellator getInternalTessellator() {
return tessellator;
}
/**
* Set the current texture coordinate.
* Called by GLStateManager.glTexCoord*.
*/
public void setTexCoord(float s, float t) {
this.texCoordS = s;
this.texCoordT = t;
this.hasTexCoord = true;
public static void setTexCoord(float s, float t) {
tessellator.setTextureUV(s, t);
}
/**
* Set the current normal vector.
* Called by GLStateManager.glNormal*.
*/
public void setNormal(float x, float y, float z) {
this.normalX = x;
this.normalY = y;
this.normalZ = z;
this.hasNormal = true;
}
/**
* Check if currently in a primitive (between glBegin and glEnd).
*/
public boolean isInPrimitive() {
return inPrimitive;
public static void setNormal(float x, float y, float z) {
tessellator.setNormal(x, y, z);
}
/**
* Start recording a new primitive.
*/
public void begin(int primitiveType) {
if (inPrimitive) {
throw new IllegalStateException("glBegin called while already in primitive");
}
this.currentPrimitiveType = primitiveType;
this.currentVertices.clear();
this.inPrimitive = true;
public static void begin(int primitiveType) {
tessellator.startDrawing(primitiveType);
}
/**
@@ -159,346 +61,27 @@ public class ImmediateModeRecorder {
*
* @return Result containing quads, lines, and flags, or null if no geometry was produced
*/
public Result end() {
if (!inPrimitive) {
public static DirectTessellator end() {
if (!tessellator.isDrawing) {
throw new IllegalStateException("glEnd called without glBegin");
}
// Capture last vertex attributes BEFORE clearing currentVertices
// These will be used to restore GL current state after VBO playback
float lastColorR = 1.0f, lastColorG = 1.0f, lastColorB = 1.0f, lastColorA = 1.0f;
float lastNormalX = 0.0f, lastNormalY = 0.0f, lastNormalZ = 1.0f;
float lastTexS = 0.0f, lastTexT = 0.0f;
tessellator.isDrawing = false;
if (!currentVertices.isEmpty()) {
ImmediateVertex last = currentVertices.get(currentVertices.size() - 1);
if (tessellator.isEmpty()) return null;
// Unpack color from ABGR format
lastColorR = (last.color & 0xFF) / 255.0f;
lastColorG = ((last.color >> 8) & 0xFF) / 255.0f;
lastColorB = ((last.color >> 16) & 0xFF) / 255.0f;
lastColorA = ((last.color >> 24) & 0xFF) / 255.0f;
// Unpack normal from NormI8 format (signed bytes packed into int)
lastNormalX = NormI8.unpackX(last.normal);
lastNormalY = NormI8.unpackY(last.normal);
lastNormalZ = NormI8.unpackZ(last.normal);
// Texture coords are stored directly as floats
lastTexS = last.texU;
lastTexT = last.texV;
}
// Convert this primitive's vertices to quads or lines
convertPrimitiveToQuads();
this.currentVertices.clear();
this.inPrimitive = false;
// Return geometry from this primitive immediately (don't accumulate)
if (quads.isEmpty() && lineVertices.isEmpty()) {
return null;
}
// Copy geometry and create flags
List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads);
List<LineVertex> resultLines = new ArrayList<>(lineVertices);
CapturingTessellator.Flags flags = new CapturingTessellator.Flags(
hasTexCoord, // hasTexture
false, // hasBrightness - immediate mode doesn't typically use lightmap
hasColor, // hasColor
hasNormal // hasNormals
);
// Clear for next primitive (but keep attribute tracking state)
quads.clear();
lineVertices.clear();
return new Result(resultQuads, resultLines, flags,
lastColorR, lastColorG, lastColorB, lastColorA,
lastNormalX, lastNormalY, lastNormalZ,
lastTexS, lastTexT);
return tessellator;
}
/**
* Record a vertex with current attributes.
* Color is read from GLStateManager at call time.
*/
public void vertex(float x, float y, float z) {
if (!inPrimitive) {
public static void vertex(float x, float y, float z) {
if (!tessellator.isDrawing) {
throw new IllegalStateException("glVertex called outside glBegin/glEnd");
}
// Get current color from GLStateManager
int packedColor = packColor(
GLStateManager.getColor().getRed(),
GLStateManager.getColor().getGreen(),
GLStateManager.getColor().getBlue(),
GLStateManager.getColor().getAlpha()
);
if (packedColor != 0xFFFFFFFF) {
hasColor = true;
}
// Pack normal
int packedNormal = NormI8.pack(normalX, normalY, normalZ);
currentVertices.add(new ImmediateVertex(
x, y, z,
packedColor,
texCoordS, texCoordT,
packedNormal
));
}
/**
* Pack RGBA floats (0-1) into ABGR int format used by ModelQuad.
*/
private static int packColor(float r, float g, float b, float a) {
int ri = (int) (r * 255.0f) & 0xFF;
int gi = (int) (g * 255.0f) & 0xFF;
int bi = (int) (b * 255.0f) & 0xFF;
int ai = (int) (a * 255.0f) & 0xFF;
// ABGR format (little-endian: stored as RGBA bytes)
return (ai << 24) | (bi << 16) | (gi << 8) | ri;
}
/**
* Convert the current primitive vertices to quads.
* Handles different primitive types.
*/
private void convertPrimitiveToQuads() {
int vertexCount = currentVertices.size();
if (vertexCount == 0) {
return;
}
switch (currentPrimitiveType) {
case GL11.GL_QUADS -> convertQuads();
case GL11.GL_TRIANGLES -> convertTriangles();
case GL11.GL_TRIANGLE_FAN, GL11.GL_POLYGON -> convertTriangleFan();
case GL11.GL_TRIANGLE_STRIP -> convertTriangleStrip();
case GL11.GL_QUAD_STRIP -> convertQuadStrip();
case GL11.GL_LINES -> convertLines();
case GL11.GL_LINE_STRIP -> convertLineStripToLines();
case GL11.GL_LINE_LOOP -> convertLineLoopToLines();
case GL11.GL_POINTS -> {
LOGGER.warn("[ImmediateModeRecorder] Point primitives not supported, discarding {} vertices", vertexCount);
}
default -> {
LOGGER.warn("[ImmediateModeRecorder] Unknown primitive type {}, discarding {} vertices",
currentPrimitiveType, vertexCount);
}
}
}
/**
* Convert GL_QUADS vertices to ModelQuads (4 vertices per quad).
*/
private void convertQuads() {
int vertexCount = currentVertices.size();
int fullQuads = vertexCount / 4;
for (int i = 0; i < fullQuads; i++) {
int base = i * 4;
addQuad(
currentVertices.get(base),
currentVertices.get(base + 1),
currentVertices.get(base + 2),
currentVertices.get(base + 3)
);
}
int remaining = vertexCount % 4;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_QUADS: Incomplete quad, discarding {} vertices", remaining);
}
}
/**
* Convert GL_TRIANGLES vertices to degenerate quads (3 vertices per triangle, duplicate last).
*/
private void convertTriangles() {
int vertexCount = currentVertices.size();
int fullTriangles = vertexCount / 3;
for (int i = 0; i < fullTriangles; i++) {
int base = i * 3;
ImmediateVertex v0 = currentVertices.get(base);
ImmediateVertex v1 = currentVertices.get(base + 1);
ImmediateVertex v2 = currentVertices.get(base + 2);
// Degenerate quad: duplicate third vertex
addQuad(v0, v1, v2, v2);
}
int remaining = vertexCount % 3;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLES: Incomplete triangle, discarding {} vertices", remaining);
}
}
/**
* Convert GL_TRIANGLE_FAN vertices to triangles then to degenerate quads.
* First vertex is center, subsequent vertices form fan.
*/
private void convertTriangleFan() {
int vertexCount = currentVertices.size();
if (vertexCount < 3) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_FAN: Need at least 3 vertices, got {}", vertexCount);
return;
}
ImmediateVertex center = currentVertices.get(0);
for (int i = 1; i < vertexCount - 1; i++) {
ImmediateVertex v1 = currentVertices.get(i);
ImmediateVertex v2 = currentVertices.get(i + 1);
// Triangle: center, v1, v2 -> degenerate quad
addQuad(center, v1, v2, v2);
}
}
/**
* Convert GL_TRIANGLE_STRIP vertices to triangles then to degenerate quads.
*/
private void convertTriangleStrip() {
int vertexCount = currentVertices.size();
if (vertexCount < 3) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_STRIP: Need at least 3 vertices, got {}", vertexCount);
return;
}
for (int i = 0; i < vertexCount - 2; i++) {
ImmediateVertex v0, v1, v2;
if ((i & 1) == 0) {
// Even triangle: v[i], v[i+1], v[i+2]
v0 = currentVertices.get(i);
v1 = currentVertices.get(i + 1);
v2 = currentVertices.get(i + 2);
} else {
// Odd triangle: v[i+1], v[i], v[i+2] (reverse winding)
v0 = currentVertices.get(i + 1);
v1 = currentVertices.get(i);
v2 = currentVertices.get(i + 2);
}
addQuad(v0, v1, v2, v2);
}
}
/**
* Convert GL_QUAD_STRIP vertices to quads.
* Vertices come in pairs: (v0,v1), (v2,v3), (v4,v5)...
* Each quad uses 4 consecutive vertices in pattern: v[2i], v[2i+1], v[2i+3], v[2i+2]
*/
private void convertQuadStrip() {
int vertexCount = currentVertices.size();
if (vertexCount < 4) {
LOGGER.warn("[ImmediateModeRecorder] GL_QUAD_STRIP: Need at least 4 vertices, got {}", vertexCount);
return;
}
int numQuads = (vertexCount - 2) / 2;
for (int i = 0; i < numQuads; i++) {
int base = i * 2;
// Quad strip winding: v[0], v[1], v[3], v[2]
addQuad(
currentVertices.get(base),
currentVertices.get(base + 1),
currentVertices.get(base + 3),
currentVertices.get(base + 2)
);
}
}
/**
* Convert GL_LINES vertices to line segments (pairs of vertices).
*/
private void convertLines() {
int vertexCount = currentVertices.size();
int fullLines = vertexCount / 2;
for (int i = 0; i < fullLines; i++) {
int base = i * 2;
ImmediateVertex v0 = currentVertices.get(base);
ImmediateVertex v1 = currentVertices.get(base + 1);
lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color));
lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color));
}
int remaining = vertexCount % 2;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINES: Incomplete line, discarding {} vertices", remaining);
}
}
/**
* Convert GL_LINE_STRIP to individual line segments.
* Vertices 0-1-2-3 become lines: 0-1, 1-2, 2-3
*/
private void convertLineStripToLines() {
int vertexCount = currentVertices.size();
if (vertexCount < 2) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINE_STRIP: Need at least 2 vertices, got {}", vertexCount);
return;
}
for (int i = 0; i < vertexCount - 1; i++) {
ImmediateVertex v0 = currentVertices.get(i);
ImmediateVertex v1 = currentVertices.get(i + 1);
lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color));
lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color));
}
}
/**
* Convert GL_LINE_LOOP to individual line segments.
* Like LINE_STRIP but also closes the loop from last to first vertex.
*/
private void convertLineLoopToLines() {
int vertexCount = currentVertices.size();
if (vertexCount < 2) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINE_LOOP: Need at least 2 vertices, got {}", vertexCount);
return;
}
// Convert as strip first
convertLineStripToLines();
// Close the loop: add last-to-first segment
ImmediateVertex vLast = currentVertices.get(vertexCount - 1);
ImmediateVertex vFirst = currentVertices.get(0);
lineVertices.add(new LineVertex(vLast.x, vLast.y, vLast.z, vLast.color));
lineVertices.add(new LineVertex(vFirst.x, vFirst.y, vFirst.z, vFirst.color));
}
/**
* Create a ModelQuad from 4 ImmediateVertex objects.
*/
private void addQuad(ImmediateVertex v0, ImmediateVertex v1, ImmediateVertex v2, ImmediateVertex v3) {
ModelQuad quad = new ModelQuad();
setVertex(quad, 0, v0);
setVertex(quad, 1, v1);
setVertex(quad, 2, v2);
setVertex(quad, 3, v3);
// Set light face based on computed normal
quad.setLightFace(ModelQuadUtil.findLightFace(quad.getComputedFaceNormal()));
quads.add(quad);
}
/**
* Set a single vertex in a ModelQuad.
*/
private void setVertex(ModelQuad quad, int idx, ImmediateVertex v) {
quad.setX(idx, v.x);
quad.setY(idx, v.y);
quad.setZ(idx, v.z);
quad.setColor(idx, v.color);
quad.setTexU(idx, v.texU);
quad.setTexV(idx, v.texV);
quad.setForgeNormal(idx, v.normal);
// Light defaults to full brightness (no lightmap for immediate mode typically)
quad.setLight(idx, ModelQuadUtil.DEFAULT_LIGHTMAP);
tessellator.addVertex(x, y, z);
}
/**
@@ -508,87 +91,16 @@ public class ImmediateModeRecorder {
* is returned from end() immediately. This method is kept for edge cases
* where primitives might fail to convert (e.g., incomplete quads).
*/
public boolean hasGeometry() {
return !quads.isEmpty() || !lineVertices.isEmpty();
public static boolean hasGeometry() {
return tessellator.vertexCount != 0;
}
/**
* Get any remaining accumulated geometry and clear the recorder.
*
* <p>Note: With immediate flush mode, this will typically return null as geometry
* is returned from end() immediately. This method is kept for cleanup and
* edge cases where geometry might remain (e.g., if end() was never called).
*
* @return Result containing remaining quads, lines, and flags, or null if no geometry
*/
public Result getQuadsAndClear() {
if (inPrimitive) {
throw new IllegalStateException("Cannot get geometry while in primitive (missing glEnd)");
}
if (quads.isEmpty() && lineVertices.isEmpty()) {
return null;
}
// Copy geometry and create flags
List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads);
List<LineVertex> resultLines = new ArrayList<>(lineVertices);
CapturingTessellator.Flags flags = new CapturingTessellator.Flags(
hasTexCoord, // hasTexture
false, // hasBrightness - immediate mode doesn't typically use lightmap
hasColor, // hasColor
hasNormal // hasNormals
);
// Clear state for reuse
quads.clear();
lineVertices.clear();
hasColor = false;
hasTexCoord = false;
hasNormal = false;
// Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec
// For getQuadsAndClear, we don't have last vertex data (it was cleared in end())
// Use default values - this method is for edge cases/cleanup anyway
return new Result(resultQuads, resultLines, flags,
1.0f, 1.0f, 1.0f, 1.0f, // Default white color
0.0f, 0.0f, 1.0f, // Default +Z normal
0.0f, 0.0f); // Default (0,0) texcoord
}
/**
* Result of immediate mode recording: quads, lines, attribute flags, and last vertex state.
* The last vertex state is used to restore GL_CURRENT_COLOR etc. after VBO playback.
*/
@com.github.bsideup.jabel.Desugar
public record Result(
List<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.
* Called when starting a new display list.
*/
public void reset() {
quads.clear();
lineVertices.clear();
currentVertices.clear();
inPrimitive = false;
currentPrimitiveType = -1;
texCoordS = 0.0f;
texCoordT = 0.0f;
normalX = 0.0f;
normalY = 0.0f;
normalZ = 1.0f;
hasColor = false;
hasTexCoord = false;
hasNormal = false;
public static void reset() {
tessellator.reset();
}
/**
@@ -600,10 +112,10 @@ public class ImmediateModeRecorder {
* @param count Number of vertices
* @return Result containing converted geometry, or null if no geometry produced
*/
public Result processDrawArrays(int mode, int first, int count) {
final var cas = GLStateManager.getClientArrayState();
final var vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null;
final var colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null;
public static DirectTessellator processDrawArrays(int mode, int first, int count) {
final ClientArrayState cas = GLStateManager.getClientArrayState();
final Buffer vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null;
final Buffer colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null;
return convertClientArrays(
mode, first, count,
@@ -632,7 +144,7 @@ public class ImmediateModeRecorder {
* @param colorStride Stride in bytes (0 for tightly packed)
* @return Result containing converted geometry, or null if no geometry produced
*/
public Result convertClientArrays(
public static DirectTessellator convertClientArrays(
int mode, int first, int count,
java.nio.Buffer vertexPointer, int vertexType, int vertexSize, int vertexStride,
java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride
@@ -645,12 +157,10 @@ public class ImmediateModeRecorder {
// Determine color reader (hoisted out of loop)
final ColorReader colorReader;
final int colorEffectiveStride;
if (colorPointer == null) {
colorReader = null;
colorEffectiveStride = 0;
} else if (colorType == GL11.GL_FLOAT && colorPointer instanceof FloatBuffer fb) {
colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride;
final int colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride;
final int strideInFloats = colorEffectiveStride / 4;
colorReader = (idx) -> {
final int offset = idx * strideInFloats;
@@ -661,7 +171,7 @@ public class ImmediateModeRecorder {
GLStateManager.glColor4f(r, g, b, a);
};
} else if ((colorType == GL11.GL_UNSIGNED_BYTE || colorType == GL11.GL_BYTE) && colorPointer instanceof ByteBuffer bb) {
colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride;
final int colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride;
colorReader = (idx) -> {
final int offset = idx * colorEffectiveStride;
final float r = (bb.get(offset) & 0xFF) / 255.0f;
@@ -672,7 +182,6 @@ public class ImmediateModeRecorder {
};
} else {
// Unsupported color type - use white
colorEffectiveStride = 0;
colorReader = (idx) -> GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
@@ -738,6 +247,8 @@ public class ImmediateModeRecorder {
return end();
}
@FunctionalInterface
private interface ColorReader {
void read(int index);
@@ -17,22 +17,4 @@ public interface DisplayListCommand {
default void delete() {
// Most commands don't hold resources
}
/**
* Handle this command during display list optimization.
*
* <p>Commands override this to implement their optimization behavior:
* <ul>
* <li>Matrix transforms: accumulate into the optimizer, return false</li>
* <li>Push/Pop: update stack, return true to emit</li>
* <li>Barriers: emit pending transforms, return true to emit</li>
* <li>State changes: return true to emit</li>
* </ul>
*
* @param ctx The optimization context providing access to transform state
* @return true if this command should be added to output, false if handled internally
*/
default boolean handleOptimization(OptimizationContext ctx) {
return true;
}
}
@@ -1,14 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
/**
* Represents a single draw call within a compiled display list.
* Each DrawCommand corresponds to one glBegin/glEnd block.
*/
@Desugar
public record DrawCommand(
int firstVertex,
int vertexCount,
int primitiveType
) {}
@@ -1,42 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import org.jetbrains.annotations.NotNull;
/**
* Command: Draw a range of vertices from a shared VBO.
* <p>
* DrawRangeCmd references a shared VBO owned by CompiledDisplayList.ownedVbos.
* Multiple DrawRangeCmds can reference different ranges within the same VBO,
* enabling format-based batching where all draws with the same vertex format
* share a single VBO.
* <p>
* Transform is NOT stored here - handled by TransformOptimizer emitting
* MultMatrixCmd before this command during optimization.
*/
@Desugar
public record DrawRangeCmd(
VertexBuffer sharedVbo,
int startVertex,
int vertexCount,
boolean hasBrightness
) implements DisplayListCommand {
@Override
public void execute() {
sharedVbo.setupState();
sharedVbo.draw(startVertex, vertexCount);
sharedVbo.cleanupState();
}
@Override
public void delete() {
// No-op: VBO lifetime is managed by CompiledDisplayList.ownedVbos
}
@Override
public @NotNull String toString() {
return "DrawRange(start=" + startVertex + ", count=" + vertexCount + ", hasBrightness=" + hasBrightness + ")";
}
}
@@ -5,7 +5,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
@@ -1,42 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import org.joml.Matrix4f;
/**
* Context provided to commands during display list optimization.
* Allows commands to interact with the transform optimizer and draw batcher.
*/
public interface OptimizationContext {
/** Get the accumulated MODELVIEW transform matrix. */
Matrix4f getAccumulatedTransform();
/** Reset accumulated transform to identity. */
void loadIdentity();
/** Push current accumulated transform onto stack. */
void pushTransform();
/** Pop transform from stack, restoring previous accumulated value. */
void popTransform();
/** Emit a MultMatrix command if accumulated differs from last emitted. */
void emitPendingTransform();
/** Emit a MultMatrix command to reach the target transform. */
void emitTransformTo(Matrix4f target);
/** Add a command to the output list. */
void emit(DisplayListCommand cmd);
/**
* Mark that the GL matrix is at an absolute value (after LoadMatrix).
* Subsequent LoadIdentity commands must be emitted to reset to identity.
*/
void markAbsoluteMatrix();
/**
* Check if the GL matrix is at an absolute value and clear the flag.
* @return true if LoadMatrix was called and not yet reset by LoadIdentity
*/
boolean checkAndClearAbsoluteMatrix();
}
@@ -1,8 +1,9 @@
package com.gtnewhorizons.angelica.glsm.states;
import java.nio.Buffer;
import org.lwjgl.opengl.GL11;
import java.nio.Buffer;
/**
* Tracks OpenGL client array state (glVertexPointer, glColorPointer, etc.)
* This state is NOT part of the server attribute stack (push/pop attrib),
@@ -1,8 +1,8 @@
package com.gtnewhorizons.angelica.glsm.states;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack;
import lombok.Getter;
import org.joml.Matrix4fStack;
import org.lwjgl.opengl.GL11;
@@ -1,11 +1,12 @@
package com.gtnewhorizons.angelica.hudcaching;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.CustomFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.SharedDepthFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexArrayBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.holoinventory.HoloInventoryReflectionCompat;
@@ -35,7 +36,7 @@ public class HUDCaching {
private static boolean dirty = true;
private static long nextHudRefresh;
private static VertexBuffer quadVAO;
private static IVertexArrayObject quadVAO;
private static float quadWidth;
private static float quadHeight;
@@ -188,14 +189,19 @@ public class HUDCaching {
private static void rebuildVAO(float width, float height) {
final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet();
final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(DefaultVertexFormat.POSITION_TEXTURE);
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0, height, 0.0, 0, 0);
tessellator.addVertexWithUV(width, height, 0.0, 1, 0);
tessellator.addVertexWithUV(width, 0, 0.0, 1, 1);
tessellator.addVertexWithUV(0, 0, 0.0, 0, 1);
tessellator.draw();
quadVAO = TessellatorManager.stopCapturingToVAO(quadVAO, DefaultVertexFormat.POSITION_TEXTURE);
if (quadVAO == null) {
quadVAO = tessellator.uploadToVBO(VertexBufferType.MUTABLE);
} else {
tessellator.updateToVBO(quadVAO.getVBO());
}
TessellatorManager.stopCapturingDirect();
}
public static void disableHoloInventory() {
@@ -41,11 +41,15 @@ public final class AngelicaRedirector {
private static final String Drawable = "org/lwjgl/opengl/Drawable";
private static final String GLStateManager = "com/gtnewhorizons/angelica/glsm/GLStateManager";
private static final String GL11 = "org/lwjgl/opengl/GL11";
private static final String GL11C = "org/lwjgl/opengl/GL11C";
private static final String GL12 = "org/lwjgl/opengl/GL12";
private static final String GL13 = "org/lwjgl/opengl/GL13";
private static final String GL14 = "org/lwjgl/opengl/GL14";
private static final String GL15 = "org/lwjgl/opengl/GL15";
private static final String GL20 = "org/lwjgl/opengl/GL20";
private static final String GL30 = "org/lwjgl/opengl/GL30";
private static final String ARBVertexArrayObject = "org/lwjgl/opengl/ARBVertexArrayObject";
private static final String APPLEVertexArrayObject = "org/lwjgl/opengl/APPLEVertexArrayObject";
private static final String Project = "org/lwjgl/util/glu/Project";
private static final String OpenGlHelper = "net/minecraft/client/renderer/OpenGlHelper";
private static final String EXTBlendFunc = "org/lwjgl/opengl/EXTBlendFuncSeparate";
@@ -224,6 +228,9 @@ public final class AngelicaRedirector {
.add("glBlendColor")
.add("glBlendEquation")
);
methodRedirects.put(GL15, RedirectMap.newMap()
.add("glBindBuffer")
);
methodRedirects.put(GL20, RedirectMap.newMap()
.add("glBlendEquationSeparate")
.add("glDrawBuffers")
@@ -233,8 +240,11 @@ public final class AngelicaRedirector {
.add("glUseProgram")
);
methodRedirects.put(GL30, RedirectMap.newMap()
.add("glBindVertexArray")
.add("glBindFramebuffer")
);
// MINECRAFT
methodRedirects.put(OpenGlHelper, RedirectMap.newMap()
.add("glBlendFunc", "tryBlendFuncSeparate")
.add("func_148821_a", "tryBlendFuncSeparate")
@@ -248,8 +258,31 @@ public final class AngelicaRedirector {
.add("isFramebufferEnabled")
);
methodRedirects.put(EXTBlendFunc, RedirectMap.newMap().add("glBlendFuncSeparateEXT", "tryBlendFuncSeparate"));
methodRedirects.put(ARBMultiTexture, RedirectMap.newMap().add("glActiveTextureARB"));
// ARB
methodRedirects.put(ARBMultiTexture, RedirectMap.newMap()
.add("glActiveTextureARB")
);
methodRedirects.put(ARBVertexArrayObject, RedirectMap.newMap()
.add("glBindVertexArray")
);
// APPLE
methodRedirects.put(APPLEVertexArrayObject, RedirectMap.newMap()
.add("glBindVertexArrayAPPLE")
);
// OTHER
methodRedirects.put(Project, RedirectMap.newMap().add("gluPerspective"));
final String glPrefix = "org/lwjgl/opengl/GL";
for (var entry : new HashMap<>(methodRedirects).entrySet()) {
if (entry.getKey().startsWith(glPrefix)) {
methodRedirects.put(entry.getKey() + "C", entry.getValue());
cstPoolParser.addString(entry.getKey() + "C");
}
}
}
public String[] getTransformerExclusions() {
@@ -280,7 +313,7 @@ public final class AngelicaRedirector {
boolean redirectInMethod = false;
for (AbstractInsnNode node : mn.instructions.toArray()) {
if (node instanceof MethodInsnNode mNode) {
if (mNode.owner.equals(GL11) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
if ((mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
final AbstractInsnNode prevNode = node.getPrevious();
String name = null;
if (prevNode instanceof LdcInsnNode ldcNode) {
@@ -321,15 +354,18 @@ public final class AngelicaRedirector {
}
} else {
final Map<String, String> redirects = methodRedirects.get(mNode.owner);
if (redirects != null && redirects.containsKey(mNode.name)) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, redirects.get(mNode.name), mNode.desc);
if (redirects != null) {
final String glsmName = redirects.get(mNode.name);
if (glsmName != null) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, mNode.desc);
}
mNode.owner = GLStateManager;
mNode.name = glsmName;
changed = true;
redirectInMethod = true;
}
mNode.owner = GLStateManager;
mNode.name = redirects.get(mNode.name);
changed = true;
redirectInMethod = true;
}
}
}
@@ -342,7 +378,7 @@ public final class AngelicaRedirector {
return changed;
}
private static class RedirectMap<K> extends HashMap<K, K> {
private static final class RedirectMap<K> extends HashMap<K, K> {
public static RedirectMap<String> newMap() {
return new RedirectMap<>();
@@ -196,7 +196,8 @@ public enum Mixins implements IMixins {
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"shaders.MixinEntityPickupFX"
"shaders.MixinDroppedItemGlintEdges"
, "shaders.MixinEntityPickupFX"
, "shaders.MixinEntityRenderer"
, "shaders.MixinGuiIngameForge"
, "shaders.MixinFramebuffer"
@@ -204,6 +205,7 @@ public enum Mixins implements IMixins {
, "shaders.MixinLocale"
, "shaders.MixinRender"
, "shaders.MixinRenderBiped"
, "shaders.MixinRenderDragon"
, "shaders.MixinRenderEntityFlame"
, "shaders.MixinRendererLivingEntity"
, "shaders.MixinRenderGlobal"
@@ -213,6 +215,8 @@ public enum Mixins implements IMixins {
, "shaders.MixinRenderNameTag"
, "shaders.MixinRenderPlayerArmor"
, "shaders.MixinTileEntityBeaconRenderer"
, "shaders.MixinRenderEndPortal"
, "shaders.MixinTileEntityRendererDispatcher"
)
),
@@ -451,6 +455,12 @@ public enum Mixins implements IMixins {
"MixinBlockTFMagicLeaves"
))
),
ET_FUTURUM_ELYTRA_CAPE(new MixinBuilder("Set custom item ID for elytra with cape texture")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.ET_FUTURUM_REQUIEM)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.etfuturum.MixinLayerBetterElytra")
),
MCPATCHER_FORGE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures)
@@ -14,6 +14,7 @@ public enum TargetedMod implements ITargetMod {
DYNAMIC_SURROUNDINGS_MIST("org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround"),
DYNAMIC_SURROUNDINGS_ORIGINAL("org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround"),
DRAGON_API("Reika.DragonAPI.Auxiliary.DragonAPIASMHandler", "DragonAPI"),
ET_FUTURUM_REQUIEM(null, "etfuturum"),
EXTRAUTILS(null, "ExtraUtilities"),
FALSETWEAKS("com.falsepattern.falsetweaks.asm.CoreLoadingPlugin", "falsetweaks"),
MINEFACTORY_RELOADED(null, "MineFactoryReloaded"),
@@ -1,11 +1,9 @@
package com.gtnewhorizons.angelica.proxy;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -18,6 +16,7 @@ import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.debug.OpenGLDebugging;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.mixins.interfaces.IGameSettingsExt;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
@@ -27,10 +26,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskRegistr
import com.gtnewhorizons.angelica.rendering.celeritas.threading.DefaultChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ThreadedChunkTaskProvider;
import com.gtnewhorizons.angelica.zoom.Zoom;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import cpw.mods.fml.client.registry.ClientRegistry;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.minecraftforge.client.ClientCommandHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
@@ -40,10 +36,11 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import jss.notfine.core.Settings;
import jss.notfine.gui.GuiCustomMenu;
import jss.notfine.gui.NotFineGameOptionPages;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.coderbot.iris.Iris;
import net.coderbot.iris.client.IrisDebugScreenHandler;
import net.minecraft.block.Block;
@@ -51,6 +48,8 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.settings.GameSettings;
@@ -61,14 +60,23 @@ import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import org.lwjgl.input.Keyboard;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
public class ClientProxy extends CommonProxy {
final Minecraft mc = Minecraft.getMinecraft();
@@ -323,6 +331,20 @@ public class ClientProxy extends CommonProxy {
}
}
@SubscribeEvent
public void onGuiInit(GuiScreenEvent.InitGuiEvent.Pre event) {
if(event.gui instanceof GuiVideoSettings eventGui) {
event.setCanceled(true);
if(AngelicaConfig.enableNotFineOptions || GuiScreen.isShiftKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new GuiCustomMenu(eventGui.parentGuiScreen, NotFineGameOptionPages.general(), NotFineGameOptionPages.detail(), NotFineGameOptionPages.atmosphere(), NotFineGameOptionPages.particles(), NotFineGameOptionPages.other()));
} else if(!AngelicaConfig.enableReesesSodiumOptions || GuiScreen.isCtrlKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(eventGui.parentGuiScreen));
} else {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(eventGui.parentGuiScreen));
}
}
}
/* coerce NaN fog values back to 0 (https://bugs.mojang.com/browse/MC-10480) - from ArchaicFix */
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onFogColor(EntityViewRenderEvent.FogColors event) {
@@ -21,16 +21,18 @@
package com.gtnewhorizons.angelica.render;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.core.Settings;
import jss.notfine.gui.options.named.GraphicsQualityOff;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourceManager;
@@ -46,7 +48,6 @@ public class CloudRenderer implements IResourceManagerReloadListener {
private static final float PX_SIZE = 1 / 256F;
// Building constants.
private static final VertexFormat FORMAT = DefaultVertexFormat.POSITION_TEXTURE_COLOR;
private static final int TOP_SECTIONS = 12; // Number of slices a top face will span.
private static final int HEIGHT = 4;
private static final float INSET = 0.001F;
@@ -59,7 +60,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
private final Minecraft mc = Minecraft.getMinecraft();
private final ResourceLocation texture = new ResourceLocation("textures/environment/clouds.png");
private VertexBuffer vbo;
private IVertexArrayObject vao;
private int cloudMode = -1;
private int renderDistance = -1;
private int cloudElevation = -1;
@@ -92,7 +93,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
return (float)Math.ceil(value / scale) * scale;
}
private void vertices(CapturingTessellator tessellator) {
private void vertices(Tessellator tessellator) {
GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore();
boolean fancy = cloudGraphicsQuality == GraphicsQualityOff.FANCY || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics;
@@ -133,18 +134,20 @@ public class CloudRenderer implements IResourceManagerReloadListener {
float v1 = sectZ1 * sectPx;
// Bottom
tessellator.pos(sectX0, 0, sectZ0).tex(u0, v0).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX1, 0, sectZ0).tex(u1, v0).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX1, 0, sectZ1).tex(u1, v1).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX0, 0, sectZ1).tex(u0, v1).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.setColorRGBA_F(bCol, bCol, bCol, ALPHA);
tessellator.addVertexWithUV(sectX0, 0, sectZ0, u0, v0);
tessellator.addVertexWithUV(sectX1, 0, sectZ0, u1, v0);
tessellator.addVertexWithUV(sectX1, 0, sectZ1, u1, v1);
tessellator.addVertexWithUV(sectX0, 0, sectZ1, u0, v1);
if (fancy) {
final int height = HEIGHT * scaleMult;
// Top
tessellator.pos(sectX0, height, sectZ0).tex(u0, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX0, height, sectZ1).tex(u0, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ1).tex(u1, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ0).tex(u1, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.setColorRGBA_F(1, 1, 1, ALPHA);
tessellator.addVertexWithUV(sectX0, height, sectZ0, u0, v0);
tessellator.addVertexWithUV(sectX0, height, sectZ1, u0, v1);
tessellator.addVertexWithUV(sectX1, height, sectZ1, u1, v1);
tessellator.addVertexWithUV(sectX1, height, sectZ0, u1, v0);
float slice;
float sliceCoord0;
@@ -157,10 +160,11 @@ public class CloudRenderer implements IResourceManagerReloadListener {
// X sides
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA);
tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1);
tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1);
tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0);
tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0);
slice -= INSET;
}
@@ -168,10 +172,11 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA);
tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0);
tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0);
tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1);
tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1);
slice += INSET;
}
}
@@ -183,10 +188,11 @@ public class CloudRenderer implements IResourceManagerReloadListener {
// Z sides
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA);
tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0);
tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1);
tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1);
tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0);
slice -= INSET;
}
@@ -194,10 +200,11 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA);
tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0);
tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1);
tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1);
tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0);
slice += INSET;
}
}
@@ -211,18 +218,16 @@ public class CloudRenderer implements IResourceManagerReloadListener {
}
private void dispose() {
if (vbo != null) {
vbo.close();
vbo = null;
if (vao != null) {
vao.delete();
vao = null;
}
}
private void build() {
CapturingTessellator tess = TessellatorManager.startCapturingAndGet();
vertices(tess);
this.vbo = TessellatorManager.stopCapturingToVAO(FORMAT);
final DirectTessellator tessellator = TessellatorManager.startCapturingDirect();
this.vertices(tessellator);
this.vao = DirectTessellator.stopCapturingToVBO(VertexBufferType.IMMUTABLE);
}
private int fullCoord(double coord, int scale) { // Corrects misalignment of UV offset when on negative coords.
@@ -230,7 +235,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
}
private boolean isBuilt() {
return vbo != null;
return vao != null;
}
public void checkSettings() {
@@ -345,12 +350,12 @@ public class CloudRenderer implements IResourceManagerReloadListener {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
mc.renderEngine.bindTexture(texture);
vbo.setupState();
vao.bind();
// Depth pass to prevent insides rendering from the outside.
GLStateManager.glColorMask(false, false, false, false);
vbo.draw();
vao.draw();
// Full render.
if (!mc.gameSettings.anaglyph) {
@@ -373,15 +378,15 @@ public class CloudRenderer implements IResourceManagerReloadListener {
GLStateManager.disableTexture();
GLStateManager.glDepthMask(false);
GLStateManager.disableFog();
vbo.draw();
vao.draw();
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
GLStateManager.glDepthMask(true);
GLStateManager.enableTexture();
GLStateManager.enableFog();
}
vbo.draw();
vbo.cleanupState(); // Unbind buffer and disable pointers.
vao.draw();
vao.unbind(); // Unbind buffer.
// Disable our coloring.
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
@@ -25,38 +25,32 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import it.unimi.dsi.fastutil.HashCommon;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import java.nio.ByteBuffer;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.minecraft.client.Minecraft;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
public class ItemRenderListManager {
// Least used element is at position 0. This is in theory slightly faster.
private static final Object2ObjectLinkedOpenHashMap<ItemProp, CachedVBO> vboCache = new Object2ObjectLinkedOpenHashMap<>(64);
// Formula: (widthSubdivisions * 2 + heightSubdivisions * 2 + 2) * 4 * vertexSize
// Using 256 as both variables due to enchants, to prevent later re-allocations.
private static ByteBuffer quadBuffer = BufferUtils.createByteBuffer(
(1026 * DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize()) << 2
);
// 1 minute
private static final int EXPIRY_TICKS = 1_200;
private static int smallestExpiry;
private static final ItemProp prop = new ItemProp();
public static VertexBuffer pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
public static CachedVBO pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
prop.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness);
if (!vboCache.isEmpty()) {
@@ -92,42 +86,35 @@ public class ItemRenderListManager {
vbo.expiry = getElapsedTicks() + EXPIRY_TICKS;
TessellatorManager.startCapturing();
return vbo.vertexBuffer;
return vbo;
}
public static void post(CapturingTessellator tessellator, VertexBuffer vbo) {
final var quads = TessellatorManager.stopCapturingToPooledQuads();
final int size = quads.size();
final int needed = (DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize() * size) << 2;
if (quadBuffer.capacity() < needed) {
quadBuffer = BufferUtils.createByteBuffer(HashCommon.nextPowerOfTwo(needed));
}
for (int i = 0; i < size; i++) {
DefaultVertexFormat.POSITION_TEXTURE_NORMAL.writeQuad(quads.get(i), quadBuffer);
}
quadBuffer.flip();
vbo.upload(quadBuffer);
quadBuffer.clear();
tessellator.clearQuads();
vbo.render();
public static void post(DirectTessellator tessellator, CachedVBO vbo) {
vbo.allocate(tessellator);
TessellatorManager.stopCapturingDirect();
vbo.vertexBuffer.render();
}
private static int getElapsedTicks() {
return Minecraft.getMinecraft().thePlayer.ticksExisted;
}
private static final class CachedVBO {
private VertexBuffer vertexBuffer;
public static final class CachedVBO {
private final IVertexArrayObject vertexBuffer;
private final IndexBuffer ebo;
private int expiry;
public CachedVBO() {
this.vertexBuffer = VAOManager.createVAO(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_QUADS);
this.ebo = new IndexBuffer();
this.vertexBuffer = VAOManager.createMutableVAO(
DefaultVertexFormat.POSITION_TEXTURE_NORMAL,
GL11.GL_TRIANGLES,
ebo
);
}
private void allocate(DirectTessellator tessellator) {
tessellator.allocateToVBO(vertexBuffer, ebo);
}
private void render(int elapsedTicks) {
@@ -136,8 +123,8 @@ public class ItemRenderListManager {
}
private void delete() {
vertexBuffer.close();
vertexBuffer = null;
vertexBuffer.delete();
// EBO gets deleted by vertexBuffer.delete()
}
}
@@ -1,32 +1,29 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource;
import java.util.Arrays;
import java.util.List;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexEncoder;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.render.chunk.ChunkColorWriter;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.QuadLightingHelper;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.world.IBlockAccess;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.ChunkColorWriter;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
@@ -36,6 +33,9 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.util.QuadUtil;
import java.util.Arrays;
import java.util.List;
public class AngelicaChunkBuildContext extends ChunkBuildContext {
public static final int NUM_PASSES = 2;
@@ -95,7 +95,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
private Material selectMaterial(Material material, TextureAtlasSprite sprite, boolean isShaderPackOverride) {
// Don't apply transparency-based optimization when shader pack explicitly overrides the material
if (isShaderPackOverride) {
if (!AngelicaMod.options().performance.useRenderPassOptimization || isShaderPackOverride) {
return material;
}
if (sprite != null && sprite.getClass() == TextureAtlasSprite.class && !sprite.hasAnimationMetadata()) {
@@ -124,7 +124,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
final boolean hasDynamicLights = chunkLightSources != null && !chunkLightSources.isEmpty();
final boolean separateAo = BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
final boolean celeritasSmoothLighting = SodiumClientMod.options().quality.useCeleritasSmoothLighting;
final boolean celeritasSmoothLighting = AngelicaMod.options().quality.useCeleritasSmoothLighting;
final boolean shaderActive = IrisApi.getInstance().isShaderPackInUse();
final boolean useAoCalculation = lightPipelineReady && (separateAo || celeritasSmoothLighting || shaderActive);
final boolean stripDiffuse = shaderActive && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
@@ -1,11 +1,12 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.world.cloned.ClonedChunkSectionCache;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -15,7 +16,6 @@ import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSectionManager;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask;
import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker;
@@ -23,12 +23,11 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.embeddedt.embeddium.impl.render.chunk.sprite.GenericSectionSpriteTicker;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.Nullable;
import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -88,7 +87,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected AsyncOcclusionMode getAsyncOcclusionMode() {
return AsyncOcclusionMode.EVERYTHING;
return AngelicaMod.options().performance.asyncOcclusionMode;
}
@Override
@@ -98,7 +97,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean useFogOcclusion() {
return true;
return AngelicaMod.options().performance.useFogOcclusion && !IrisShaderProviderHolder.isActive();
}
@Override
@@ -108,10 +107,13 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean shouldUseOcclusionCulling(Viewport positionedViewport, boolean spectator) {
if (!spectator) return true;
final var camBlockPos = positionedViewport.getBlockCoord();
return !this.world.getBlock(camBlockPos.x(), camBlockPos.y(), camBlockPos.z()).isOpaqueCube();
if (spectator) {
final var camBlockPos = positionedViewport.getBlockCoord();
if (this.world.getBlock(camBlockPos.x(), camBlockPos.y(), camBlockPos.z()).isOpaqueCube()) {
return false;
}
}
return AngelicaMod.options().performance.useOcclusionCulling;
}
@Override
@@ -150,7 +152,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean allowImportantRebuilds() {
return !SodiumClientMod.options().performance.alwaysDeferChunkUpdates;
return !AngelicaMod.options().performance.alwaysDeferChunkUpdates;
}
@Override
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice;
import org.lwjgl.opengl.GL15;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
@@ -10,7 +11,7 @@ public class CeleritasSetup {
public static void ensureInitialized() {
if (!initialized && AngelicaConfig.enableCeleritas) {
GLRenderDevice.VANILLA_STATE_RESETTER = () -> GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLRenderDevice.VANILLA_STATE_RESETTER = () -> GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
LOGGER.debug("Celeritas init");
initialized = true;
}
@@ -1,11 +1,14 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import net.coderbot.iris.pipeline.ShadowRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
@@ -23,9 +26,6 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import org.embeddedt.embeddium.impl.render.terrain.SimpleWorldRenderer;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4f;
@@ -118,7 +118,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
}
}
if (SodiumClientMod.options().advanced.useCompactVertexFormat) {
if (AngelicaMod.options().performance.useCompactVertexFormat) {
return ChunkMeshFormats.COMPACT;
}
return ChunkMeshFormats.VANILLA_LIKE;
@@ -146,7 +146,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
renderSectionManager.setCameraPosition(transform.x, transform.y, transform.z);
this.useEntityCulling = true;
this.useEntityCulling = AngelicaMod.options().performance.useEntityCulling;
super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately);
@@ -1,6 +1,7 @@
package com.prupe.mcpatcher.ctm;
import net.minecraft.block.Block;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
@@ -8,6 +9,9 @@ import com.prupe.mcpatcher.mal.block.BlockStateMatcher;
final class BlockOrientation extends RenderBlockState {
private static final boolean fixedBottomFaceUV = (boolean) Launch.blackboard
.getOrDefault("hodgepodge.FixesConfig.fixBottomFaceUV", Boolean.FALSE);
// NEIGHBOR_OFFSETS[a][b][c] = offset from starting block
// a: face 0-5
// b: neighbor 0-7
@@ -16,7 +20,11 @@ final class BlockOrientation extends RenderBlockState {
// 1 2 3
// c: coordinate (x,y,z) 0-2
private static final int[][][] NEIGHBOR_OFFSET = new int[][][] {
makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // BOTTOM_FACE
(
fixedBottomFaceUV
? makeNeighborOffset(EAST_FACE, SOUTH_FACE, WEST_FACE, NORTH_FACE) // BOTTOM_FACE fixedBottomFaceUV
: makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE) // BOTTOM_FACE not fixed
),
makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // TOP_FACE
makeNeighborOffset(EAST_FACE, BOTTOM_FACE, WEST_FACE, TOP_FACE), // NORTH_FACE
makeNeighborOffset(WEST_FACE, BOTTOM_FACE, EAST_FACE, TOP_FACE), // SOUTH_FACE
@@ -1,7 +1,6 @@
package jss.notfine.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.config.NotFineConfig;
import jss.notfine.core.Settings;
@@ -297,7 +296,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useBlockFaceCulling = value, opts -> opts.advanced.useBlockFaceCulling)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
@@ -305,14 +304,14 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useCompactVertexFormat = value, opts -> opts.advanced.useCompactVertexFormat)
.setBinding((opts, value) -> opts.performance.useCompactVertexFormat = value, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_fog_occlusion.name"))
.setTooltip(I18n.format("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.useFogOcclusion = value, opts -> opts.advanced.useFogOcclusion)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
@@ -320,7 +319,7 @@ public class NotFineGameOptionPages {
.setName(I18n.format("sodium.options.translucency_sorting.name"))
.setTooltip(I18n.format("sodium.options.translucency_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.translucencySorting = value, opts -> opts.advanced.translucencySorting)
.setBinding((opts, value) -> opts.performance.translucencySorting = value, opts -> opts.performance.translucencySorting)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
@@ -329,7 +328,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useEntityCulling = value, opts -> opts.advanced.useEntityCulling)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_particle_culling.name"))
@@ -345,7 +344,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.animateOnlyVisibleTextures = value, opts -> opts.advanced.animateOnlyVisibleTextures)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.build())
.build());
groups.add(OptionGroup.createBuilder()
@@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.client.gui.FontConfigScreen;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import jss.notfine.gui.GuiCustomMenu;
import net.coderbot.iris.Iris;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.AbstractFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.BasicFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components.SearchTextFieldComponent;
@@ -19,6 +18,7 @@ import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.gui.GuiScreen;
@@ -283,7 +283,7 @@ public class ReeseSodiumVideoOptionsScreen extends SodiumOptionsGUI {
}
if (keyCode == Keyboard.KEY_P) {
if(isShiftKeyDown()){
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(), SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(), SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance(), SodiumGameOptionPages.appearance(), SodiumGameOptionPages.debug()));
} else if (isCtrlKeyDown()) {
this.mc.displayGuiScreen(new SodiumOptionsGUI(this.prevScreen));
}
@@ -1,88 +0,0 @@
package me.jellysquid.mods.sodium.client;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.proxy.CommonProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(modid = SodiumClientMod.MODID,
name = SodiumClientMod.NAME,
version = Tags.VERSION,
acceptedMinecraftVersions = "[1.7.10]",
acceptableRemoteVersions = "*")
public class SodiumClientMod {
@SidedProxy(clientSide = "me.jellysquid.mods.sodium.proxy.ClientProxy", serverSide = "me.jellysquid.mods.sodium.proxy.CommonProxy")
public static CommonProxy proxy;
private static SodiumGameOptions CONFIG;
public static Logger LOGGER = LogManager.getLogger("Embeddium");
private static String MOD_VERSION = Tags.VERSION;
public static final String MODID = "embeddium";
public static final String NAME = "Embeddium";
@Getter
private static Thread MainThread;
public SodiumClientMod() {
MainThread = Thread.currentThread();
}
public static SodiumGameOptions options() {
if (CONFIG == null) {
CONFIG = loadConfig();
}
return CONFIG;
}
public static Logger logger() {
if (LOGGER == null) {
LOGGER = LogManager.getLogger("Embeddium");
}
return LOGGER;
}
private static SodiumGameOptions loadConfig() {
return SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
public static String getVersion() {
if (MOD_VERSION == null) {
throw new NullPointerException("Mod version hasn't been populated yet");
}
return MOD_VERSION;
}
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
proxy.preInit(event);
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
proxy.init(event);
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
proxy.postInit(event);
}
public static boolean isDirectMemoryAccessEnabled() {
return options().advanced.allowDirectMemoryAccess;
}
}
@@ -2,7 +2,6 @@ package me.jellysquid.mods.sodium.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.core.Settings;
import jss.notfine.core.SettingsManager;
@@ -28,6 +27,7 @@ import net.coderbot.iris.gui.option.IrisVideoSettings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.lwjgl.opengl.Display;
import java.io.IOException;
@@ -80,19 +80,6 @@ public class SodiumGameOptionPages {
.setControl(opt -> new SliderControl(opt, 0, 100, 1, ControlValueFormatter.brightness()))
.setBinding((opts, value) -> opts.gammaSetting = value * 0.01F, (opts) -> (int) (opts.gammaSetting / 0.01F))
.build());
firstGroupBuilder.add(Settings.MODE_LIGHT_FLICKER.option)
.add(Settings.MODE_SKY.option)
.add(Settings.MODE_SUN_MOON.option)
.add(Settings.RENDER_DISTANCE_CLOUDS.option)
.add(Settings.CLOUD_HEIGHT.option)
.add(Settings.CLOUD_SCALE.option)
.add(Settings.MODE_CLOUD_TRANSLUCENCY.option)
.add(Settings.MODE_STARS.option)
.add(Settings.TOTAL_STARS.option)
.add(Settings.HORIZON_DISABLE.option)
.add(Settings.FOG_DISABLE.option)
.add(Settings.FOG_NEAR_DISTANCE.option)
.add(Settings.VOID_FOG.option);
groups.add(firstGroupBuilder.build());
int maxGuiScale = Math.max(3, Math.min(Minecraft.getMinecraft().displayWidth / 320, Minecraft.getMinecraft().displayHeight / 240));
@@ -166,24 +153,6 @@ public class SodiumGameOptionPages {
.add(Settings.DYNAMIC_FOV.option)
.add(Settings.MODE_WATER.option)
.add(Settings.MODE_DROPPED_ITEMS.option)
.add(
OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.droppedItemLimit"))
.setTooltip(I18n.format("options.angelica.droppedItemLimit.tooltip"))
.setControl(option -> new SliderControl(option, 32, 2048, 32, ControlValueFormatter.droppedItemLimitLimit()))
.setBinding((options, value) -> AngelicaConfig.droppedItemLimit = value, options -> AngelicaConfig.droppedItemLimit)
.setImpact(OptionImpact.MEDIUM)
.build()
)
.add(
OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.mobSpawnerRenderDistance"))
.setTooltip(I18n.format("options.angelica.mobSpawnerRenderDistance.tooltip"))
.setControl(option -> new SliderControl(option, 16, 64, 1, ControlValueFormatter.number()))
.setBinding((options, value) -> AngelicaConfig.mobSpawnerRenderDistance = value, options -> (int) AngelicaConfig.mobSpawnerRenderDistance)
.setImpact(OptionImpact.MEDIUM)
.build()
)
.build());
return new OptionPage(I18n.format("stat.generalButton"), ImmutableList.copyOf(groups));
@@ -305,7 +274,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useBlockFaceCulling = value, opts -> opts.advanced.useBlockFaceCulling)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
@@ -314,7 +283,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useCompactVertexFormat = value, opts -> opts.advanced.useCompactVertexFormat)
.setBinding((opts, value) -> opts.performance.useCompactVertexFormat = value, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
@@ -322,7 +291,7 @@ public class SodiumGameOptionPages {
.setName(I18n.format("sodium.options.use_fog_occlusion.name"))
.setTooltip(I18n.format("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.useFogOcclusion = value, opts -> opts.advanced.useFogOcclusion)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
@@ -331,7 +300,7 @@ public class SodiumGameOptionPages {
.setName(I18n.format("sodium.options.translucency_sorting.name"))
.setTooltip(I18n.format("sodium.options.translucency_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.translucencySorting = value, opts -> opts.advanced.translucencySorting)
.setBinding((opts, value) -> opts.performance.translucencySorting = value, opts -> opts.performance.translucencySorting)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
@@ -341,7 +310,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useEntityCulling = value, opts -> opts.advanced.useEntityCulling)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
@@ -357,7 +326,34 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.animateOnlyVisibleTextures = value, opts -> opts.advanced.animateOnlyVisibleTextures)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_render_pass_optimization.name"))
.setTooltip(I18n.format("sodium.options.use_render_pass_optimization.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useRenderPassOptimization = value, opts -> opts.performance.useRenderPassOptimization)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_occlusion_culling.name"))
.setTooltip(I18n.format("sodium.options.use_occlusion_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> opts.performance.useOcclusionCulling = value, opts -> opts.performance.useOcclusionCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(AsyncOcclusionMode.class, sodiumOpts)
.setName(I18n.format("sodium.options.async_occlusion_mode.name"))
.setTooltip(I18n.format("sodium.options.async_occlusion_mode.tooltip"))
.setControl(o -> new CyclingControl<>(o, AsyncOcclusionMode.class, new String[]{"None", "Only Shadow", "Everything"}))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.asyncOcclusionMode = value, opts -> opts.performance.asyncOcclusionMode)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build());
@@ -383,28 +379,6 @@ public class SodiumGameOptionPages {
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.itemdisplaylistcount"))
.setTooltip(I18n.format("options.angelica.itemdisplaylistcount.tooltip"))
.setControl(o -> new SliderControl(o, 256, 1024, 16, ControlValueFormatter.number()))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> AngelicaConfig.itemRendererCacheSize = value, options -> AngelicaConfig.itemRendererCacheSize)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_GUI_BACKGROUND.option)
.add(Settings.GUI_BACKGROUND.option)
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.disablef3"))
.setTooltip(I18n.format("options.angelica.disablef3.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> AngelicaConfig.disableF3Additions = value, opts -> AngelicaConfig.disableF3Additions)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.advanced"), ImmutableList.copyOf(groups));
}
@@ -446,14 +420,6 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.performance.useNoErrorGLContext = value, opts -> opts.performance.useNoErrorGLContext)
.setFlags(OptionFlag.REQUIRES_GAME_RESTART)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_gl_state_cache.name"))
.setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.aggressiveChunkLoading"))
.setTooltip(I18n.format("options.angelica.aggressiveChunkLoading.tooltip"))
@@ -462,9 +428,94 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> AngelicaConfig.useVanillaChunkTracking = value, opts -> AngelicaConfig.useVanillaChunkTracking)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setName(I18n.format("sodium.options.cpu_render_ahead_limit.name"))
.setTooltip(I18n.format("sodium.options.cpu_render_ahead_limit.tooltip"))
.setControl(o -> new SliderControl(o, 0, 9, 1, ControlValueFormatter.quantity("sodium.options.cpu_render_ahead_limit.value")))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.cpuRenderAheadLimit = value, opts -> opts.performance.cpuRenderAheadLimit)
.setEnabled(GLStateManager.capabilities != null && GLStateManager.capabilities.OpenGL32)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.droppedItemLimit"))
.setTooltip(I18n.format("options.angelica.droppedItemLimit.tooltip"))
.setControl(option -> new SliderControl(option, 32, 2048, 32, ControlValueFormatter.droppedItemLimitLimit()))
.setBinding((options, value) -> AngelicaConfig.droppedItemLimit = value, options -> AngelicaConfig.droppedItemLimit)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.mobSpawnerRenderDistance"))
.setTooltip(I18n.format("options.angelica.mobSpawnerRenderDistance.tooltip"))
.setControl(option -> new SliderControl(option, 16, 64, 1, ControlValueFormatter.number()))
.setBinding((options, value) -> AngelicaConfig.mobSpawnerRenderDistance = value, options -> (int) AngelicaConfig.mobSpawnerRenderDistance)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.itemdisplaylistcount"))
.setTooltip(I18n.format("options.angelica.itemdisplaylistcount.tooltip"))
.setControl(o -> new SliderControl(o, 256, 1024, 16, ControlValueFormatter.number()))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> AngelicaConfig.itemRendererCacheSize = value, options -> AngelicaConfig.itemRendererCacheSize)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.performance"), ImmutableList.copyOf(groups));
}
public static OptionPage appearance() {
final List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_SKY.option)
.add(Settings.MODE_SUN_MOON.option)
.add(Settings.RENDER_DISTANCE_CLOUDS.option)
.add(Settings.CLOUD_HEIGHT.option)
.add(Settings.CLOUD_SCALE.option)
.add(Settings.MODE_CLOUD_TRANSLUCENCY.option)
.add(Settings.MODE_STARS.option)
.add(Settings.TOTAL_STARS.option)
.add(Settings.HORIZON_DISABLE.option)
.add(Settings.MODE_LIGHT_FLICKER.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.FOG_DISABLE.option)
.add(Settings.FOG_NEAR_DISTANCE.option)
.add(Settings.VOID_FOG.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_GUI_BACKGROUND.option)
.add(Settings.GUI_BACKGROUND.option)
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.disablef3"))
.setTooltip(I18n.format("options.angelica.disablef3.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> AngelicaConfig.disableF3Additions = value, opts -> AngelicaConfig.disableF3Additions)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.appearance"), ImmutableList.copyOf(groups));
}
public static OptionPage debug() {
final List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_gl_state_cache.name"))
.setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.debug"), ImmutableList.copyOf(groups));
}
}
@@ -4,9 +4,11 @@ import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality;
import net.coderbot.iris.Iris;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import java.io.FileReader;
import java.io.IOException;
@@ -26,21 +28,26 @@ public class SodiumGameOptions {
public boolean useVertexArrayObjects = true;
public boolean useChunkMultidraw = true;
public boolean animateOnlyVisibleTextures = true;
public boolean useEntityCulling = true;
public boolean useParticleCulling = true;
public boolean useFogOcclusion = true;
public boolean useCompactVertexFormat = true;
public boolean useBlockFaceCulling = true;
public boolean allowDirectMemoryAccess = true;
public boolean ignoreDriverBlacklist = false;
public boolean translucencySorting = true;
}
public static class PerformanceSettings {
public int chunkBuilderThreads = 0;
public boolean alwaysDeferChunkUpdates = true;
public boolean useNoErrorGLContext = true;
public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.EVERYTHING;
public boolean useOcclusionCulling = true;
public boolean animateOnlyVisibleTextures = true;
public boolean useEntityCulling = true;
public boolean useFogOcclusion = true;
public boolean useBlockFaceCulling = true;
public boolean useCompactVertexFormat = true;
public boolean translucencySorting = true;
public boolean useRenderPassOptimization = true;
public int cpuRenderAheadLimit = 3;
}
public static class EntityRenderDistance {
@@ -74,7 +81,7 @@ public class SodiumGameOptions {
} catch (IOException e) {
throw new RuntimeException("Could not parse config", e);
} catch (JsonSyntaxException e) {
SodiumClientMod.logger().error("Could not parse config, will fallback to default settings", e);
AngelicaMod.LOGGER.error("Could not parse config, will fallback to default settings", e);
config = new SodiumGameOptions();
resaveConfig = false;
}
@@ -84,6 +91,11 @@ public class SodiumGameOptions {
config.configPath = path;
// Clamp render-ahead to 0 if GL 3.2 fences aren't available
if (GLStateManager.capabilities == null || !GLStateManager.capabilities.OpenGL32) {
config.performance.cpuRenderAheadLimit = 0;
}
try {
if(resaveConfig)
config.writeChanges();
@@ -7,7 +7,6 @@ import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import jss.notfine.gui.GuiCustomMenu;
import net.coderbot.iris.Iris;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
@@ -19,6 +18,7 @@ import me.jellysquid.mods.sodium.client.gui.options.control.element.SodiumContro
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
@@ -62,6 +62,7 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
this.pages.add(SodiumGameOptionPages.quality());
this.pages.add(SodiumGameOptionPages.advanced());
this.pages.add(SodiumGameOptionPages.performance());
this.pages.add(SodiumGameOptionPages.appearance());
// Add Dynamic Lights page if enabled
if (DynamicLights.configEnabled) {
@@ -75,6 +76,8 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
shaderPacks = new OptionPage(I18n.format("options.iris.shaderPackSelection"), ImmutableList.of());
this.pages.add(shaderPacks);
}
this.pages.add(SodiumGameOptionPages.debug());
}
public void setPage(OptionPage page) {
@@ -298,7 +301,8 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
if (keyCode == Keyboard.KEY_P && isShiftKeyDown()) {
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(),
SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance(),
SodiumGameOptionPages.appearance(), SodiumGameOptionPages.debug()));
}
}
@@ -1,8 +1,8 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
public class AngelicaOptionsStorage implements OptionStorage<AngelicaConfig> {
@@ -18,6 +18,6 @@ public class AngelicaOptionsStorage implements OptionStorage<AngelicaConfig> {
@Override
public void save() {
ConfigurationManager.save(AngelicaConfig.class);
SodiumClientMod.logger().info("Flushed changes to Angelica configuration");
AngelicaMod.LOGGER.info("Flushed changes to Angelica configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
@@ -20,6 +20,6 @@ public class MinecraftOptionsStorage implements OptionStorage<GameSettings> {
public void save() {
this.getData().saveOptions();
SodiumClientMod.logger().info("Flushed changes to Minecraft configuration");
AngelicaMod.LOGGER.info("Flushed changes to Minecraft configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import java.io.IOException;
@@ -9,7 +9,7 @@ public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> {
private final SodiumGameOptions options;
public SodiumOptionsStorage() {
this.options = SodiumClientMod.options();
this.options = AngelicaMod.options();
}
@Override
@@ -25,6 +25,6 @@ public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> {
throw new RuntimeException("Couldn't save configuration changes", e);
}
SodiumClientMod.logger().info("Flushed changes to Angelica configuration");
AngelicaMod.LOGGER.info("Flushed changes to Angelica configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.utils;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraft.util.Util;
import java.io.IOException;
@@ -19,7 +19,7 @@ public class URLUtils {
try {
Runtime.getRuntime().exec(getURLOpenCommand(url));
} catch (IOException exception) {
SodiumClientMod.logger().error("Couldn't open url '{}'", url, exception);
AngelicaMod.LOGGER.error("Couldn't open url '{}'", url, exception);
}
}
@@ -1,56 +0,0 @@
package me.jellysquid.mods.sodium.proxy;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import jss.notfine.gui.GuiCustomMenu;
import jss.notfine.gui.NotFineGameOptionPages;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.MinecraftForge;
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onGui(GuiScreenEvent.InitGuiEvent.Pre event) {
if(event.gui instanceof GuiVideoSettings eventGui) {
event.setCanceled(true);
if(AngelicaConfig.enableNotFineOptions || GuiScreen.isShiftKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new GuiCustomMenu(eventGui.parentGuiScreen,
NotFineGameOptionPages.general(),
NotFineGameOptionPages.detail(), NotFineGameOptionPages.atmosphere(),
NotFineGameOptionPages.particles(), NotFineGameOptionPages.other()
));
} else if(!AngelicaConfig.enableReesesSodiumOptions || GuiScreen.isCtrlKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(eventGui.parentGuiScreen));
} else {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(eventGui.parentGuiScreen));
}
}
}
@Override
public void init(FMLInitializationEvent event) {
// Nothing to do here (yet)
}
@Override
public void postInit(FMLPostInitializationEvent event) {
// Nothing to do here (yet)
}
}
@@ -1,16 +0,0 @@
package me.jellysquid.mods.sodium.proxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
}
public void init(FMLInitializationEvent event) {}
public void postInit(FMLPostInitializationEvent event) {}
}
@@ -12,6 +12,7 @@ import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.coderbot.iris.shaderpack.ProgramSource;
@@ -146,7 +147,7 @@ public class CeleritasTerrainPipeline {
public ProgramUniforms.Builder initUniforms(int programId) {
final ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<celeritas shaders>", programId);
CommonUniforms.addDynamicUniforms(uniforms);
CommonUniforms.addDynamicUniforms(uniforms, FogMode.PER_VERTEX);
customUniforms.assignTo(uniforms);
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
@@ -15,6 +15,10 @@ public enum FeatureFlags {
BLOCK_EMISSION_ATTRIBUTE(() -> true, () -> true),
CUSTOM_IMAGES(() -> true, RenderSystem::supportsImageLoadStore),
SSBO(() -> true, RenderSystem::supportsSSBO),
HIGHER_SHADOWCOLOR(() -> true, () -> true),
TESSELLATION_SHADERS(() -> true, RenderSystem::supportsTesselation),
REVERSED_CULLING(() -> true, () -> true),
CAN_DISABLE_WEATHER(() -> true, () -> true),
UNKNOWN(() -> false, () -> false);
private final BooleanSupplier irisRequirement;
@@ -55,16 +59,16 @@ public enum FeatureFlags {
}
public static boolean isInvalid(String name) {
try {
return !FeatureFlags.valueOf(name).isUsable();
} catch (IllegalArgumentException e) {
return true;
}
FeatureFlags flag = getValue(name);
return flag == UNKNOWN || !flag.isUsable();
}
public static FeatureFlags getValue(String value) {
if (value.equalsIgnoreCase("TESSELATION_SHADERS")) {
value = "TESSELLATION_SHADERS";
}
try {
return FeatureFlags.valueOf(value);
return FeatureFlags.valueOf(value.toUpperCase(java.util.Locale.US));
} catch (IllegalArgumentException e) {
return FeatureFlags.UNKNOWN;
}
@@ -1,6 +1,8 @@
package net.coderbot.iris.gl.blending;
public class AlphaTest {
public static final AlphaTest ALWAYS = new AlphaTest(AlphaTestFunction.ALWAYS, 0.0f);
private final AlphaTestFunction function;
private final float reference;
@@ -16,4 +18,45 @@ public class AlphaTest {
public float getReference() {
return reference;
}
public String toExpression(String indentation) {
return toExpression("gl_FragData[0].a", "iris_currentAlphaTest", indentation);
}
public String toExpression(String alphaAccessor, String alphaThreshold, String indentation) {
String expr = function.getExpression();
if (function == AlphaTestFunction.ALWAYS) {
return "// alpha test disabled\n";
} else if (function == AlphaTestFunction.NEVER) {
return "discard;\n";
}
return indentation + "if (!(" + alphaAccessor + " " + expr + " " + alphaThreshold + ")) {\n" +
indentation + " discard;\n" +
indentation + "}\n";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((function == null) ? 0 : function.hashCode());
result = prime * result + Float.floatToIntBits(reference);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AlphaTest other = (AlphaTest) obj;
if (function != other.function)
return false;
return Float.floatToIntBits(reference) == Float.floatToIntBits(other.reference);
}
}
@@ -5,33 +5,35 @@ import org.lwjgl.opengl.GL11;
import java.util.Optional;
public enum AlphaTestFunction {
NEVER(GL11.GL_NEVER),
LESS(GL11.GL_LESS),
EQUAL(GL11.GL_EQUAL),
LEQUAL(GL11.GL_LEQUAL),
GREATER(GL11.GL_GREATER),
NOTEQUAL(GL11.GL_NOTEQUAL),
GEQUAL(GL11.GL_GEQUAL),
ALWAYS(GL11.GL_ALWAYS);
NEVER(GL11.GL_NEVER, null),
LESS(GL11.GL_LESS, "<"),
EQUAL(GL11.GL_EQUAL, "=="),
LEQUAL(GL11.GL_LEQUAL, "<="),
GREATER(GL11.GL_GREATER, ">"),
NOTEQUAL(GL11.GL_NOTEQUAL, "!="),
GEQUAL(GL11.GL_GEQUAL, ">="),
ALWAYS(GL11.GL_ALWAYS, null);
private final int glId;
private final String expression;
AlphaTestFunction(int glFormat) {
AlphaTestFunction(int glFormat, String expression) {
this.glId = glFormat;
this.expression = expression;
}
public static Optional<AlphaTestFunction> fromGlId(int glId) {
return switch (glId) {
case GL11.GL_NEVER -> Optional.of(NEVER);
case GL11.GL_LESS -> Optional.of(LESS);
case GL11.GL_EQUAL -> Optional.of(EQUAL);
case GL11.GL_LEQUAL -> Optional.of(LEQUAL);
case GL11.GL_GREATER -> Optional.of(GREATER);
case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL);
case GL11.GL_GEQUAL -> Optional.of(GEQUAL);
case GL11.GL_ALWAYS -> Optional.of(ALWAYS);
default -> Optional.empty();
};
return switch (glId) {
case GL11.GL_NEVER -> Optional.of(NEVER);
case GL11.GL_LESS -> Optional.of(LESS);
case GL11.GL_EQUAL -> Optional.of(EQUAL);
case GL11.GL_LEQUAL -> Optional.of(LEQUAL);
case GL11.GL_GREATER -> Optional.of(GREATER);
case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL);
case GL11.GL_GEQUAL -> Optional.of(GEQUAL);
case GL11.GL_ALWAYS -> Optional.of(ALWAYS);
default -> Optional.empty();
};
}
public static Optional<AlphaTestFunction> fromString(String name) {
@@ -54,4 +56,8 @@ public enum AlphaTestFunction {
public int getGlId() {
return glId;
}
public String getExpression() {
return expression;
}
}
@@ -19,6 +19,6 @@ public class ImageBinding {
public void update() {
// We can assume that image bindings are supported here as either the EXT extension or 4.2 core, as otherwise ImageLimits
// would report that zero image units are supported.
RenderSystem.bindImageTexture(imageUnit, textureID.getAsInt(), 0, false, 0, GL15.GL_READ_WRITE, internalFormat);
RenderSystem.bindImageTexture(imageUnit, textureID.getAsInt(), 0, true, 0, GL15.GL_READ_WRITE, internalFormat);
}
}
@@ -34,36 +34,31 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo
public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource,
@Nullable String fragmentSource, ImmutableSet<Integer> reservedTextureUnits) {
GlShader vertex;
GlShader geometry;
GlShader fragment;
return begin(name, vertexSource, geometrySource, null, null, fragmentSource, reservedTextureUnits);
}
vertex = buildShader(ShaderType.VERTEX, name + ".vsh", vertexSource);
public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource,
@Nullable String tessControlSource, @Nullable String tessEvalSource,
@Nullable String fragmentSource, ImmutableSet<Integer> reservedTextureUnits) {
GlShader vertex = buildShader(ShaderType.VERTEX, name + ".vsh", vertexSource);
GlShader geometry = geometrySource != null ? buildShader(ShaderType.GEOMETRY, name + ".gsh", geometrySource) : null;
GlShader tessControl = tessControlSource != null ? buildShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControlSource) : null;
GlShader tessEval = tessEvalSource != null ? buildShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEvalSource) : null;
GlShader fragment = buildShader(ShaderType.FRAGMENT, name + ".fsh", fragmentSource);
if (geometrySource != null) {
geometry = buildShader(ShaderType.GEOMETRY, name + ".gsh", geometrySource);
} else {
geometry = null;
java.util.List<GlShader> shaders = new java.util.ArrayList<>();
shaders.add(vertex);
if (geometry != null) shaders.add(geometry);
if (tessControl != null) shaders.add(tessControl);
if (tessEval != null) shaders.add(tessEval);
shaders.add(fragment);
int programId = ProgramCreator.create(name, shaders.toArray(new GlShader[0]));
for (GlShader shader : shaders) {
shader.destroy();
}
fragment = buildShader(ShaderType.FRAGMENT, name + ".fsh", fragmentSource);
int programId;
if (geometry != null) {
programId = ProgramCreator.create(name, vertex, geometry, fragment);
} else {
programId = ProgramCreator.create(name, vertex, fragment);
}
vertex.destroy();
if (geometry != null) {
geometry.destroy();
}
fragment.destroy();
return new ProgramBuilder(name, programId, reservedTextureUnits);
}
@@ -12,7 +12,7 @@ import org.lwjgl.opengl.KHRDebug;
public class ProgramCreator {
private static final Logger LOGGER = LogManager.getLogger(ProgramCreator.class);
private static final Logger LOGGER = LogManager.getLogger("ProgramCreator");
public static final int MC_ENTITY = 11;
public static final int MC_MID_TEX_COORD = 12;
@@ -4,6 +4,7 @@ package net.coderbot.iris.gl.shader;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.lwjgl.opengl.GL40;
import org.lwjgl.opengl.GL43;
/**
@@ -12,6 +13,8 @@ import org.lwjgl.opengl.GL43;
public enum ShaderType {
VERTEX(GL20.GL_VERTEX_SHADER),
GEOMETRY(GL32.GL_GEOMETRY_SHADER),
TESSELATION_CONTROL(GL40.GL_TESS_CONTROL_SHADER),
TESSELATION_EVAL(GL40.GL_TESS_EVALUATION_SHADER),
FRAGMENT(GL20.GL_FRAGMENT_SHADER),
COMPUTE(GL43.GL_COMPUTE_SHADER);
@@ -2,6 +2,7 @@ package net.coderbot.iris.gl.shader;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.Loader;
import net.coderbot.iris.parsing.BiomeCategories;
import net.coderbot.iris.pipeline.HandRenderer;
@@ -75,6 +76,9 @@ public class StandardMacros {
define(standardDefines, "MC_RENDER_QUALITY", "1.0");
define(standardDefines, "MC_SHADOW_QUALITY", "1.0");
define(standardDefines, "IS_ANGELICA");
if (AngelicaConfig.defineIsIris) {
define(standardDefines, "IS_IRIS");
}
define(standardDefines, "ANGELICA_VERSION", makeAngelicaVersion());
define(standardDefines, "MC_HAND_DEPTH", Float.toString(HandRenderer.DEPTH));
@@ -0,0 +1,18 @@
package net.coderbot.iris.gl.state;
public enum FogMode {
/**
* Fog is disabled.
*/
OFF,
/**
* Per-vertex fog, applicable to most geometry.
*/
PER_VERTEX,
/**
* Per-fragment fog, for extra-long geometry like beacon beams.
*/
PER_FRAGMENT
}
@@ -1,5 +1,6 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.GlVersion;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
@@ -105,4 +106,29 @@ public enum InternalTextureFormat {
public GlVersion getMinimumGlVersion() {
return minimumGlVersion;
}
public InternalTextureFormat getColorRenderableFallback() {
if (!RenderSystem.supportsSnormFormats()) {
return switch (this) {
case R8_SNORM, RG8_SNORM, RGB8_SNORM, RGBA8_SNORM -> RGBA16F;
case R16_SNORM, RG16_SNORM, RGB16_SNORM, RGBA16_SNORM -> RGBA16F;
default -> this.getPackedFloatFallback();
};
}
return this.getPackedFloatFallback();
}
private InternalTextureFormat getPackedFloatFallback() {
if (!RenderSystem.supportsPackedFloatRenderable()) {
return switch (this) {
case R11F_G11F_B10F, RGB9_E5 -> RGBA16F;
case RGB8 -> RGBA8;
case RGB16 -> RGBA16;
case RGB16F -> RGBA16F;
case RGB32F -> RGBA32F;
default -> this;
};
}
return this;
}
}
@@ -1,5 +1,6 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.minecraft.client.Minecraft;
import org.joml.Vector4f;
@@ -24,7 +25,7 @@ public class ClearPass {
}
public void execute(Vector4f defaultClearColor) {
GL11.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt());
GLStateManager.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt());
framebuffer.bind();
Vector4f color = Objects.requireNonNull(defaultClearColor);
@@ -86,7 +86,7 @@ public class ClearPassCreator {
// Sort buffers by their clear color so we can group up glClear calls.
Map<Vector4f, IntList> clearByColor = new HashMap<>();
for (int i = 0; i < renderTargetDirectives.getColorSamplingSettings().size(); i++) {
for (int i = 0; i < Math.min(renderTargetDirectives.getColorSamplingSettings().size(), renderTargets.getNumColorTextures()); i++) {
// unboxed
PackShadowDirectives.SamplingSettings settings = renderTargetDirectives.getColorSamplingSettings().get(i);
@@ -9,15 +9,13 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder;
import net.coderbot.iris.gl.buffer.ShaderStorageInfo;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.image.ImageInformation;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.ProgramTable;
import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition;
@@ -26,14 +24,20 @@ import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.gl.blending.AlphaTestOverride;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.blending.BufferBlendOverride;
import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder;
import net.coderbot.iris.gl.buffer.ShaderStorageInfo;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.image.ImageInformation;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import net.coderbot.iris.postprocess.BufferFlipper;
@@ -48,7 +52,6 @@ import net.coderbot.iris.samplers.IrisImages;
import net.coderbot.iris.samplers.IrisSamplers;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.ComputeSource;
import net.coderbot.iris.shaderpack.IdMap;
import net.coderbot.iris.shaderpack.OptionalBoolean;
import net.coderbot.iris.shaderpack.PackDirectives;
import net.coderbot.iris.shaderpack.PackShadowDirectives;
@@ -58,6 +61,7 @@ import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shaderpack.loading.ProgramId;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.shadows.ShadowCompositeRenderer;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.texture.format.TextureFormat;
import net.coderbot.iris.texture.format.TextureFormatLoader;
@@ -80,6 +84,7 @@ import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.util.ArrayList;
import java.util.Collections;
@@ -117,10 +122,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private ImmutableList<ClearPass> shadowClearPasses;
private ImmutableList<ClearPass> shadowClearPassesFull;
private final ComputeProgram[] setup;
private final CompositeRenderer beginRenderer;
private final CompositeRenderer prepareRenderer;
@Nullable
private final ShadowRenderer shadowRenderer;
@Nullable
private final ShadowCompositeRenderer shadowCompositeRenderer;
private final CustomUniforms customUniforms;
@@ -156,6 +165,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final boolean shouldRenderVignette;
private final boolean shouldRenderSun;
private final boolean shouldRenderMoon;
private final boolean shouldRenderStars;
private final boolean shouldRenderSkyDisc;
private final boolean shouldRenderWeather;
private final boolean shouldRenderWeatherParticles;
private final boolean shouldWriteRainAndSnowToDepthBuffer;
private final boolean shouldRenderParticlesBeforeDeferred;
private final boolean shouldRenderPrepareBeforeShadow;
@@ -176,6 +189,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private int currentNormalTexture;
private int currentSpecularTexture;
private PackDirectives packDirectives;
private final Set<FeatureFlags> activeFeatures;
public DeferredWorldRenderingPipeline(ProgramSet programs) {
Objects.requireNonNull(programs);
@@ -207,6 +221,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shouldRenderVignette = programs.getPackDirectives().vignette();
this.shouldRenderSun = programs.getPackDirectives().shouldRenderSun();
this.shouldRenderMoon = programs.getPackDirectives().shouldRenderMoon();
this.shouldRenderStars = programs.getPackDirectives().shouldRenderStars();
this.shouldRenderSkyDisc = programs.getPackDirectives().shouldRenderSkyDisc();
this.shouldRenderWeather = programs.getPackDirectives().shouldRenderWeather();
this.shouldRenderWeatherParticles = programs.getPackDirectives().shouldRenderWeatherParticles();
this.shouldWriteRainAndSnowToDepthBuffer = programs.getPackDirectives().rainDepth();
this.shouldRenderParticlesBeforeDeferred = programs.getPackDirectives().getParticleRenderingSettings()
.map(s -> s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.BEFORE || s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.MIXED)
@@ -217,6 +235,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.updateNotifier = new FrameUpdateNotifier();
this.packDirectives = programs.getPackDirectives();
this.activeFeatures = programs.getPack().getActiveFeatures();
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
@@ -304,8 +323,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
this.flippedBeforeShadow = ImmutableSet.of();
BufferFlipper flipper = new BufferFlipper();
this.centerDepthSampler = new CenterDepthSampler(() -> getRenderTargets().getDepthTexture(), programs.getPackDirectives().getCenterDepthHalfLife());
@@ -314,7 +331,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shadowTargetsSupplier = () -> {
if (shadowRenderTargets == null) {
this.shadowRenderTargets = new ShadowRenderTargets(shadowMapResolution, shadowDirectives);
this.shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives);
}
return shadowRenderTargets;
@@ -322,18 +339,26 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
PatchedShaderPrinter.resetPrintState();
final ProgramBuildContext beginBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.BEGIN), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext prepareBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare");
this.setup = createSetupComputes(programs.getSetup());
this.beginRenderer = new CompositeRenderer(programs.getBegin(), programs.getBeginCompute(), flipper, beginBuildContext, programs.getPackDirectives().getExplicitFlips("begin_pre"), null, "begin", TextureStage.BEGIN);
this.flippedBeforeShadow = flipper.snapshot();
this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare", TextureStage.PREPARE);
flippedAfterPrepare = flipper.snapshot();
this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred");
this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred", TextureStage.DEFERRED);
flippedAfterTranslucent = flipper.snapshot();
this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite");
this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite", TextureStage.COMPOSITE_AND_FINAL);
this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final");
// [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)]
@@ -423,16 +448,24 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
});
});
if (shadowRenderTargets == null && shadowDirectives.isShadowEnabled() == OptionalBoolean.TRUE) {
shadowRenderTargets = new ShadowRenderTargets(shadowMapResolution, shadowDirectives);
shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives);
}
if (shadowRenderTargets != null) {
this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives);
this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives);
this.shadowCompositeRenderer = new ShadowCompositeRenderer(this, programs.getPackDirectives(),
programs.getShadowComposite(), programs.getShadowCompCompute(), this.shadowRenderTargets,
ssboHolder,
customTextureManager.getNoiseTexture(), updateNotifier,
customTextureManager.getCustomTextureIdMap(TextureStage.SHADOWCOMP),
customImages, programs.getPackDirectives().getExplicitFlips("shadowcomp_pre"),
customTextureManager.getIrisCustomTextures(), customUniforms);
if (programs.getPackDirectives().getShadowDirectives().isShadowEnabled().orElse(true)) {
this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null),
programs.getPackDirectives(), shadowRenderTargets);
programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer);
Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram();
shadowRenderer.setUsesImages(shadowProgram != null && shadowProgram.getActiveImages() > 0);
} else {
@@ -441,6 +474,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
} else {
this.shadowClearPasses = ImmutableList.of();
this.shadowClearPassesFull = ImmutableList.of();
this.shadowCompositeRenderer = null;
this.shadowRenderer = null;
}
@@ -449,6 +483,25 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, programs.getPackDirectives().getRenderTargetDirectives());
this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, programs.getPackDirectives().getRenderTargetDirectives());
boolean hasSetup = false;
for (ComputeProgram program : setup) {
if (program != null) {
if (!hasSetup) {
hasSetup = true;
renderTargets.onFullClear();
final Vector4f fogColor = new Vector4f(1.0F, 1.0F, 1.0F, 1.0F);
clearPassesFull.forEach(clearPass -> clearPass.execute(fogColor));
}
program.use();
customUniforms.push(program);
program.dispatch(1, 1);
}
}
if (hasSetup) {
ComputeProgram.unbind();
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
// Terrain pipeline sampler/image factory setup follows.
Supplier<ImmutableSet<Integer>> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
@@ -586,6 +639,26 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return shouldRenderMoon;
}
@Override
public boolean shouldRenderStars() {
return shouldRenderStars;
}
@Override
public boolean shouldRenderSkyDisc() {
return shouldRenderSkyDisc;
}
@Override
public boolean shouldRenderWeather() {
return shouldRenderWeather;
}
@Override
public boolean shouldRenderWeatherParticles() {
return shouldRenderWeatherParticles;
}
@Override
public boolean shouldWriteRainAndSnowToDepthBuffer() {
return shouldWriteRainAndSnowToDepthBuffer;
@@ -606,6 +679,16 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return sunPathRotation;
}
@Override
public boolean hasFeature(FeatureFlags flag) {
return activeFeatures.contains(flag);
}
@Override
public Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap() {
return packDirectives.getTextureMap();
}
private RenderCondition getCondition(WorldRenderingPhase phase) {
if (isRenderingShadow) {
return RenderCondition.SHADOW;
@@ -704,17 +787,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
transformed = TransformPatcher.patchAttributes(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new),
availability);
}
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment);
ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment,
IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
return createPassInner(builder, source.getDirectives(), availability, shadow, id);
@@ -722,7 +809,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) {
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -868,10 +955,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
if (shadowViewport) {
GL11.glViewport(0, 0, shadowMapResolution, shadowMapResolution);
GLStateManager.glViewport(0, 0, shadowMapResolution, shadowMapResolution);
} else {
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
GL11.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight);
GLStateManager.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight);
}
if (program != null) {
@@ -931,12 +1018,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
// Destroy the composite rendering pipeline
//
// This destroys all the loaded composite programs as well.
beginRenderer.destroy();
prepareRenderer.destroy();
compositeRenderer.destroy();
deferredRenderer.destroy();
finalPassRenderer.destroy();
centerDepthSampler.destroy();
// Destroy setup compute programs
if (setup != null) {
for (ComputeProgram compute : setup) {
if (compute != null) {
compute.destroy();
}
}
}
// Destroy shadow compute programs
if (shadowComputes != null) {
for (ComputeProgram compute : shadowComputes) {
@@ -946,6 +1043,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
// Destroy shadow composite renderer
if (shadowCompositeRenderer != null) {
shadowCompositeRenderer.destroy();
}
horizonRenderer.destroy();
// Make sure that any custom framebuffers are not bound before destroying render targets
@@ -1054,6 +1156,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
main.framebufferHeight, depthBufferFormat, packDirectives);
if (changed) {
beginRenderer.recalculateSizes();
prepareRenderer.recalculateSizes();
deferredRenderer.recalculateSizes();
compositeRenderer.recalculateSizes();
@@ -1074,6 +1177,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
if (ssboHolder != null) {
ssboHolder.hasResizedScreen(main.framebufferWidth, main.framebufferHeight);
}
// Re-run setup computes after resize (SETUP dispatches with 1,1 workgroups)
boolean ranSetup = false;
for (ComputeProgram program : setup) {
if (program != null) {
ranSetup = true;
program.use();
customUniforms.push(program);
program.dispatch(1, 1);
}
}
if (ranSetup) {
ComputeProgram.unbind();
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
}
final ImmutableList<ClearPass> passes;
@@ -1109,13 +1227,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.GBUFFERS_AND_SHADOW, getTextureMap());
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
}
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -1158,6 +1278,60 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return programs;
}
private ComputeProgram[] createSetupComputes(ComputeSource[] compute) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
for (int i = 0; i < programs.length; i++) {
ComputeSource source = compute[i];
if (source == null || !source.getSource().isPresent()) {
continue;
} else {
ProgramBuilder builder;
try {
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SETUP, getTextureMap());
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
throw new RuntimeException("Shader compilation failed for setup compute " + source.getName() + "!", e);
}
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
ImmutableSet<Integer> empty = ImmutableSet.of();
Supplier<ImmutableSet<Integer>> flipped = () -> empty;
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor =
ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.SETUP));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, true, this);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
if (shadowRenderTargets != null) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true);
IrisImages.addShadowColorImages(builder, shadowRenderTargets, null);
}
}
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups(), null);
}
}
return programs;
}
@Override
public void beginHand() {
// We need to copy the current depth texture so that depthtex2 can contain the depth values for
@@ -1280,6 +1454,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
image.clear();
}
isRenderingFullScreenPass = true;
beginRenderer.renderAll();
isRenderingFullScreenPass = false;
setPhase(WorldRenderingPhase.SKY);
// Render our horizon box before actual sky rendering to avoid being broken by mods that do weird things
@@ -1413,7 +1591,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP };
private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElse(null)));
}
private static Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> submitCompositeTransforms(ProgramSource[] sources) {
@@ -1441,7 +1619,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
processedSourceNames.add(source.getName());
for (InputAvailability avail : INPUT_AVAILABILITIES) {
Pair<String, InputAvailability> key = Pair.of(source.getName(), avail);
futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null), avail)));
futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElse(null), avail)));
}
}
}
@@ -1,13 +1,19 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMaps;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
@@ -166,6 +172,26 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
return true;
}
@Override
public boolean shouldRenderStars() {
return true;
}
@Override
public boolean shouldRenderSkyDisc() {
return true;
}
@Override
public boolean shouldRenderWeather() {
return true;
}
@Override
public boolean shouldRenderWeatherParticles() {
return true;
}
@Override
public boolean shouldWriteRainAndSnowToDepthBuffer() {
return false;
@@ -186,4 +212,14 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
// No sun tilt
return 0;
}
@Override
public boolean hasFeature(FeatureFlags flag) {
return false;
}
@Override
public Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap() {
return Object2ObjectMaps.emptyMap();
}
}
@@ -1,8 +1,10 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import net.minecraft.client.Minecraft;
@@ -42,7 +44,7 @@ public class HorizonRenderer {
* Sine of 22.5 degrees.
*/
private static final double SIN_22_5 = Math.sin(Math.toRadians(22.5));
private VertexBuffer vertexBuffer;
private IVertexArrayObject vao;
private int currentRenderDistance;
public HorizonRenderer() {
@@ -52,13 +54,17 @@ public class HorizonRenderer {
}
private void rebuildBuffer() {
final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet();
if (this.vao != null) {
this.vao.delete();
}
final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(DefaultVertexFormat.POSITION);
// Build the horizon quads into a buffer
tessellator.startDrawingQuads(); //(GL11.GL_QUADS, DefaultVertexFormat.POSITION);
buildHorizon(currentRenderDistance * 16, tessellator);
this.vertexBuffer = TessellatorManager.stopCapturingToVAO(vertexBuffer, DefaultVertexFormat.POSITION);
this.vao = DirectTessellator.stopCapturingToVBO(VertexBufferType.IMMUTABLE);
}
private void buildQuad(Tessellator consumer, double x1, double z1, double x2, double z2) {
@@ -145,18 +151,24 @@ public class HorizonRenderer {
buildBottomPlane(consumer, 384);
}
public void renderHorizon(FloatBuffer floatBuffer) {
public void renderHorizon(FloatBuffer matrix) {
if (currentRenderDistance != Minecraft.getMinecraft().gameSettings.renderDistanceChunks) {
currentRenderDistance = Minecraft.getMinecraft().gameSettings.renderDistanceChunks;
rebuildBuffer();
}
vertexBuffer.setupState();
vertexBuffer.draw(floatBuffer);
vertexBuffer.cleanupState();
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glMultMatrix(matrix);
vao.bind();
vao.draw();
vao.unbind();
GL11.glPopMatrix();
}
public void destroy() {
vertexBuffer.close();
vao.delete();
}
}
@@ -27,6 +27,18 @@ public class PatchedShaderPrinter {
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String fragment) {
debugPatchedShaders(name, vertex, geometry, null, null, fragment, null);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment) {
debugPatchedShaders(name, vertex, geometry, tessControl, tessEval, fragment, null);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String fragment, String compute) {
debugPatchedShaders(name, vertex, geometry, null, null, fragment, compute);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, String compute) {
if (prettyPrintShaders) {
final Path debugOutDir = Minecraft.getMinecraft().mcDataDir.toPath().resolve("patched_shaders");
if (!outputLocationCleared) {
@@ -59,9 +71,18 @@ public class PatchedShaderPrinter {
if (geometry != null) {
Files.write(debugOutDir.resolve(prefix + name + ".gsh"), geometry.getBytes(StandardCharsets.UTF_8));
}
if (tessControl != null) {
Files.write(debugOutDir.resolve(prefix + name + ".tcs"), tessControl.getBytes(StandardCharsets.UTF_8));
}
if (tessEval != null) {
Files.write(debugOutDir.resolve(prefix + name + ".tes"), tessEval.getBytes(StandardCharsets.UTF_8));
}
if (fragment != null) {
Files.write(debugOutDir.resolve(prefix + name + ".fsh"), fragment.getBytes(StandardCharsets.UTF_8));
}
if (compute != null) {
Files.write(debugOutDir.resolve(prefix + name + ".csh"), compute.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
Iris.logger.warn("Failed to write debug patched shader source", e);
}
@@ -23,11 +23,13 @@ import net.coderbot.iris.shaderpack.PackShadowDirectives;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shadow.ShadowMatrices;
import net.coderbot.iris.shadows.CullingDataCache;
import net.coderbot.iris.shadows.ShadowCompositeRenderer;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.coderbot.iris.shadows.frustum.CullEverythingFrustum;
import net.coderbot.iris.shadows.frustum.FrustumHolder;
import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum;
import net.coderbot.iris.shadows.frustum.advanced.SafeZoneCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum;
import net.coderbot.iris.uniforms.CameraUniforms;
@@ -72,6 +74,7 @@ public class ShadowRenderer {
public static ShadowRenderTargets CURRENT_TARGETS = null;
private final float halfPlaneLength;
private final float voxelDistance;
private final float renderDistanceMultiplier;
private final float entityShadowDistanceMultiplier;
private final int resolution;
@@ -79,6 +82,7 @@ public class ShadowRenderer {
private final Float fov;
private final ShadowRenderTargets targets;
private final ShadowCullState packCullingState;
private final ShadowCompositeRenderer compositeRenderer;
private boolean packHasVoxelization;
private final boolean shouldRenderTerrain;
private final boolean shouldRenderTranslucent;
@@ -108,13 +112,14 @@ public class ShadowRenderer {
private double lastAdvancedBoxCullerDistance = -1;
private double lastTileEntityCullerDistance = -1;
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets) {
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer) {
this.profiler = Minecraft.getMinecraft().mcProfiler;
final PackShadowDirectives shadowDirectives = directives.getShadowDirectives();
this.halfPlaneLength = shadowDirectives.getDistance();
this.voxelDistance = shadowDirectives.getVoxelDistance();
this.renderDistanceMultiplier = shadowDirectives.getDistanceRenderMul();
this.entityShadowDistanceMultiplier = shadowDirectives.getEntityShadowDistanceMul();
this.resolution = shadowDirectives.getResolution();
@@ -125,6 +130,8 @@ public class ShadowRenderer {
this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer();
this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities();
this.compositeRenderer = compositeRenderer;
debugStringOverall = "half plane = " + halfPlaneLength + " meters @ " + resolution + "x" + resolution;
this.terrainFrustumHolder = new FrustumHolder();
@@ -221,7 +228,8 @@ public class ShadowRenderer {
configureDepthSampler(targets.getDepthTextureNoTranslucents().getTextureId(), depthSamplingSettings.get(1));
for (int i = 0; i < colorSamplingSettings.size(); i++) {
for (int i = 0; i < Math.min(colorSamplingSettings.size(), targets.getNumColorTextures()); i++) {
if (targets.get(i) == null) continue;
int glTextureId = targets.get(i).getMainTexture();
configureSampler(glTextureId, colorSamplingSettings.get(i));
@@ -282,7 +290,7 @@ public class ShadowRenderer {
// TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected.
String distanceInfo;
String cullingInfo;
if ((packCullingState == ShadowCullState.DISTANCE || packHasVoxelization) && packCullingState != ShadowCullState.ADVANCED) {
if ((packCullingState == ShadowCullState.DISTANCE || packHasVoxelization) && packCullingState != ShadowCullState.ADVANCED && packCullingState != ShadowCullState.SAFE_ZONE) {
double distance = halfPlaneLength * renderMultiplier;
String reason;
@@ -304,26 +312,29 @@ public class ShadowRenderer {
holder.setInfo(getOrCreateBoxCullingFrustum(distance), distanceInfo, cullingInfo);
}
} else {
final BoxCuller boxCuller;
BoxCuller boxCuller;
double distance = halfPlaneLength * renderMultiplier;
boolean hasSafeZone = packCullingState == ShadowCullState.SAFE_ZONE;
if (hasSafeZone && renderMultiplier < 0) renderMultiplier = 1.0f;
double distance = (hasSafeZone ? voxelDistance : halfPlaneLength) * renderMultiplier;
String setter = "(set by shader pack)";
if (renderMultiplier < 0) {
// TODO: GUI
distance = IrisVideoSettings.shadowDistance * 16; // can be zero :(
//distance = 32 * 16;
setter = "(set by user)";
}
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) {
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16 && !hasSafeZone) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
boxCuller = null;
} else {
distanceInfo = distance + " blocks " + setter;
if (distance == 0.0) {
if (distance == 0.0 && !hasSafeZone) {
cullingInfo = "no shadows rendered";
return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo);
}
@@ -331,15 +342,22 @@ public class ShadowRenderer {
boxCuller = getOrCreateAdvancedBoxCuller(distance);
}
cullingInfo = "Advanced Frustum Culling enabled";
cullingInfo = (hasSafeZone ? "Safe Zone" : "Advanced") + " Frustum Culling enabled";
final Vector4f shadowLightPosition = celestialUniforms.getShadowLightPositionInWorldSpace();
shadowLightVectorCache.set(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorCache.normalize();
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
if (hasSafeZone) {
BoxCuller distanceCuller = new BoxCuller(halfPlaneLength * renderMultiplier);
SafeZoneCullingFrustum safeZoneFrustum = new SafeZoneCullingFrustum(
RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(),
shadowLightVectorCache, boxCuller, distanceCuller);
return holder.setInfo(safeZoneFrustum, distanceInfo, cullingInfo);
} else {
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
}
}
return holder;
@@ -382,7 +400,7 @@ public class ShadowRenderer {
private void setupGlState(Matrix4f projMatrix) {
// Bind shadow framebuffer and set viewport to shadow resolution
targets.getDepthSourceFb().bind();
GL11.glViewport(0, 0, resolution, resolution);
GLStateManager.glViewport(0, 0, resolution, resolution);
// Set up our projection matrix and load it into the legacy matrix stack
RenderSystem.setupProjectionMatrix(projMatrix);
@@ -407,7 +425,7 @@ public class ShadowRenderer {
// Restore main framebuffer and viewport
Minecraft mc = Minecraft.getMinecraft();
mc.getFramebuffer().bindFramebuffer(false);
GL11.glViewport(0, 0, mc.displayWidth, mc.displayHeight);
GLStateManager.glViewport(0, 0, mc.displayWidth, mc.displayHeight);
}
private void copyPreTranslucentDepth() {
@@ -675,7 +693,7 @@ public class ShadowRenderer {
}
// Reset viewport in case terrain rendering changed it
GL11.glViewport(0, 0, resolution, resolution);
GLStateManager.glViewport(0, 0, resolution, resolution);
profiler.endStartSection("entities");
@@ -750,6 +768,10 @@ public class ShadowRenderer {
((CullingDataCache) levelRenderer).restoreState();
}
profiler.endStartSection("shadowcomp");
if (compositeRenderer != null) compositeRenderer.renderAll();
ACTIVE = false;
CURRENT_TARGETS = null;
profiler.endSection();
@@ -1,12 +1,17 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.renderer.EntityRenderer;
@@ -49,9 +54,16 @@ public interface WorldRenderingPipeline {
boolean shouldRenderVignette();
boolean shouldRenderSun();
boolean shouldRenderMoon();
boolean shouldRenderStars();
boolean shouldRenderSkyDisc();
boolean shouldRenderWeather();
boolean shouldRenderWeatherParticles();
boolean shouldWriteRainAndSnowToDepthBuffer();
boolean shouldRenderParticlesBeforeDeferred();
boolean allowConcurrentCompute();
float getSunPathRotation();
boolean hasFeature(FeatureFlags flag);
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap();
}
@@ -14,8 +14,16 @@ import java.util.Map;
class AttributeTransformer {
public static void transform(Transformer transformer, AttributeParameters parameters, String profile, int version) {
boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility"));
// Common patches (compatibility profile)
CommonTransformer.transform(transformer, parameters, isCore, version);
// Entity ID and overlay color patching (uniform path)
EntityPatcher.patchEntityId(transformer, parameters);
EntityPatcher.patchOverlayColor(transformer, parameters);
if (isCore) {
if (parameters.type == PatchShaderType.VERTEX) {
if (parameters.type == ShaderType.VERTEX) {
throw new IllegalStateException("Vertex shaders must be in the compatibility profile to run properly!");
}
return;
@@ -28,66 +36,49 @@ class AttributeTransformer {
transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1");
}
Map<String, String> texCoordReplacements = new HashMap<>();
if (!parameters.inputs.lightmap) {
texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
}
if (!parameters.inputs.texture) {
texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
}
texCoordReplacements.forEach(transformer::replaceExpression);
Map<String, String> texCoordReplacements = new HashMap<>();
if (!parameters.inputs.lightmap) {
texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
}
if (!parameters.inputs.texture) {
texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
}
texCoordReplacements.forEach(transformer::replaceExpression);
patchTextureMatrices(transformer, parameters.inputs.lightmap);
if (parameters.type.glShaderType == ShaderType.VERTEX
&& transformer.hasVariable("gl_MultiTexCoord3")
&& !transformer.hasVariable("mc_midTexCoord")) {
// TODO: proper type conversion
// gl_MultiTexCoord3 is a super legacy alias of mc_midTexCoord. We don't do this
// replacement if we think mc_midTexCoord could be defined just we can't handle
// an existing declaration robustly. But basically the proper way to do this is
// to define mc_midTexCoord only if it's not defined, and if it is defined,
// figure out its type, then replace all occurrences of gl_MultiTexCoord3 with
// the correct conversion from mc_midTexCoord's declared type to vec4.
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
if (parameters.type == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
private static void patchTextureMatrices(Transformer transformer, boolean hasLightmap) {
transformer.rename("gl_TextureMatrix", "iris_TextureMatrix");
transformer.rename("gl_TextureMatrix", "iris_TextureMatrix");
// TODO: These were originally marked const, but that breaks things
// If these are marked const, then using them below in the iris_LightmapTextureMatrix creation
// breaks with them being undefined. I suppose the const variables cause them to get defined later than otherwise?
// Similarly, if you make them a const, then iris_ONE_OVER_32 breaks because it references iris_ONE_OVER_256.
// Not sure if it really matters if these are marked const or not. Alternatively they can be marked const
// and the values hardcoded within the places that use them here, that seems to work fine, but this probably
// stayed closer to the original way it worked.
transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;");
transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;");
transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
if (hasLightmap) {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
} else {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" +
"mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," +
" 0.0, iris_ONE_OVER_256, 0.0, 0.0," +
" 0.0, 0.0, iris_ONE_OVER_256, 0.0," +
" iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_256);");
}
if (hasLightmap) {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
} else {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" +
"mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," +
" 0.0, iris_ONE_OVER_256, 0.0, 0.0," +
" 0.0, 0.0, iris_ONE_OVER_256, 0.0," +
" iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_256);");
}
// column major
transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" +
"gl_TextureMatrix[0]," +
"iris_LightmapTextureMatrix," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)" +
");");
transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" +
"gl_TextureMatrix[0]," +
"iris_LightmapTextureMatrix," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)" +
");");
}
}
@@ -1,18 +1,17 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.FRAGMENT;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.VERTEX;
class CeleritasTransformer {
public static void transform(Transformer transformer, Parameters parameters) {
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, false, glslVersion);
switch (parameters.type) {
// For Celeritas patching, treat fragment and geometry the same
case FRAGMENT:
case GEOMETRY:
transformFragment(transformer, parameters);
@@ -26,7 +25,7 @@ class CeleritasTransformer {
}
public static void transformVertex(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform vec3 u_RegionOffset;"); // Per-region offset from setRegionOffset()
transformer.injectVariable("uniform vec3 u_RegionOffset;");
transformer.injectVariable("vec4 iris_LightTexCoord;");
transformer.injectFunction("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * _celeritas_getVertexPosition(); }");
transformer.injectFunction(
@@ -57,7 +56,6 @@ class CeleritasTransformer {
}
public static void transformFragment(Transformer transformer, Parameters parameters) {
// interestingly there is nothing that isn't shared
transformShared(transformer, parameters);
}
@@ -82,31 +80,5 @@ class CeleritasTransformer {
sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
sharedReplacements.put("gl_ModelViewProjectionMatrix", "(iris_ProjectionMatrix * iris_ModelViewMatrix)");
sharedReplacements.forEach(transformer::replaceExpression);
transformFog(transformer, parameters);
}
private static void transformFog(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform float iris_FogDensity;");
transformer.injectVariable("uniform float iris_FogStart;");
transformer.injectVariable("uniform float iris_FogEnd;");
transformer.injectVariable("uniform vec4 iris_FogColor;");
transformer.injectFunction("struct iris_FogParameters { vec4 color; float density; float start; float end; float scale; };");
transformer.injectFunction(
"iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, " +
"iris_FogStart, iris_FogEnd, 1.0 / (iris_FogEnd - iris_FogStart));");
final Map<String, String> fogRenames = new HashMap<>();
fogRenames.put("gl_Fog", "iris_Fog");
fogRenames.put("gl_FogFragCoord", "iris_FogFragCoord");
transformer.rename(fogRenames);
if (parameters.type == VERTEX) {
transformer.injectVariable("out float iris_FogFragCoord;");
transformer.prependMain("iris_FogFragCoord = 0.0;");
} else if (parameters.type == FRAGMENT) {
transformer.injectVariable("in float iris_FogFragCoord;");
}
}
}
@@ -0,0 +1,80 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.Map;
public class CommonTransformer {
private static final Map<String, String> COMMON_TEXTURE_RENAMES = Map.ofEntries(
Map.entry("texture2D", "texture"),
Map.entry("texture3D", "texture"),
Map.entry("texture2DLod", "textureLod"),
Map.entry("texture3DLod", "textureLod"),
Map.entry("texture2DProj", "textureProj"),
Map.entry("texture3DProj", "textureProj"),
Map.entry("texture2DGrad", "textureGrad"),
Map.entry("texture2DGradARB", "textureGrad"),
Map.entry("texture3DGrad", "textureGrad"),
Map.entry("texelFetch2D", "texelFetch"),
Map.entry("texelFetch3D", "texelFetch"),
Map.entry("textureSize2D", "textureSize")
);
public static void transform(Transformer root, Parameters parameters, boolean core, int glslVersion) {
root.rename("gl_FogFragCoord", "iris_FogFragCoord");
if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("out float iris_FogFragCoord;");
root.prependMain("iris_FogFragCoord = 0.0f;");
} else if (parameters.type == ShaderType.FRAGMENT) {
root.injectVariable("in float iris_FogFragCoord;");
}
if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("vec4 iris_FrontColor;");
root.rename("gl_FrontColor", "iris_FrontColor");
}
if (parameters.type == ShaderType.FRAGMENT) {
if (root.containsCall("gl_FragColor")) {
root.replaceExpression("gl_FragColor", "gl_FragData[0]");
}
// Note: In compatibility profile, gl_FragData is a built-in array.
if (!core && parameters.getAlphaTest() != AlphaTest.ALWAYS) {
root.injectVariable("uniform float iris_currentAlphaTest;");
root.appendMain(parameters.getAlphaTest().toExpression("gl_FragData[0].a", "iris_currentAlphaTest", ""));
}
}
if (root.containsCall("texture") && root.hasVariable("texture")) {
root.rename("texture", "gtexture");
}
if (root.hasVariable("iris_renamed_texture")) {
root.rename("iris_renamed_texture", "gtexture");
}
if (root.containsCall("gcolor") && root.hasVariable("gcolor")) {
root.rename("gcolor", "gtexture");
}
root.rename("gl_Fog", "iris_Fog");
root.injectVariable("uniform float iris_FogDensity;");
root.injectVariable("uniform float iris_FogStart;");
root.injectVariable("uniform float iris_FogEnd;");
root.injectVariable("uniform vec4 iris_FogColor;");
root.injectFunction("struct iris_FogParameters {vec4 color;float density;float start;float end;float scale;};");
root.injectFunction("iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, iris_FogStart, iris_FogEnd, 1.0f / (iris_FogEnd - iris_FogStart));");
// GLSL 120 natively uses texture2D/shadow2D etc. Ttexture/textureLod don't exist in 120, so only rename for versions that support them.
if (glslVersion > 120) {
root.renameFunctionCall(COMMON_TEXTURE_RENAMES);
root.renameAndWrapShadow("shadow2D", "texture");
root.renameAndWrapShadow("shadow2DLod", "textureLod");
}
}
}
@@ -15,8 +15,7 @@ public class CompatibilityTransformer {
public static void transformEach(Transformer transformer, Parameters parameters) {
if (parameters.type == PatchShaderType.VERTEX) {
;
if (parameters.type == ShaderType.VERTEX) {
// TODO: sildur's jankness
// This is a hacky patch for sildur's shaders that changes the way it does it's waving water to make it work better?
// Why is this the GLSL transformation code in Iris, tell sildur to fix it and remove this?
@@ -1,15 +1,17 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
class CompositeDepthTransformer {
public static void transform(Transformer transformer) {
// replace original declaration
int type = transformer.findType("centerDepthSmooth");
if (type != 0) {
transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;");
transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
}
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, false, glslVersion);
int type = transformer.findType("centerDepthSmooth");
if (type != 0) {
transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;");
transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
}
}
}
@@ -0,0 +1,11 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
public class ComputeTransformer {
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, true, glslVersion);
}
}
@@ -0,0 +1,23 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
class EntityPatcher {
public static void patchEntityId(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
}
public static void patchOverlayColor(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
}
private static void injectUniformIfUndeclared(Transformer transformer, String name, String declaration) {
if (transformer.containsCall(name) && !transformer.hasVariable(name)) {
transformer.injectVariable(declaration);
}
}
}
@@ -3,5 +3,6 @@ package net.coderbot.iris.pipeline.transform;
public enum Patch {
ATTRIBUTES,
CELERITAS_TERRAIN,
COMPOSITE
COMPOSITE,
COMPUTE
}
@@ -5,7 +5,10 @@ import net.coderbot.iris.gl.shader.ShaderType;
public enum PatchShaderType {
VERTEX(ShaderType.VERTEX),
GEOMETRY(ShaderType.GEOMETRY),
FRAGMENT(ShaderType.FRAGMENT);
TESS_CONTROL(ShaderType.TESSELATION_CONTROL),
TESS_EVAL(ShaderType.TESSELATION_EVAL),
FRAGMENT(ShaderType.FRAGMENT),
COMPUTE(ShaderType.COMPUTE);
public static final PatchShaderType[] VALUES = values();
@@ -19,8 +22,10 @@ public enum PatchShaderType {
return switch (glShaderType) {
case VERTEX -> new PatchShaderType[] { VERTEX };
case GEOMETRY -> new PatchShaderType[] { GEOMETRY };
case TESSELATION_CONTROL -> new PatchShaderType[] { TESS_CONTROL };
case TESSELATION_EVAL -> new PatchShaderType[] { TESS_EVAL };
case FRAGMENT -> new PatchShaderType[] { FRAGMENT };
default -> throw new IllegalArgumentException("Unknown shader type: " + glShaderType);
case COMPUTE -> new PatchShaderType[] { COMPUTE };
};
}
}
@@ -9,58 +9,71 @@ import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.StorageCollector;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShaderTransformer {
private static final Pattern versionPattern = Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?");
private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^\\s*(in|out)(\\s+)");
private static final Pattern inPattern = Pattern.compile("(?m)^\\s*(in)(\\s+)");
private static final Pattern outPattern = Pattern.compile("(?m)^\\s*(out)(\\s+)");
private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in|out)(\\s+)");
private static final Pattern inPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in)(\\s+)");
private static final Pattern outPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(out)(\\s+)");
private static final Pattern texturePattern = Pattern.compile("\\btexture\\s*\\(|(\\btexture\\b)");
private static final Pattern unsignedSuffixPattern = Pattern.compile("(\\b(?:\\d+|0[xX][0-9a-fA-F]+))[uU]\\b");
private static final int CACHE_SIZE = 100;
private static final Object2ObjectLinkedOpenHashMap<TransformKey<?>, Map<PatchShaderType, String>> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>();
private static final boolean useCache = true;
// Track logged negotiations to avoid spam - cleared on shader pack reload
private static final Set<String> loggedNegotiations = new HashSet<>();
public static void clearCache() {
synchronized (shaderTransformationCache) {
shaderTransformationCache.clear();
}
loggedNegotiations.clear();
}
/**
* These are words which need to be renamed by iris if a shader uses them, regardless o the GLSL version.
* The words will get caught and renamed to iris_renamed_$WORD
*/
private static final List<String> fullReservedWords = new ArrayList<>();
/**
* This does the same thing as fullReservedWords, but based on a maximum GLSL version. As an example
* if something was register to 400 here, it would get applied on any version below 400.
*/
private static final Map<Integer, List<String>> versionedReservedWords = new HashMap<>();
static {
// texture seems to be reserved by some drivers but not others, however this is not actually reserved by the GLSL spec
fullReservedWords.add("texture");
private static String replaceTexture(String input) {
final var matcher = texturePattern.matcher(input);
final StringBuilder builder = new StringBuilder();
while (matcher.find()) {
if (matcher.group(1) != null) {
matcher.appendReplacement(builder, "iris_renamed_texture");
} else {
matcher.appendReplacement(builder, Matcher.quoteReplacement(matcher.group(0)));
}
}
matcher.appendTail(builder);
return builder.toString();
}
static {
// sample was added as a keyword in GLSL 400, many shaders use it
versionedReservedWords.put(400, List.of("sample"));
}
@@ -68,14 +81,160 @@ public class ShaderTransformer {
private record VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {}
// Sorted descending by minVersion for early exit in getRequiredVersion
private static final VersionRequirement[] VERSION_REQUIREMENTS = {
new VersionRequirement("std430", 430, RenderSystem::supportsSSBO),
new VersionRequirement("iimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageLoad", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageStore", 420, RenderSystem::supportsImageLoadStore)
new VersionRequirement("imageStore", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uint", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec2", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec3", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec4", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("flat", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
};
private record DowngradeRule(
int fromVersion,
int toVersion,
BooleanSupplier supported,
List<String> extensions,
Map<String, String> defines,
List<String> preprocessorDefines,
boolean convertStorageQualifiers
) {}
private static final DowngradeRule[] DOWNGRADE_RULES = {
new DowngradeRule(130, 120,
RenderSystem::supportsGpuShader4,
List.of("GL_EXT_gpu_shader4"),
Map.of("texture", "texture2D"),
List.of(
// Preprocessor defines
"#define uint int",
"#define uvec2 ivec2",
"#define uvec3 ivec3",
"#define uvec4 ivec4",
"#define isnan(x) ((x) != (x))",
"#define isinf(x) ((x) == (1.0/0.0) || (x) == (-1.0/0.0))",
"#define trunc(x) (sign(x) * floor(abs(x)))",
"#define round(x) (floor((x) + 0.5))",
"#define texelFetch texelFetch2D",
"#define textureSize textureSize2D",
"#define modf iris_modf",
// Function definitions
"GLSL_FUNC:float iris_modf(float x, out float i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec2 iris_modf(vec2 x, out vec2 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec3 iris_modf(vec3 x, out vec3 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec4 iris_modf(vec4 x, out vec4 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec2 mix(vec2 a, vec2 b, bvec2 sel) { return vec2(sel.x ? b.x : a.x, sel.y ? b.y : a.y); }",
"GLSL_FUNC:vec3 mix(vec3 a, vec3 b, bvec3 sel) { return vec3(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z); }",
"GLSL_FUNC:vec4 mix(vec4 a, vec4 b, bvec4 sel) { return vec4(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z, sel.w ? b.w : a.w); }",
"GLSL_FUNC:bool any(bool b) { return b; }",
"GLSL_FUNC:bool all(bool b) { return b; }"
),
true
)
};
record NegotiationResult(
int targetVersion,
String profile,
List<String> extensions,
Map<String, String> defines,
List<String> preprocessorDefines,
boolean convertStorageQualifiers,
String error
) {
static NegotiationResult success(int targetVersion, String profile, List<String> extensions, Map<String, String> defines, List<String> preprocessorDefines, boolean convertStorageQualifiers) {
return new NegotiationResult(targetVersion, profile, extensions, defines, preprocessorDefines, convertStorageQualifiers, null);
}
static NegotiationResult error(String message) {
return new NegotiationResult(-1, "", List.of(), Map.of(), List.of(), false, message);
}
static NegotiationResult noop(int version, String profile) {
return new NegotiationResult(version, profile, List.of(), Map.of(), List.of(), false, null);
}
boolean isError() { return error != null; }
}
private static int getStageMinimumVersion(PatchShaderType stage) {
return switch (stage) {
case COMPUTE -> 330;
case TESS_CONTROL, TESS_EVAL -> 400;
case GEOMETRY -> 150;
default -> 110;
};
}
static NegotiationResult negotiateVersion(int effectiveVersion, PatchShaderType stage) {
final int maxGlsl = RenderSystem.getMaxGlslVersion();
if (effectiveVersion <= maxGlsl) {
if (effectiveVersion <= 120 && RenderSystem.supportsGpuShader4()) {
final String profile = "";
for (DowngradeRule rule : DOWNGRADE_RULES) {
if (rule.fromVersion == 130 && rule.toVersion == 120) {
final List<String> definesOnly = rule.preprocessorDefines.stream().filter(d -> !d.startsWith("GLSL_FUNC:")).toList();
return NegotiationResult.success(effectiveVersion, profile, rule.extensions, rule.defines, definesOnly, true);
}
}
return NegotiationResult.success(effectiveVersion, profile, List.of("GL_EXT_gpu_shader4"), Map.of(), List.of(), true);
}
return NegotiationResult.noop(effectiveVersion, effectiveVersion >= 150 ? "compatibility" : "");
}
final int stageMin = getStageMinimumVersion(stage);
if (maxGlsl < stageMin) {
return NegotiationResult.error("Hardware GLSL " + maxGlsl + " below stage minimum " + stageMin + " for " + stage.name());
}
// Walk downgrade rules from effectiveVersion toward maxGlsl
final List<String> accExtensions = new ArrayList<>();
final Map<String, String> accDefines = new HashMap<>();
final List<String> accPreprocessorDefines = new ArrayList<>();
boolean accConvertQualifiers = false;
int currentVersion = effectiveVersion;
while (currentVersion > maxGlsl) {
DowngradeRule matched = null;
for (DowngradeRule rule : DOWNGRADE_RULES) {
if (rule.fromVersion == currentVersion) {
matched = rule;
break;
}
}
if (matched == null) {
return NegotiationResult.error("No downgrade rule from GLSL " + currentVersion + " (hardware max: " + maxGlsl + ", shader requires: " + effectiveVersion + ")");
}
// Verify rule's required extensions are supported
if (!matched.supported.getAsBoolean()) {
return NegotiationResult.error("Downgrade from " + matched.fromVersion + " to " + matched.toVersion + " requires extensions " + matched.extensions + " which are not supported");
}
accExtensions.addAll(matched.extensions);
accDefines.putAll(matched.defines);
accPreprocessorDefines.addAll(matched.preprocessorDefines);
accConvertQualifiers |= matched.convertStorageQualifiers;
currentVersion = matched.toVersion;
}
if (currentVersion < stageMin) {
return NegotiationResult.error("Downgrade reached GLSL " + currentVersion + " which is below stage minimum " + stageMin + " for " + stage.name());
}
final String profile = currentVersion >= 150 ? "compatibility" : "";
return NegotiationResult.success(currentVersion, profile, accExtensions, accDefines, accPreprocessorDefines, accConvertQualifiers);
}
private static Pattern hoistPattern;
private static Object2IntMap<String> keywordToVersion;
private static int maxSupportedHoistVersion;
@@ -89,7 +248,7 @@ public class ShaderTransformer {
if (req.supported.getAsBoolean()) {
if (!patternBuilder.isEmpty()) patternBuilder.append('|');
patternBuilder.append(Pattern.quote(req.keyword));
patternBuilder.append("\\b").append(Pattern.quote(req.keyword)).append("\\b");
versionMap.put(req.keyword, req.minVersion);
maxVersion = Math.max(maxVersion, req.minVersion);
}
@@ -156,8 +315,8 @@ public class ShaderTransformer {
}
}
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String fragment, P parameters) {
if (vertex == null && geometry == null && fragment == null) {
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, P parameters) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) {
return null;
} else {
Map<PatchShaderType, String> result;
@@ -167,6 +326,8 @@ public class ShaderTransformer {
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class);
inputs.put(PatchShaderType.VERTEX, vertex);
inputs.put(PatchShaderType.GEOMETRY, geometry);
inputs.put(PatchShaderType.TESS_CONTROL, tessControl);
inputs.put(PatchShaderType.TESS_EVAL, tessEval);
inputs.put(PatchShaderType.FRAGMENT, fragment);
var key = new TransformKey<>(patchType, inputs, parameters);
@@ -195,24 +356,142 @@ public class ShaderTransformer {
}
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
List<Transformer> textureLodExtensionPatches = new ArrayList<>();
List<Transformer> hacky120Patches = new ArrayList<>();
public static <P extends Parameters> Map<PatchShaderType, String> transformCompute(String compute, P parameters) {
if (compute == null) {
return null;
} else {
Map<PatchShaderType, String> result;
Stopwatch watch = Stopwatch.createStarted();
final var patchType = parameters.patch;
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class);
inputs.put(PatchShaderType.COMPUTE, compute);
final var key = new TransformKey<>(patchType, inputs, parameters);
synchronized (shaderTransformationCache) {
result = shaderTransformationCache.getAndMoveToLast(key);
}
if (result == null || !useCache) {
result = transformComputeInternal(compute, patchType, parameters);
// Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null;
synchronized (shaderTransformationCache) {
// Double-check in case another thread added it while we were transforming
final Map<PatchShaderType, String> existing = shaderTransformationCache.getAndMoveToLast(key);
if (existing != null) {
return existing;
}
if (shaderTransformationCache.size() >= CACHE_SIZE) {
shaderTransformationCache.removeFirst();
}
shaderTransformationCache.putAndMoveToLast(key, result);
}
}
return result;
}
}
private static <P extends Parameters> Map<PatchShaderType, String> transformComputeInternal(String compute, Patch patchType, P parameters) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
parameters.type = ShaderType.COMPUTE;
final Matcher matcher = versionPattern.matcher(compute);
if (!matcher.find()) {
throw new IllegalArgumentException("No #version directive found in compute shader source code!");
}
String versionString = matcher.group(1);
int versionInt = Integer.parseInt(versionString);
// Check if shader uses features requiring a higher GLSL version
final int requiredVersion = getRequiredVersion(compute, versionInt);
if (requiredVersion > versionInt) {
Iris.logger.debug("Compute shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt);
versionInt = requiredVersion;
versionString = String.valueOf(versionInt);
}
// Compute shaders always use core profile, minimum 330
if (versionInt < 330) {
versionString = "330";
versionInt = 330;
}
// Negotiate version downgrade if needed
final NegotiationResult negotiation = negotiateVersion(versionInt, PatchShaderType.COMPUTE);
if (negotiation.isError()) {
throw new RuntimeException("Compute shader version negotiation failed: " + negotiation.error());
}
if (negotiation.targetVersion() != versionInt) {
Iris.logger.debug("Negotiated compute shader from GLSL {} to {}", versionInt, negotiation.targetVersion());
versionInt = negotiation.targetVersion();
versionString = String.valueOf(versionInt);
}
String profileString = "#version " + versionString + " core\n";
// Rename reserved words
String input = replaceTexture(compute);
for (int version : versionedReservedWords.keySet()) {
if (versionInt < version) {
for (String reservedWord : versionedReservedWords.get(version)) {
final String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
}
}
final var parsedShader = ShaderParser.parseShader(input);
final var transformer = new Transformer(parsedShader.full());
doTransform(transformer, patchType, parameters, "core", versionInt);
// Extract extensions
final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
final String finalHeader = profileString + (extensions.isEmpty() ? "" : "\n" + extensions);
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> {
formattedShaderBuilder.append(getFormattedShader(tree, finalHeader));
});
String formattedShader = formattedShaderBuilder.toString();
// Restore identifiers that were temporarily renamed
formattedShader = formattedShader.replace("iris_renamed_texture", "texture");
formattedShader = formattedShader.replace("iris_renamed_sample", "sample");
result.put(PatchShaderType.COMPUTE, formattedShader);
watch.stop();
Iris.logger.info("[Load #{}] Transformed compute shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
return result;
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, NegotiationResult> negotiations = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Boolean> needsTextureLodExtension = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
for (PatchShaderType type : PatchShaderType.VALUES) {
parameters.type = type;
parameters.type = type.glShaderType;
if (inputs.get(type) == null) {
continue;
}
String input = inputs.get(type);
Matcher matcher = versionPattern.matcher(input);
final Matcher matcher = versionPattern.matcher(input);
if (!matcher.find()) {
throw new IllegalArgumentException("No #version directive found in source code!");
}
@@ -225,68 +504,84 @@ public class ShaderTransformer {
String profile = "";
int versionInt = Integer.parseInt(versionString);
// Check if shader uses features requiring a higher GLSL version
int requiredVersion = getRequiredVersion(input, versionInt);
// Include celeritas header in scan — it's injected post-negotiation but contains uint/uvec3
final String scanSource = (patchType == Patch.CELERITAS_TERRAIN && type == PatchShaderType.VERTEX) ? input + computeCeleritasHeader() : input;
final int requiredVersion = getRequiredVersion(scanSource, versionInt);
if (requiredVersion > versionInt) {
Iris.logger.debug("Shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt);
versionInt = requiredVersion;
versionString = String.valueOf(versionInt);
}
if (versionInt >= 150) {
profile = matcher.group(2);
if (profile == null) {
profile = "compatibility";
}
// Negotiate version downgrade if needed
final NegotiationResult negotiation = negotiateVersion(versionInt, type);
if (negotiation.isError()) {
throw new RuntimeException("Shader version negotiation failed for " + type.name() + ": " + negotiation.error());
}
String profileString = "#version " + versionString + " " + profile + "\n";
if (negotiation.targetVersion() != versionInt) {
String negotiationKey = type.name() + "_" + versionInt + "_" + negotiation.targetVersion();
if (loggedNegotiations.add(negotiationKey)) {
Iris.logger.info("Negotiated {} shader from GLSL {} to {} (extensions: {}, polyfills: {})", type.name(), versionInt, negotiation.targetVersion(), negotiation.extensions(), negotiation.preprocessorDefines().size());
}
versionInt = negotiation.targetVersion();
versionString = String.valueOf(versionInt);
profile = negotiation.profile();
} else {
if (versionInt >= 150) {
profile = matcher.group(2);
if (profile == null) {
profile = "compatibility";
}
}
}
negotiations.put(type, negotiation);
final String profileString = "#version " + versionString + (profile.isEmpty() ? "" : " " + profile) + "\n";
input = replaceTexture(input);
// The primary reason we rename words here using regex, is because if the words cause invalid
// GLSL, regardless of the version being used, it will cause glsl-transformation-lib to fail
// so we need to rename them prior to passing the shader input to glsl-transformation-lib.
for (String reservedWord : fullReservedWords) {
String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
for (int version : versionedReservedWords.keySet()) {
if (versionInt < version) {
for (String reservedWord : versionedReservedWords.get(version)) {
String newName = "iris_renamed_" + reservedWord;
final String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
}
}
var parsedShader = ShaderParser.parseShader(input);
var transformer = new Transformer(parsedShader.full());
final var parsedShader = ShaderParser.parseShader(input);
final var transformer = new Transformer(parsedShader.full());
if (parameters.type == ShaderType.VERTEX || parameters.type == ShaderType.FRAGMENT) {
upgradeStorageQualifiers(transformer, parameters);
}
doTransform(transformer, patchType, parameters, profile, versionInt);
// Check if we need to patch in texture LOD extension enabling
if (versionInt <= 120 && (transformer.containsCall("texture2DLod") || transformer.containsCall("texture3DLod") || transformer.containsCall("texture2DGradARB"))) {
textureLodExtensionPatches.add(transformer);
}
// Check if we need to patch in some hacky GLSL 120 compat
if (versionInt <= 120) {
hacky120Patches.add(transformer);
needsTextureLodExtension.put(type, true);
}
// Extract extensions from the pre-parsed content (version + extensions before main code)
// This preserves #extension directives that the shader pack declares
var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
types.put(type, transformer);
prepatched.put(type, profileString + (extensions.isEmpty() ? "" : "\n" + extensions));
}
CompatibilityTransformer.transformGrouped(types, parameters);
for (var entry : types.entrySet()) {
final PatchShaderType shaderType = entry.getKey();
final Transformer transformer = entry.getValue();
String header = prepatched.get(entry.getKey());
String header = prepatched.get(shaderType);
final NegotiationResult negotiation = negotiations.get(shaderType);
// For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header
if (patchType == Patch.CELERITAS_TERRAIN && entry.getKey() == PatchShaderType.VERTEX) {
if (patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX) {
header += computeCeleritasHeader();
}
@@ -303,39 +598,38 @@ public class ShaderTransformer {
formattedShader = formattedShader.replace("iris_renamed_texture", "texture");
formattedShader = formattedShader.replace("iris_renamed_sample", "sample");
// Please don't mind the entire rest of this loop basically, we're doing awful fragile regex on the transformed
// shader output to do things that I can't figure out with AST because I'm bad at it
if (textureLodExtensionPatches.contains(transformer)) {
String[] parts = formattedShader.split("\n", 2);
// Inject texture LOD extension if needed
if (needsTextureLodExtension.containsKey(shaderType)) {
final String[] parts = formattedShader.split("\n", 2);
parts[1] = "#extension GL_ARB_shader_texture_lod : require\n" + parts[1];
formattedShader = parts[0] + "\n" + parts[1];
}
if (hacky120Patches.contains(transformer)) {
// Forcibly enable GL_EXT_gpu_shader4, it has a lot of compatibility backports with GLSL 130+
// and seems more or less universally supported by hardware/drivers
String[] parts = formattedShader.split("\n", 2);
parts[1] = "#extension GL_EXT_gpu_shader4 : require\n" + parts[1];
formattedShader = parts[0] + "\n" + parts[1];
if (negotiation != null && (!negotiation.extensions().isEmpty() || !negotiation.preprocessorDefines().isEmpty())) {
formattedShader = injectGlslPreamble(formattedShader, negotiation.extensions(), negotiation.preprocessorDefines());
}
// GLSL 120 compatibility for in/out specifiers:
// - Vertex shaders: "in" = vertex attribute input -> "attribute", "out" = to fragment -> "varying"
// - Fragment shaders: "in" = from vertex -> "varying", "out" = color output -> handled elsewhere
if (entry.getKey() == PatchShaderType.VERTEX) {
// In vertex shaders, "in" declarations are vertex attributes, not varyings
Matcher inMatcher = inPattern.matcher(formattedShader);
formattedShader = inMatcher.replaceAll("attribute$2");
Matcher outMatcher = outPattern.matcher(formattedShader);
formattedShader = outMatcher.replaceAll("varying$2");
} else {
// In fragment (and geometry) shaders, both in/out become varying
Matcher inOutVaryingMatcher = inOutVaryingPattern.matcher(formattedShader);
formattedShader = inOutVaryingMatcher.replaceAll("varying$2");
if (negotiation != null && !negotiation.defines().isEmpty()) {
for (var defineEntry : negotiation.defines().entrySet()) {
formattedShader = formattedShader.replaceAll("\\b" + Pattern.quote(defineEntry.getKey()) + "\\b", Matcher.quoteReplacement(defineEntry.getValue()));
}
}
result.put(entry.getKey(), formattedShader);
// Convert storage qualifiers for downgraded shaders or native 120 shaders
if (negotiation != null && (negotiation.convertStorageQualifiers() || negotiation.targetVersion() <= 120)) {
if (shaderType == PatchShaderType.VERTEX) {
final Matcher inMatcher = inPattern.matcher(formattedShader);
formattedShader = inMatcher.replaceAll("$1attribute$3");
final Matcher outMatcher = outPattern.matcher(formattedShader);
formattedShader = outMatcher.replaceAll("$1varying$3");
} else {
final Matcher inOutVaryingMatcher = inOutVaryingPattern.matcher(formattedShader);
formattedShader = inOutVaryingMatcher.replaceAll("$1varying$3");
}
formattedShader = unsignedSuffixPattern.matcher(formattedShader).replaceAll("$1");
}
result.put(shaderType, formattedShader);
}
watch.stop();
Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
@@ -345,18 +639,21 @@ public class ShaderTransformer {
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) {
switch (patchType) {
case CELERITAS_TERRAIN:
CeleritasTransformer.transform(transformer, parameters);
CeleritasTransformer.transform(transformer, parameters, versionInt);
// Handle mc_midTexCoord for Celeritas
patchMultiTexCoord3(transformer, parameters);
replaceMidTexCoord(transformer, IrisExtendedChunkVertexType.MID_TEX_SCALE);
applyIntelHd4000Workaround(transformer);
break;
case COMPOSITE:
CompositeDepthTransformer.transform(transformer);
CompositeDepthTransformer.transform(transformer, parameters, versionInt);
break;
case ATTRIBUTES:
AttributeTransformer.transform(transformer, (AttributeParameters) parameters, profile, versionInt);
break;
case COMPUTE:
ComputeTransformer.transform(transformer, parameters, versionInt);
break;
default:
throw new IllegalStateException("Unknown patch type: " + patchType.name());
}
@@ -367,22 +664,15 @@ public class ShaderTransformer {
transformer.renameFunctionCall("ftransform", "iris_ftransform");
}
public static void replaceGlMultiTexCoordBounded(Transformer transformer, int min, int max) {
for (int i = min; i <= max; i++) {
transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)");
}
}
public static void patchMultiTexCoord3(Transformer transformer, Parameters parameters) {
if (parameters.type.glShaderType == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
if (parameters.type == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
public static void replaceMidTexCoord(Transformer transformer, float textureScale) {
int type = transformer.findType("mc_midTexCoord");
final int type = transformer.findType("mc_midTexCoord");
if (type != 0) {
transformer.removeVariable("mc_midTexCoord");
}
@@ -439,6 +729,89 @@ public class ShaderTransformer {
return "\n\n" + chunkVertexHeader + "\n\n";
}
/**
* Converts GLSL 120 storage qualifiers (varying/attribute) to modern in/out tokens so downstream AST transforms (e.g. CompatibilityTransformer) can find them.
* The hacky120Patches regex pass converts them back for the final output.
*/
public static void upgradeStorageQualifiers(Transformer root, Parameters parameters) {
final List<TerminalNode> tokens = new ArrayList<>();
root.mutateTree(tree -> ParseTreeWalker.DEFAULT.walk(new StorageCollector(tokens), tree));
for (TerminalNode node : tokens) {
if (!(node.getSymbol() instanceof CommonToken token)) {
return;
}
if (token.getType() == GLSLParser.ATTRIBUTE) {
token.setType(GLSLParser.IN);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", ""));
} else if (token.getType() == GLSLParser.VARYING) {
if (parameters.type == ShaderType.VERTEX) {
token.setType(GLSLParser.OUT);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.OUT).replace("'", ""));
} else {
token.setType(GLSLParser.IN);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", ""));
}
}
}
}
private static String injectGlslPreamble(String shader, List<String> extensions, List<String> preprocessorDefines) {
final StringBuilder extensionBlock = new StringBuilder();
final StringBuilder defineBlock = new StringBuilder();
final StringBuilder functionBlock = new StringBuilder();
for (String ext : extensions) {
extensionBlock.append("#extension ").append(ext).append(" : require\n");
}
for (String define : preprocessorDefines) {
if (define.startsWith("GLSL_FUNC:")) {
functionBlock.append(define.substring(10)).append("\n");
} else {
defineBlock.append(define).append("\n");
}
}
// Find where preprocessor section ends and code begins
final String[] lines = shader.split("\n");
final StringBuilder shaderResult = new StringBuilder();
boolean extensionsInjected = false, definesInjected = false, functionsInjected = false;
for (String line : lines) {
final String trimmed = line.trim();
final boolean isPreprocessor = trimmed.startsWith("#");
final boolean isExtension = trimmed.startsWith("#extension");
final boolean isVersion = trimmed.startsWith("#version");
// Inject our extensions right after #version
if (isVersion) {
shaderResult.append(line).append("\n");
shaderResult.append(extensionBlock);
extensionsInjected = true;
continue;
}
// Inject our defines after the last #extension line (before other preprocessor or code)
if (!definesInjected && extensionsInjected && !isExtension && !trimmed.isEmpty()) {
shaderResult.append(defineBlock);
definesInjected = true;
}
// Inject our functions after all preprocessor lines
if (!functionsInjected && definesInjected && !isPreprocessor && !trimmed.isEmpty()) {
shaderResult.append(functionBlock);
functionsInjected = true;
}
shaderResult.append(line).append("\n");
}
if (!definesInjected) shaderResult.append(defineBlock);
if (!functionsInjected) shaderResult.append(functionBlock);
return shaderResult.toString();
}
public static String getFormattedShader(ParseTree tree, String string) {
final StringBuilder sb = new StringBuilder(string + "\n");
final String[] tabHolder = {""};
@@ -1,8 +1,15 @@
package net.coderbot.iris.pipeline.transform;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import net.coderbot.iris.pipeline.transform.parameter.CeleritasTerrainParameters;
import net.coderbot.iris.pipeline.transform.parameter.ComputeParameters;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.TextureStageParameters;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -23,12 +30,16 @@ public class TransformPatcher {
final Parameters parameters;
final String vertex;
final String geometry;
final String tessControl;
final String tessEval;
final String fragment;
public CacheKey(Parameters parameters, String vertex, String geometry, String fragment) {
public CacheKey(Parameters parameters, String vertex, String geometry, String tessControl, String tessEval, String fragment) {
this.parameters = parameters;
this.vertex = vertex;
this.geometry = geometry;
this.tessControl = tessControl;
this.tessEval = tessEval;
this.fragment = fragment;
}
@@ -38,6 +49,8 @@ public class TransformPatcher {
int result = 1;
result = prime * result + ((fragment == null) ? 0 : fragment.hashCode());
result = prime * result + ((geometry == null) ? 0 : geometry.hashCode());
result = prime * result + ((tessControl == null) ? 0 : tessControl.hashCode());
result = prime * result + ((tessEval == null) ? 0 : tessEval.hashCode());
result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
result = prime * result + ((vertex == null) ? 0 : vertex.hashCode());
return result;
@@ -45,39 +58,20 @@ public class TransformPatcher {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj;
if (fragment == null) {
if (other.fragment != null)
return false;
} else if (!fragment.equals(other.fragment))
return false;
if (geometry == null) {
if (other.geometry != null)
return false;
} else if (!geometry.equals(other.geometry))
return false;
if (parameters == null) {
if (other.parameters != null)
return false;
} else if (!parameters.equals(other.parameters))
return false;
if (vertex == null) {
if (other.vertex != null)
return false;
} else if (!vertex.equals(other.vertex))
return false;
return true;
return java.util.Objects.equals(fragment, other.fragment)
&& java.util.Objects.equals(geometry, other.geometry)
&& java.util.Objects.equals(tessControl, other.tessControl)
&& java.util.Objects.equals(tessEval, other.tessEval)
&& java.util.Objects.equals(parameters, other.parameters)
&& java.util.Objects.equals(vertex, other.vertex);
}
}
private static Map<PatchShaderType, String> transform(String vertex, String geometry, String fragment, Parameters parameters) {
if (vertex == null && geometry == null && fragment == null) {
private static Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, Parameters parameters) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) {
return null;
}
@@ -85,7 +79,7 @@ public class TransformPatcher {
TransformPatcher.CacheKey key = null;
Map<PatchShaderType, String> result = null;
if (useCache) {
key = new TransformPatcher.CacheKey(parameters, vertex, geometry, fragment);
key = new TransformPatcher.CacheKey(parameters, vertex, geometry, tessControl, tessEval, fragment);
synchronized (cache) {
result = cache.get(key);
}
@@ -93,7 +87,7 @@ public class TransformPatcher {
// if there is no cache result, transform the shaders
if (result == null) {
result = ShaderTransformer.transform(vertex, geometry, fragment, parameters);
result = ShaderTransformer.transform(vertex, geometry, tessControl, tessEval, fragment, parameters);
if (useCache) {
synchronized (cache) {
// Double-check in case another thread added it while we were transforming
@@ -109,16 +103,40 @@ public class TransformPatcher {
return result;
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs));
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String fragment, InputAvailability inputs) {
return transform(vertex, geometry, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs));
return patchAttributes(vertex, geometry, null, null, fragment, inputs);
}
public static Map<PatchShaderType, String> patchCeleritasTerrain(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.CELERITAS_TERRAIN));
return transform(vertex, geometry, null, null, fragment, new CeleritasTerrainParameters(Patch.CELERITAS_TERRAIN));
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE));
return patchComposite(vertex, geometry, null, null, fragment, TextureStage.COMPOSITE_AND_FINAL, null);
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String tessControl, String tessEval, String fragment) {
return patchComposite(vertex, geometry, tessControl, tessEval, fragment, TextureStage.COMPOSITE_AND_FINAL, null);
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String tessControl, String tessEval, String fragment, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new TextureStageParameters(Patch.COMPOSITE, stage, textureMap));
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return patchComposite(vertex, geometry, null, null, fragment, stage, textureMap);
}
public static String patchCompute(String name, String compute, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
if (compute == null) {
return null;
}
Map<PatchShaderType, String> result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap));
return result != null ? result.get(PatchShaderType.COMPUTE) : null;
}
public static void clearCache() {
@@ -2,42 +2,49 @@ package net.coderbot.iris.pipeline.transform.parameter;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class AttributeParameters extends Parameters {
public final boolean hasGeometry;
public final InputAvailability inputs;
public final boolean hasGeometry;
public final InputAvailability inputs;
// WARNING: adding new fields requires updating hashCode and equals methods!
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) {
super(patch);
this.hasGeometry = hasGeometry;
this.inputs = inputs;
}
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) {
super(patch, null);
this.hasGeometry = hasGeometry;
this.inputs = inputs;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@Override
public TextureStage getTextureStage() {
return TextureStage.GBUFFERS_AND_SHADOW;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
} else if (!inputs.equals(other.inputs))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
} else if (!inputs.equals(other.inputs))
return false;
return true;
}
}
@@ -0,0 +1,19 @@
package net.coderbot.iris.pipeline.transform.parameter;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class CeleritasTerrainParameters extends Parameters {
// WARNING: adding new fields requires updating hashCode and equals methods!
public CeleritasTerrainParameters(Patch patch) {
super(patch, null);
}
@Override
public TextureStage getTextureStage() {
return TextureStage.GBUFFERS_AND_SHADOW;
}
// since this class has no additional fields, hashCode() and equals() are inherited from Parameters
}
@@ -0,0 +1,24 @@
package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class ComputeParameters extends TextureStageParameters {
// WARNING: adding new fields requires updating hashCode and equals methods!
public ComputeParameters(Patch patch, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
super(patch, stage, textureMap);
}
@Override
public AlphaTest getAlphaTest() {
return AlphaTest.ALWAYS;
}
// since this class has no fields, hashCode() and equals() are inherited from
// TextureStageParameters
}
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more