diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index 23328a0c0..12bd864dc 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -14,6 +14,7 @@ import com.gtnewhorizons.angelica.glsm.backend.VSyncMode; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.glsm.ffp.VertexKey; import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler; import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler; import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler; @@ -3057,9 +3058,15 @@ public class GLStateManager { return; } } + if (light >= VertexKey.FFP_LIGHT_COUNT && (warnedFfpLightMask & (1 << light)) == 0 && ShaderManager.getInstance().isEnabled()) { + warnedFfpLightMask |= (1 << light); + LOGGER.warn("GL_LIGHT{} enabled, but FFP shader emulation implements only GL_LIGHT0..{}", light, VertexKey.FFP_LIGHT_COUNT - 1, new Throwable("call site")); + } ctx().lightStates[light].enable(); } + private static int warnedFfpLightMask = 0; + public static void enableColorMaterial() { final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLighting.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLighting.java new file mode 100644 index 000000000..3b69aa371 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLighting.java @@ -0,0 +1,83 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.LightState; +import com.gtnewhorizons.angelica.glsm.states.MaterialState; +import org.joml.Matrix3f; +import org.joml.Vector3f; +import org.joml.Vector4f; + +public final class FFPVertexLighting { + + private static final Vector3f scratchNormal = new Vector3f(); + private static final Vector3f scratchLightVec = new Vector3f(); + private static final Vector4f scratchEyePos = new Vector4f(); + private static final Matrix3f scratchNormalMat = new Matrix3f(); + private static final Vector3f scratchVec = new Vector3f(); + + private FFPVertexLighting() {} + + public static boolean modulatesVertexColor(Vector3f destFactor) { + destFactor.set(1.0f); + + if (!GLStateManager.getLightingState().isEnabled()) return false; + if (!GLStateManager.getColorMaterial().isEnabled()) return false; + if (VertexKey.encodeColorMaterialMode(GLStateManager.getColorMaterialParameter().getValue()) != VertexKey.CM_AMBIENT_AND_DIFFUSE) return false; + + final MaterialState material = GLStateManager.getFrontMaterial(); + if (material.emission.x != 0.0f || material.emission.y != 0.0f || material.emission.z != 0.0f) + return false; + + final boolean materialHasSpecular = material.shininess > 0.0f && (material.specular.x != 0.0f || material.specular.y != 0.0f || material.specular.z != 0.0f); + + final Vector4f lightModelAmbient = GLStateManager.getLightModel().ambient; + float r = lightModelAmbient.x; + float g = lightModelAmbient.y; + float b = lightModelAmbient.z; + + final var lightEnables = GLStateManager.getLightStates(); + final var lightData = GLStateManager.getLightDataStates(); + boolean normalReady = false; + + for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) { + if (!lightEnables[i].isEnabled()) continue; + final LightState light = lightData[i]; + if (materialHasSpecular && (light.specular.x != 0.0f || light.specular.y != 0.0f || light.specular.z != 0.0f)) + return false; + if (!normalReady) { + transformCurrentNormal(); + normalReady = true; + } + final float nDotVP = Math.max(scratchNormal.dot(lightDirection(light)), 0.0f); + r += light.ambient.x + nDotVP * light.diffuse.x; + g += light.ambient.y + nDotVP * light.diffuse.y; + b += light.ambient.z + nDotVP * light.diffuse.z; + } + + if (r == 1.0f && g == 1.0f && b == 1.0f) return false; + if (!Float.isFinite(r + g + b)) return false; + destFactor.set(r, g, b); + return true; + } + + private static void transformCurrentNormal() { + GLStateManager.getModelViewMatrix().normal(scratchNormalMat); + scratchNormal.set(ShaderManager.getCurrentNormal()); + scratchNormalMat.transform(scratchNormal); + if (GLStateManager.getNormalizeState().isEnabled()) { + scratchNormal.normalize(); + } else if (GLStateManager.getRescaleNormalState().isEnabled()) { + scratchNormal.mul(Uniforms.rescaleFactor(scratchNormalMat, scratchVec)); + } + } + + private static Vector3f lightDirection(LightState light) { + if (light.position.w == 0.0f) { + scratchLightVec.set(light.position.x, light.position.y, light.position.z); + } else { + scratchEyePos.set(0.0f, 0.0f, 0.0f, 1.0f).mul(GLStateManager.getModelViewMatrix()); + scratchLightVec.set(light.position.x - scratchEyePos.x, light.position.y - scratchEyePos.y, light.position.z - scratchEyePos.z); + } + return scratchLightVec.normalize(); + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java index 5bca87279..e798b176e 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java @@ -232,8 +232,12 @@ public class Uniforms { private void stageNormalMatrix() { GLStateManager.getModelViewMatrix().normal(normalMatrix); putMat3(FFPUniformBlock.NORMAL_MATRIX, normalMatrix); - final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length(); - putFloat(FFPUniformBlock.NORMAL_SCALE, scale); + putFloat(FFPUniformBlock.NORMAL_SCALE, rescaleFactor(normalMatrix, tempVec3)); + } + + static float rescaleFactor(Matrix3f normalMatrix, Vector3f scratch) { + final float f = normalMatrix.getColumn(2, scratch).lengthSquared(); + return f > 1.0e-12f ? 1.0f / (float) Math.sqrt(f) : 1.0f; } private void stageTextureMatrices() { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java index b7de1f334..a143bd287 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -20,38 +20,36 @@ public final class VertexKey { public static final int MAX_UNITS = 4; + public static final int FFP_LIGHT_COUNT = 2; + private final long packed; private static final int BIT_LIGHTING = 0; - private static final int BIT_LIGHT0 = 1; - private static final int BIT_LIGHT1 = 2; - private static final int BIT_LIGHT0_DIR = 3; - private static final int BIT_LIGHT1_DIR = 4; - private static final int BIT_COLOR_MATERIAL = 5; - private static final int BIT_SEPARATE_SPECULAR = 6; - private static final int BIT_FOG = 7; - private static final int BIT_FOG_DIST_MODE = 8; // 2 bits: 8-9 - private static final int BIT_NORMALIZE = 10; - private static final int BIT_RESCALE_NORMAL = 11; - // Per-unit texcoord enable: bits 12-15 (unit 0..3). Unit 1 doubles as the lightmap flag. - private static final int BIT_UNIT_TEX_BASE = 12; - private static final int BIT_HAS_VERTEX_COLOR = 16; - private static final int BIT_HAS_VERTEX_NORMAL = 17; - private static final int BIT_HAS_VERTEX_TEX = 18; - private static final int BIT_HAS_VERTEX_LIGHTMAP = 19; - private static final int BIT_COLOR_MAT_MODE = 20; // 3 bits: 20-22 - // TexGen modes (unit 0 only, for now): 3 bits each (0=NONE, 1=OBJ_LINEAR, 2=EYE_LINEAR). - private static final int BIT_TEXGEN_S = 23; // 3 bits: 23-25 - private static final int BIT_TEXGEN_T = 26; // 3 bits: 26-28 - private static final int BIT_TEXGEN_R = 29; // 3 bits: 29-31 - private static final int BIT_TEXGEN_Q = 32; // 3 bits: 32-34 - private static final int BIT_CLIP_PLANES = 35; - private static final int BIT_WIDE_LINE = 36; - // Per-unit texmat enable: bits 37-40 (unit 0..3). Unit 1 is the lightmap matrix. - private static final int BIT_UNIT_TEXMAT_BASE = 37; - private static final int BIT_UNIT23_UV_FROM_UNIT0 = 41; - private static final int BIT_LINE_STIPPLE = 42; - private static final int BIT_INSTANCED = 44; + private static final int BIT_LIGHT_BASE = BIT_LIGHTING + 1; + private static final int BIT_LIGHT_DIR_BASE = BIT_LIGHT_BASE + FFP_LIGHT_COUNT; + private static final int BIT_COLOR_MATERIAL = BIT_LIGHT_DIR_BASE + FFP_LIGHT_COUNT; + private static final int BIT_SEPARATE_SPECULAR = BIT_COLOR_MATERIAL + 1; + private static final int BIT_FOG = BIT_SEPARATE_SPECULAR + 1; + private static final int BIT_FOG_DIST_MODE = BIT_FOG + 1; + private static final int BIT_NORMALIZE = BIT_FOG_DIST_MODE + 2; + private static final int BIT_RESCALE_NORMAL = BIT_NORMALIZE + 1; + private static final int BIT_UNIT_TEX_BASE = BIT_RESCALE_NORMAL + 1; + private static final int BIT_HAS_VERTEX_COLOR = BIT_UNIT_TEX_BASE + MAX_UNITS; + private static final int BIT_HAS_VERTEX_NORMAL = BIT_HAS_VERTEX_COLOR + 1; + private static final int BIT_HAS_VERTEX_TEX = BIT_HAS_VERTEX_NORMAL + 1; + private static final int BIT_HAS_VERTEX_LIGHTMAP = BIT_HAS_VERTEX_TEX + 1; + private static final int BIT_COLOR_MAT_MODE = BIT_HAS_VERTEX_LIGHTMAP + 1; + // TexGen modes are unit 0 only, for now. + private static final int BIT_TEXGEN_S = BIT_COLOR_MAT_MODE + 3; + private static final int BIT_TEXGEN_T = BIT_TEXGEN_S + 3; + private static final int BIT_TEXGEN_R = BIT_TEXGEN_T + 3; + private static final int BIT_TEXGEN_Q = BIT_TEXGEN_R + 3; + private static final int BIT_CLIP_PLANES = BIT_TEXGEN_Q + 3; + private static final int BIT_WIDE_LINE = BIT_CLIP_PLANES + 1; + private static final int BIT_UNIT_TEXMAT_BASE = BIT_WIDE_LINE + 1; + private static final int BIT_UNIT23_UV_FROM_UNIT0 = BIT_UNIT_TEXMAT_BASE + MAX_UNITS; + private static final int BIT_LINE_STIPPLE = BIT_UNIT23_UV_FROM_UNIT0 + 1; + private static final int BIT_INSTANCED = BIT_LINE_STIPPLE + 1; public static final int TG_NONE = 0; public static final int TG_OBJ_LINEAR = 1; @@ -70,10 +68,8 @@ public final class VertexKey { public long pack() { return packed; } public boolean lightingEnabled() { return bit(BIT_LIGHTING); } - public boolean light0Enabled() { return bit(BIT_LIGHT0); } - public boolean light1Enabled() { return bit(BIT_LIGHT1); } - public boolean light0Directional() { return bit(BIT_LIGHT0_DIR); } - public boolean light1Directional() { return bit(BIT_LIGHT1_DIR); } + public boolean lightEnabled(int light) { return bit(BIT_LIGHT_BASE + light); } + public boolean lightDirectional(int light) { return bit(BIT_LIGHT_DIR_BASE + light); } public boolean colorMaterialEnabled() { return bit(BIT_COLOR_MATERIAL); } public boolean separateSpecular() { return bit(BIT_SEPARATE_SPECULAR); } public boolean fogEnabled() { return bit(BIT_FOG); } @@ -136,17 +132,12 @@ public final class VertexKey { if (lighting) { bits |= (1L << BIT_LIGHTING); - if (GLStateManager.getLightStates()[0].isEnabled()) { - bits |= (1L << BIT_LIGHT0); + for (int i = 0; i < FFP_LIGHT_COUNT; i++) { + if (!GLStateManager.getLightStates()[i].isEnabled()) continue; + bits |= (1L << (BIT_LIGHT_BASE + i)); // position.w == 0 means directional - if (GLStateManager.getLightDataStates()[0].position.w == 0.0f) { - bits |= (1L << BIT_LIGHT0_DIR); - } - } - if (GLStateManager.getLightStates()[1].isEnabled()) { - bits |= (1L << BIT_LIGHT1); - if (GLStateManager.getLightDataStates()[1].position.w == 0.0f) { - bits |= (1L << BIT_LIGHT1_DIR); + if (GLStateManager.getLightDataStates()[i].position.w == 0.0f) { + bits |= (1L << (BIT_LIGHT_DIR_BASE + i)); } } @@ -265,7 +256,7 @@ public final class VertexKey { @Override public String toString() { return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%b]", - packed, lightingEnabled(), light0Enabled(), light1Enabled(), + packed, lightingEnabled(), lightEnabled(0), lightEnabled(1), colorMaterialEnabled(), fogEnabled(), unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0, unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0, diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java index 7219547f5..04acbb210 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java @@ -182,11 +182,10 @@ public final class VertexShaderGenerator { } // Per-light accumulation - if (key.light0Enabled()) { - emitLightContribution(sb, key, 0); - } - if (key.light1Enabled()) { - emitLightContribution(sb, key, 1); + for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) { + if (key.lightEnabled(i)) { + emitLightContribution(sb, key, i); + } } sb.append(" v_Color = vec4(clamp(color0, 0.0, 1.0), outAlpha);\n"); @@ -198,7 +197,7 @@ public final class VertexShaderGenerator { private static void emitLightContribution(StringBuilder sb, VertexKey key, int lightIndex) { final String li = String.valueOf(lightIndex); - final boolean directional = (lightIndex == 0) ? key.light0Directional() : key.light1Directional(); + final boolean directional = key.lightDirectional(lightIndex); final String posUniform = "u_Light" + li + "Position"; sb.append(" { // Light ").append(li).append('\n'); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLightingGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLightingGLTest.java new file mode 100644 index 000000000..62dec18f5 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPVertexLightingGLTest.java @@ -0,0 +1,241 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.joml.Vector3f; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; + +import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.COLOR_BIT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class FFPVertexLightingGLTest { + + private static final int POSITION_LOC = VertexFormatElement.Usage.POSITION.getAttributeLocation(); + private static final int COLOR_LOC = VertexFormatElement.Usage.COLOR.getAttributeLocation(); + private static final int STRIDE = 16; + + private static final int VERTEX_COLOR = 0xFF808080; + private static final float VERTEX_CHANNEL = 0x80 / 255.0f; + + private static final Vector3f IDENTITY_FACTOR = new Vector3f(1.0f, 1.0f, 1.0f); + + private final Vector3f factor = new Vector3f(); + + private int vao; + private int vbo; + + @BeforeEach + void setUpState() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.disableBlend(); + GLStateManager.disableTexture(); + GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f); + standardItemLighting(); + + GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 0.0f); + } + + @AfterEach + void cleanup() { + GLStateManager.glDisable(GL11.GL_NORMALIZE); + GLStateManager.glDisable(GL12.GL_RESCALE_NORMAL); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glDisable(GL11.GL_LIGHTING); + GLStateManager.glDisable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_LIGHT1); + GLStateManager.glDisable(GL11.GL_LIGHT2); + GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL); + final ShaderManager sm = ShaderManager.getInstance(); + if (sm.isActive()) sm.deactivate(); + sm.disable(); + GLStateManager.glBindVertexArray(0); + if (vbo != 0) { + GLStateManager.glDeleteBuffers(vbo); + vbo = 0; + } + if (vao != 0) { + GLStateManager.glDeleteVertexArrays(vao); + vao = 0; + } + } + + private static void standardItemLighting() { + GLStateManager.glEnable(GL11.GL_LIGHTING); + GLStateManager.glEnable(GL11.GL_LIGHT0); + GLStateManager.glEnable(GL11.GL_LIGHT1); + GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL); + GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE); + GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, floats(0.4f, 0.4f, 0.4f, 1.0f)); + light(GL11.GL_LIGHT0, 0.2f, 1.0f, -0.7f); + light(GL11.GL_LIGHT1, -0.2f, 1.0f, 0.7f); + } + + private static void light(int light, float x, float y, float z) { + GLStateManager.glLight(light, GL11.GL_POSITION, floats(x, y, z, 0.0f)); + GLStateManager.glLight(light, GL11.GL_DIFFUSE, floats(0.6f, 0.6f, 0.6f, 1.0f)); + GLStateManager.glLight(light, GL11.GL_AMBIENT, floats(0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glLight(light, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f)); + } + + private static String gateState() { + final var material = GLStateManager.getFrontMaterial(); + return "lighting=" + GLStateManager.getLightingState().isEnabled() + + " colorMaterial=" + GLStateManager.getColorMaterial().isEnabled() + + " cmParam=0x" + Integer.toHexString(GLStateManager.getColorMaterialParameter().getValue()) + + " emission=" + material.emission + + " specular=" + material.specular + + " shininess=" + material.shininess + + " lmAmbient=" + GLStateManager.getLightModel().ambient + + " light0=" + GLStateManager.getLightStates()[0].isEnabled() + + " light1=" + GLStateManager.getLightStates()[1].isEnabled(); + } + + private static FloatBuffer floats(float... values) { + final FloatBuffer buf = BufferUtils.createFloatBuffer(values.length); + buf.put(values).flip(); + return buf; + } + + private void buildTriangle() { + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + + final ByteBuffer data = BufferUtils.createByteBuffer(3 * STRIDE); + putVertex(data, -0.9f, -0.9f); + putVertex(data, 0.9f, -0.9f); + putVertex(data, 0.0f, 0.9f); + data.flip(); + + vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW); + GLStateManager.glEnableVertexAttribArray(POSITION_LOC); + GLStateManager.glVertexAttribPointer(POSITION_LOC, 3, GL11.GL_FLOAT, false, STRIDE, 0L); + GLStateManager.glEnableVertexAttribArray(COLOR_LOC); + GLStateManager.glVertexAttribPointer(COLOR_LOC, 4, GL11.GL_UNSIGNED_BYTE, true, STRIDE, 12L); + VAOManager.setCurrentVertexFlags(COLOR_BIT); + } + + private static void putVertex(ByteBuffer buf, float x, float y) { + final int base = buf.position(); + buf.putFloat(base, x).putFloat(base + 4, y).putFloat(base + 8, 0.0f); + buf.putInt(base + 12, VERTEX_COLOR); + buf.position(base + STRIDE); + } + + private float[] drawAndReadCenter() { + buildTriangle(); + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + GLStateManager.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "FFP draw must not raise a GL error"); + + final ByteBuffer pixel = BufferUtils.createByteBuffer(4); + GL11.glReadPixels(400, 200, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); + return new float[] { (pixel.get(0) & 0xFF) / 255.0f, (pixel.get(1) & 0xFF) / 255.0f, (pixel.get(2) & 0xFF) / 255.0f }; + } + + private void assertSolverMatchesShader(String context) { + assertTrue(FFPVertexLighting.modulatesVertexColor(factor), context + ": expected a representable factor"); + final float[] actual = drawAndReadCenter(); + final float[] expected = { Math.min(1.0f, VERTEX_CHANNEL * factor.x), Math.min(1.0f, VERTEX_CHANNEL * factor.y), Math.min(1.0f, VERTEX_CHANNEL * factor.z) }; + for (int c = 0; c < 3; c++) { + assertEquals(expected[c], actual[c], 2.0f / 255.0f, context + ": channel " + c + " solver=" + expected[c] + " shader=" + actual[c] + " factor=" + factor); + } + } + + @Test + void faceOnNormalMatchesGeneratedShader() { + GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f); + assertSolverMatchesShader("face-on normal"); + } + + @Test + void signNormalMatchesGeneratedShader() { + GLStateManager.glNormal3f(0.0f, 0.0f, -0.010416667f); + assertSolverMatchesShader("sign normal"); + assertTrue(factor.x < 0.45f, "a 0.0104-long normal must stay at the 0.4 light model ambient floor rather than pick up 0.6 per light, got " + factor.x); + } + + @Test + void tiltedNormalMatchesGeneratedShader() { + GLStateManager.glNormal3f(0.3f, 0.8f, 0.5f); + assertSolverMatchesShader("tilted normal"); + } + + @Test + void rescaleNormalMatchesGeneratedShader() { + GLStateManager.glEnable(GL12.GL_RESCALE_NORMAL); + GLStateManager.glScalef(1.0f, 2.0f, 1.0f); + GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f); + assertSolverMatchesShader("rescale normal"); + } + + @Test + void normalizeMatchesGeneratedShader() { + GLStateManager.glEnable(GL11.GL_NORMALIZE); + GLStateManager.glScalef(1.0f, 2.0f, 1.0f); + GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f); + assertSolverMatchesShader("normalize"); + assertTrue(factor.x > 1.2f, "normalize restores the unit normal, which must pick up more diffuse than rescale's 0.5-long one, got " + factor.x); + } + + @Test + void materialEmissionIsNotRepresentable() { + GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.1f, 0.1f, 0.1f, 1.0f)); + assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "emission is additive, so the lit colour is not vertexColor * factor"); + assertEquals(IDENTITY_FACTOR, factor, "a rejected solve must leave an identity factor"); + } + + @Test + void specularContributionIsNotRepresentable() { + GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f)); + GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 16.0f); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f)); + assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "specular is additive, so the lit colour is not vertexColor * factor"); + } + + @Test + void nonAmbientAndDiffuseColorMaterialIsNotRepresentable() { + GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION); + assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "only AMBIENT_AND_DIFFUSE makes the lit colour scale with the vertex colour"); + } + + @Test + void lightsBeyondTheFfpCountAreIgnored() { + assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState); + final Vector3f twoLights = new Vector3f(factor); + + light(GL11.GL_LIGHT2, 0.0f, 0.0f, 1.0f); + GLStateManager.glEnable(GL11.GL_LIGHT2); + assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState); + + assertEquals(twoLights, factor, "VertexShaderGenerator emits only GL_LIGHT0/GL_LIGHT1, so text must not see GL_LIGHT2 either"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/UniformsRescaleTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/UniformsRescaleTest.java new file mode 100644 index 000000000..d3a0ffb19 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/UniformsRescaleTest.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class UniformsRescaleTest { + + private static float rescaleFactorFor(float sx, float sy, float sz) { + final Matrix3f normalMatrix = new Matrix3f(); + new Matrix4f().rotateY(0.7f).scale(sx, sy, sz).normal(normalMatrix); + return Uniforms.rescaleFactor(normalMatrix, new Vector3f()); + } + + @Test + void rescaleFactorUsesTheInverseModelviewBottomRow() { + assertEquals(8.0f, rescaleFactorFor(4.0f, 2.0f, 8.0f), 1.0e-5f, "wrong normal matrix column"); + } + + @Test + void uniformScaleIsRowIndependent() { + assertEquals(2.0f, rescaleFactorFor(2.0f, 2.0f, 2.0f), 1.0e-5f); + } + + @Test + void singularMatrixFallsBackToUnitScale() { + assertEquals(1.0f, rescaleFactorFor(1.0f, 1.0f, 0.0f), 1.0e-5f, "a degenerate normal matrix must not divide by zero"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FontFilterVertexSamplerTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FontFilterVertexSamplerTest.java new file mode 100644 index 000000000..08bb19f38 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FontFilterVertexSamplerTest.java @@ -0,0 +1,76 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerLookup; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryUtil.memFree; + +class FontFilterVertexSamplerTest { + + private static final String FONT_FILTER_VSH = TestPaths.readString("src/main/resources/assets/angelica/shaders/fontFilter.vsh"); + + private static String runSdlPipeline(String raw) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, GL20.GL_VERTEX_SHADER, "fontFilter.vsh", true); + String src = pre != null ? pre.rewrittenSource() : raw; + src = ClipZRemap.injectGLToVulkanClipZ(src); + src = SamplerStripper.stripUnused(src); + return src; + } + + private static ShaderManager.StageReflection reflect(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_vertex_shader, + "fontFilter.vsh", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "fontFilter.vsh failed to compile for Vulkan: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + return ShaderManager.reflectStage(spirv, true); + } finally { + memFree(spirv); + } + } + + @Test + void samplerSurvivesStrippingAndReflectsOnTheVertexStage() { + final String transformed = runSdlPipeline(FONT_FILTER_VSH); + assertTrue(transformed.contains("uniform sampler2D lightmap"), "a reference inside a runtime if must keep the declaration; only preprocessor #if hides it"); + + final List samplers = reflect(transformed).samplerNames(); + assertEquals(List.of("lightmap"), samplers, "the vertex stage must expose exactly the lightmap sampler"); + } + + @Test + void looseVec3UniformReflectsWithAStd140Offset() { + final List members = reflect(runSdlPipeline(FONT_FILTER_VSH)).uboMembers(); + + final ShaderManager.UboMember lightmap = members.stream() + .filter(m -> m.name().endsWith("u_Lightmap")) + .findFirst() + .orElseThrow(() -> new AssertionError("u_Lightmap missing from the default uniform block: " + members)); + + assertEquals(3, lightmap.vectorSize(), "u_Lightmap must reflect as a 3-wide vector"); + assertEquals(1, lightmap.columns(), "u_Lightmap is a vector, not a matrix"); + assertEquals(0, lightmap.arrayStride(), "a scalar member takes Std140Writer's contiguous path"); + assertEquals(0, lightmap.offset() % 16, "std140 aligns a vec3 to 16 bytes"); + } + + @Test + void samplerNamedLightmapResolvesToTextureUnitOne() { + final List samplers = reflect(runSdlPipeline(FONT_FILTER_VSH)).samplerNames(); + final Object2IntOpenHashMap noExplicitUnits = new Object2IntOpenHashMap<>(); + noExplicitUnits.defaultReturnValue(-1); + + assertEquals(1, SamplerLookup.getSamplerTextureUnit(samplers, noExplicitUnits, 0), "even without a glUniform1i the SDL fallback must put a sampler named 'lightmap' on unit 1"); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java index 62fdbaa68..107dc8f39 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -4,19 +4,14 @@ import com.google.common.collect.ImmutableSet; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer; import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements; -import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR; -import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD; -import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH; -import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD; - import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.FontConfig; -import com.gtnewhorizons.angelica.hudcaching.HUDCaching; -import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.ffp.FFPVertexLighting; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; +import com.gtnewhorizons.angelica.hudcaching.HUDCaching; import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; @@ -29,20 +24,31 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.joml.Vector4f; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; - import java.nio.ByteBuffer; import java.nio.FloatBuffer; - import java.util.Arrays; import java.util.Comparator; import java.util.Objects; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutByte; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutShort; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memRealloc; +import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR; +import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD; +import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH; +import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD; /** * A batching replacement for {@code FontRenderer} @@ -67,6 +73,8 @@ public class BatchingFontRenderer { private final int AAStrength; private final int alphaTestRefLocation; private final int mvpMatrixLocation; + private final int lightmapLocation; + private final int lightmapSamplerLocation; private final int fontShaderId; final boolean isSGA; @@ -111,6 +119,8 @@ public class BatchingFontRenderer { AAStrength = GLStateManager.glGetUniformLocation(fontShaderId, "strength"); alphaTestRefLocation = GLStateManager.glGetUniformLocation(fontShaderId, "alphaTestRef"); mvpMatrixLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_MVPMatrix"); + lightmapLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_Lightmap"); + lightmapSamplerLocation = GLStateManager.glGetUniformLocation(fontShaderId, "lightmap"); if (ebo == null) { ebo = new IndexBuffer(); vbo = GLStateManager.glGenBuffers(); @@ -128,6 +138,9 @@ public class BatchingFontRenderer { // [v, v, t, t, c, c, c, c, tb, tb, tb, tb] // v, t and tb are floats, c is bytes; 36 bytes total private static final int VERTEX_SIZE = 36; + + /** {@code OpenGlHelper.lightmapTexUnit} */ + private static final int LIGHTMAP_TEX_UNIT = 1; private static int rawCapacity = INITIAL_BATCH_SIZE * VERTEX_SIZE; private static ByteBuffer vertexData = memAlloc(rawCapacity); private static long vertexDataAddress = memAddress0(vertexData); @@ -138,6 +151,7 @@ public class BatchingFontRenderer { private static int fontVAO = 0; private static int vbo; private static IndexBuffer ebo; + private static int lightmapSamplerProgram; private static final int RING_CAPACITY = 2 * 1024 * 1024; private static PersistentStreamingBuffer streamRing; @@ -158,11 +172,58 @@ public class BatchingFontRenderer { private int blendSrcRGB = GL11.GL_SRC_ALPHA; private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA; + private float lightmapU = 0.0f; + private float lightmapV = 0.0f; + private boolean lightmapActive = false; + private int lightmapTextureId = 0; + + private final Vector3f lightingFactor = new Vector3f(1.0f, 1.0f, 1.0f); + private boolean lightingFactorActive = false; + + private static final Vector4f scratchLightmapUv = new Vector4f(); + + private int applyLighting(int argb) { + if (!lightingFactorActive) return argb; + final int red = Math.max(0, Math.min(255, (int) (((argb >> 16) & 0xFF) * lightingFactor.x + 0.5f))); + final int green = Math.max(0, Math.min(255, (int) (((argb >> 8) & 0xFF) * lightingFactor.y + 0.5f))); + final int blue = Math.max(0, Math.min(255, (int) ((argb & 0xFF) * lightingFactor.z + 0.5f))); + return (argb & 0xFF000000) | (red << 16) | (green << 8) | blue; + } + + private void captureLightmapState() { + final int unitBinding = GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding(); + + final boolean active = GLStateManager.getProjectionMatrix().m33() == 0.0f && unitBinding != 0; + + float u = 0.0f; + float v = 0.0f; + int texture = 0; + if (active) { + scratchLightmapUv.set(GLSMConfig.lastBrightnessX, GLSMConfig.lastBrightnessY, 0.0f, 1.0f).mul(GLStateManager.getTextures().getTextureUnitMatrix(LIGHTMAP_TEX_UNIT)); + u = scratchLightmapUv.x; + v = scratchLightmapUv.y; + texture = unitBinding; + } + + if (active == lightmapActive && u == lightmapU && v == lightmapV && texture == lightmapTextureId) { + return; + } + sealBatchSegment(); + lightmapActive = active; + lightmapU = u; + lightmapV = v; + lightmapTextureId = texture; + } + private static final class TextSegment { final Matrix4f mvp = new Matrix4f(); BatchingFontRenderer owner; int cmdStart; int cmdEnd; + float lightmapU; + float lightmapV; + boolean lightmapActive; + int lightmapTexture; } // 16-bit EBO index range @@ -183,7 +244,6 @@ public class BatchingFontRenderer { private int batchSealedEnd; private static BatchingFontRenderer arenaOwner; - private void allocateBuffers() { populateEBO(rawCapacity / VERTEX_SIZE); } @@ -255,6 +315,7 @@ public class BatchingFontRenderer { private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) { final long ptr = vertexDataAddress + vertexDataPos; + rgba = applyLighting(rgba); // v, v memPutFloat(ptr, x); @@ -414,6 +475,10 @@ public class BatchingFontRenderer { segment.cmdStart = batchSealedEnd; segment.cmdEnd = end; resolveMvp(segment.mvp); + segment.lightmapActive = lightmapActive; + segment.lightmapU = lightmapU; + segment.lightmapV = lightmapV; + segment.lightmapTexture = lightmapTextureId; batchSegments.add(segment); batchSealedEnd = end; } @@ -485,6 +550,7 @@ public class BatchingFontRenderer { final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D); final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND); final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + final int lightmapBindingBefore = boundLightmapTexture(); final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled(); final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled(); @@ -493,6 +559,7 @@ public class BatchingFontRenderer { GLStateManager.glDepthMask(false); flushLastTexture = DUMMY_RESOURCE_LOCATION; flushTextureChanged = false; + resetFlushLightmap(); try (MemoryStack stack = stackPush()) { final FloatBuffer mvpBuf = stack.mallocFloat(16); for (int i = 0, n = deferredSegments.size(); i < n; i++) { @@ -500,10 +567,12 @@ public class BatchingFontRenderer { mvpBuf.clear(); segment.mvp.get(mvpBuf); GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf); + uploadLightmap(segment.owner.lightmapLocation, segment.lightmapActive, segment.lightmapU, + segment.lightmapV, segment.lightmapTexture); drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner); } } - restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore); + restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore, lightmapBindingBefore); restoreDepth(depthTestBefore, depthMaskBefore); discardDeferredText(); @@ -517,6 +586,7 @@ public class BatchingFontRenderer { segment.owner.recycleBatchSegments(); segment.owner.batchSealedEnd = 0; segment.owner.batchMatrixValid = false; + segment.owner.resetLightmapState(); segment.owner = null; } deferredSegmentPool.addAll(deferredSegments); @@ -578,12 +648,14 @@ public class BatchingFontRenderer { final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D); final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND); final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + final int lightmapBindingBefore = boundLightmapTexture(); final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled(); final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled(); setupFontDrawState(); flushLastTexture = DUMMY_RESOURCE_LOCATION; flushTextureChanged = false; + resetFlushLightmap(); try (MemoryStack stack = stackPush()) { final FloatBuffer mvpBuf = stack.mallocFloat(16); for (int i = 0; i < segmentCount; i++) { @@ -591,6 +663,7 @@ public class BatchingFontRenderer { mvpBuf.clear(); segment.mvp.get(mvpBuf); GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf); + uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture); drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this); } if (batchSealedEnd < cmdCount) { @@ -598,10 +671,11 @@ public class BatchingFontRenderer { resolveMvp(scratchMvp); scratchMvp.get(mvpBuf); GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf); + uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId); drawCommands(cmds, batchSealedEnd, cmdCount, this); } } - restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore); + restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore, lightmapBindingBefore); restoreDepth(depthTestBefore, depthMaskBefore); truncateBatchToWatermark(); @@ -624,6 +698,10 @@ public class BatchingFontRenderer { GLStateManager.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f); } GLStateManager.glUniform1f(alphaTestRefLocation, GLStateManager.getAlphaState().getReference()); + if (lightmapSamplerProgram != fontShaderId) { + GLStateManager.glUniform1i(lightmapSamplerLocation, LIGHTMAP_TEX_UNIT); + lightmapSamplerProgram = fontShaderId; + } if (fontVAO == 0) { fontVAO = GLStateManager.glGenVertexArrays(); @@ -654,6 +732,38 @@ public class BatchingFontRenderer { private static ResourceLocation flushLastTexture; private static boolean flushTextureChanged; + private static float flushLastLightmapU; + private static float flushLastLightmapV; + private static boolean flushLastLightmapActive; + + private static void resetFlushLightmap() { + flushLastLightmapU = Float.NaN; + flushLastLightmapV = Float.NaN; + flushLastLightmapActive = false; + } + + private static int boundLightmapTexture() { + return GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding(); + } + + private static void bindLightmapTexture(int texture) { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + + private static void uploadLightmap(int uniformLocation, boolean active, float u, float v, int texture) { + if (u != flushLastLightmapU || v != flushLastLightmapV || active != flushLastLightmapActive) { + GLStateManager.glUniform3f(uniformLocation, u, v, active ? 1.0f : 0.0f); + flushLastLightmapU = u; + flushLastLightmapV = v; + flushLastLightmapActive = active; + } + if (active && texture != 0 && boundLightmapTexture() != texture) { + bindLightmapTexture(texture); + } + } + private static void drawCommands(FontDrawCmd[] cmdsData, int from, int to, BatchingFontRenderer owner) { for (int i = from; i < to; i++) { final FontDrawCmd cmd = cmdsData[i]; @@ -673,7 +783,7 @@ public class BatchingFontRenderer { } } - private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore) { + private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore, int lightmapBindingBefore) { GLStateManager.glUseProgram(prevProgram); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); @@ -688,6 +798,9 @@ public class BatchingFontRenderer { if (flushTextureChanged) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore); } + if (boundLightmapTexture() != lightmapBindingBefore) { + bindLightmapTexture(lightmapBindingBefore); + } } private static void restoreDepth(boolean testBefore, boolean maskBefore) { @@ -709,11 +822,19 @@ public class BatchingFontRenderer { batchMatrixValid = false; vertexDataPos = deferredVertexPos; idxWriterIndex = deferredIdxPos; + resetLightmapState(); if (arenaOwner == this) { arenaOwner = null; } } + private void resetLightmapState() { + lightmapActive = false; + lightmapU = 0.0f; + lightmapV = 0.0f; + lightmapTextureId = 0; + } + // === Actual text mesh generation public static boolean charInRange(char what, char fromInclusive, char toInclusive) { @@ -808,6 +929,8 @@ public class BatchingFontRenderer { FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture; this.beginBatch(); + this.captureLightmapState(); + this.lightingFactorActive = FFPVertexLighting.modulatesVertexColor(this.lightingFactor); float curX = anchorX; try { final int totalStringLength = string.length(); diff --git a/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java b/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java index 352716cbc..cd96675b2 100644 --- a/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java @@ -6,7 +6,7 @@ import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import org.joml.Matrix4f; public class BuiltinReplacementUniforms { - private static final Matrix4f lightmapTextureMatrix; + public static final Matrix4f lightmapTextureMatrix; static { // This mimics the transformations done in LightTexture to the GL_TEXTURE matrix. diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.vsh b/src/main/resources/assets/angelica/shaders/fontFilter.vsh index 7dbc83680..84e99b3ea 100644 --- a/src/main/resources/assets/angelica/shaders/fontFilter.vsh +++ b/src/main/resources/assets/angelica/shaders/fontFilter.vsh @@ -6,6 +6,8 @@ layout(location = 2) in vec4 a_Color; layout(location = 3) in vec4 a_TexBounds; uniform mat4 u_MVPMatrix; +uniform vec3 u_Lightmap; +uniform sampler2D lightmap; out vec4 tB; out vec4 color; @@ -15,5 +17,10 @@ void main() { gl_Position = u_MVPMatrix * vec4(a_Position, 0.0, 1.0); texCoord = a_TexCoord0; color = a_Color; + + if (u_Lightmap.z > 0.5) { + color.rgb *= textureLod(lightmap, u_Lightmap.xy, 0.0).rgb; + } + tB = a_TexBounds; } diff --git a/src/test/java/com/gtnewhorizons/angelica/client/font/FontFilterLightmapGLTest.java b/src/test/java/com/gtnewhorizons/angelica/client/font/FontFilterLightmapGLTest.java new file mode 100644 index 000000000..c33d290ee --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/client/font/FontFilterLightmapGLTest.java @@ -0,0 +1,195 @@ +package com.gtnewhorizons.angelica.client.font; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; +import org.joml.Matrix4f; +import org.joml.Vector4f; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@GLCoreTest +class FontFilterLightmapGLTest { + + private static final int LIGHTMAP_TEX_UNIT = 1; + private static final int LIGHTMAP_SIZE = 16; + private static final int VERTEX_SIZE = 36; + + private static final float BRIGHTNESS_X = 128.0f; + private static final float BRIGHTNESS_Y = 64.0f; + private static final int LIT_TEXEL_X = 8; + private static final int LIT_TEXEL_Y = 4; + + private static final int TEXEL_R = 0x40; + private static final int TEXEL_G = 0x80; + private static final int TEXEL_B = 0xC0; + + private static final int VERTEX_COLOR = 0xFFFFFFFF; + + private int program; + private int vao; + private int vbo; + private int lightmapTexture; + + @AfterEach + void cleanup() { + GLStateManager.glUseProgram(0); + GLStateManager.glBindVertexArray(0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + if (lightmapTexture != 0) { GL11.glDeleteTextures(lightmapTexture); lightmapTexture = 0; } + if (vbo != 0) { GLStateManager.glDeleteBuffers(vbo); vbo = 0; } + if (vao != 0) { GLStateManager.glDeleteVertexArrays(vao); vao = 0; } + if (program != 0) { GLStateManager.glDeleteProgram(program); program = 0; } + } + + private static int compile(int type, String name) { + final int shader = GLStateManager.glCreateShader(type); + GLStateManager.glShaderSource(shader, TestPaths.readString("src/main/resources/assets/angelica/shaders/" + name)); + GLStateManager.glCompileShader(shader); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS), () -> name + " failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096)); + return shader; + } + + private void buildProgram() { + final int vertex = compile(GL20.GL_VERTEX_SHADER, "fontFilter.vsh"); + final int fragment = compile(GL20.GL_FRAGMENT_SHADER, "fontFilter.fsh"); + program = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(program, vertex); + GLStateManager.glAttachShader(program, fragment); + GLStateManager.glLinkProgram(program); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetProgrami(program, GL20.GL_LINK_STATUS), () -> "fontFilter failed to link:\n" + GLStateManager.glGetProgramInfoLog(program, 4096)); + GLStateManager.glDeleteShader(vertex); + GLStateManager.glDeleteShader(fragment); + } + + private void buildLightmapTexture() { + final ByteBuffer pixels = BufferUtils.createByteBuffer(LIGHTMAP_SIZE * LIGHTMAP_SIZE * 4); + for (int y = 0; y < LIGHTMAP_SIZE; y++) { + for (int x = 0; x < LIGHTMAP_SIZE; x++) { + final boolean lit = x == LIT_TEXEL_X && y == LIT_TEXEL_Y; + final int base = (y * LIGHTMAP_SIZE + x) * 4; + pixels.put(base, (byte) (lit ? TEXEL_R : 0)); + pixels.put(base + 1, (byte) (lit ? TEXEL_G : 0)); + pixels.put(base + 2, (byte) (lit ? TEXEL_B : 0)); + pixels.put(base + 3, (byte) 0xFF); + } + } + + lightmapTexture = GL11.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, lightmapTexture); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, LIGHTMAP_SIZE, LIGHTMAP_SIZE, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + + private void buildQuad() { + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + + final ByteBuffer data = BufferUtils.createByteBuffer(3 * VERTEX_SIZE); + putVertex(data, -0.9f, -0.9f); + putVertex(data, 0.9f, -0.9f); + putVertex(data, 0.0f, 0.9f); + data.flip(); + + vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW); + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 0L); + GLStateManager.glEnableVertexAttribArray(1); + GLStateManager.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 8L); + GLStateManager.glEnableVertexAttribArray(2); + GLStateManager.glVertexAttribPointer(2, 4, GL11.GL_UNSIGNED_BYTE, true, VERTEX_SIZE, 16L); + GLStateManager.glEnableVertexAttribArray(3); + GLStateManager.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, VERTEX_SIZE, 20L); + } + + private static void putVertex(ByteBuffer buf, float x, float y) { + final int base = buf.position(); + buf.putFloat(base, x).putFloat(base + 4, y); + buf.putFloat(base + 8, 0.0f).putFloat(base + 12, 0.0f); + buf.putInt(base + 16, VERTEX_COLOR); + buf.putFloat(base + 20, 0.0f).putFloat(base + 24, 1.0f) + .putFloat(base + 28, 0.0f).putFloat(base + 32, 1.0f); + buf.position(base + VERTEX_SIZE); + } + + private static void applyVanillaLightmapMatrix() { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glScalef(0.00390625f, 0.00390625f, 0.00390625f); + GLStateManager.glTranslatef(8.0f, 8.0f, 8.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + + private float[] draw(boolean lightmapEnabled) { + buildProgram(); + buildLightmapTexture(); + buildQuad(); + applyVanillaLightmapMatrix(); + + assertEquals(BuiltinReplacementUniforms.lightmapTextureMatrix, new Matrix4f(GLStateManager.getTextures().getTextureUnitMatrix(LIGHTMAP_TEX_UNIT)), "EntityRenderer#enableLightmap must reproduce the lightmap texture matrix Iris documents"); + + final Vector4f uv = new Vector4f(BRIGHTNESS_X, BRIGHTNESS_Y, 0.0f, 1.0f).mul(GLStateManager.getTextures().getTextureUnitMatrix(LIGHTMAP_TEX_UNIT)); + + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.disableBlend(); + + GLStateManager.glUseProgram(program); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(program, "sampler"), 0); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(program, "lightmap"), LIGHTMAP_TEX_UNIT); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(program, "aaMode"), 0); + GLStateManager.glUniform1f(GLStateManager.glGetUniformLocation(program, "strength"), 1.0f); + GLStateManager.glUniform1f(GLStateManager.glGetUniformLocation(program, "alphaTestRef"), 0.0f); + GLStateManager.glUniform3f(GLStateManager.glGetUniformLocation(program, "u_Lightmap"), uv.x, uv.y, lightmapEnabled ? 1.0f : 0.0f); + + GLStateManager.glUniformMatrix4(GLStateManager.glGetUniformLocation(program, "u_MVPMatrix"), false, new Matrix4f().get(BufferUtils.createFloatBuffer(16))); + + GLStateManager.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "fontFilter draw must not raise a GL error"); + + final ByteBuffer pixel = BufferUtils.createByteBuffer(4); + GL11.glReadPixels(400, 200, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); + return new float[] { + (pixel.get(0) & 0xFF) / 255.0f, + (pixel.get(1) & 0xFF) / 255.0f, + (pixel.get(2) & 0xFF) / 255.0f }; + } + + @Test + void enabledLightmapModulatesTheGlyphColor() { + final float[] actual = draw(true); + assertEquals(TEXEL_R / 255.0f, actual[0], 2.0f / 255.0f, "red must come from lightmap texel"); + assertEquals(TEXEL_G / 255.0f, actual[1], 2.0f / 255.0f, "green must come from lightmap texel"); + assertEquals(TEXEL_B / 255.0f, actual[2], 2.0f / 255.0f, "blue must come from lightmap texel"); + } + + @Test + void disabledLightmapLeavesTheGlyphColorAlone() { + final float[] actual = draw(false); + assertEquals(1.0f, actual[0], 2.0f / 255.0f, "u_Lightmap.z = 0 must leave the colour unmodulated"); + assertEquals(1.0f, actual[1], 2.0f / 255.0f, "u_Lightmap.z = 0 must leave the colour unmodulated"); + assertEquals(1.0f, actual[2], 2.0f / 255.0f, "u_Lightmap.z = 0 must leave the colour unmodulated"); + } +}