From c827d446d59a751ab21cc2a986f2c17a0b4cf8c0 Mon Sep 17 00:00:00 2001 From: Jason Mitchell Date: Fri, 27 Mar 2026 11:20:29 -0700 Subject: [PATCH] External Redirector API (#1580) Co-authored-by: Alexdoru <57050655+Alexdoru@users.noreply.github.com> --- .../glsm/ffp/FragmentShaderGenerator.java | 14 +- .../glsm/redirect/GLSMRedirector.java | 20 ++ .../angelica/api/GLRedirects.java | 118 ++++++++++++ .../loading/rfb/AngelicaRfbPlugin.java | 1 + .../angelica/api/GLRedirectsTest.java | 181 ++++++++++++++++++ 5 files changed, 328 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/gtnewhorizons/angelica/api/GLRedirects.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/api/GLRedirectsTest.java diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java index 5c64472d7..42f6c5af8 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java @@ -273,21 +273,23 @@ public final class FragmentShaderGenerator { sb.append(" // Alpha test\n"); final int func = FragmentKey.decodeAlphaFunc(key.alphaTestFunc()); + sb.append(" float qa = round(color.a * 255.0);\n"); + sb.append(" float qr = round(u_AlphaRef * 255.0);\n"); switch (func) { case GL11.GL_NEVER -> sb.append(" discard;\n"); case GL11.GL_LESS -> - sb.append(" if (color.a >= u_AlphaRef) discard;\n"); + sb.append(" if (qa >= qr) discard;\n"); case GL11.GL_EQUAL -> - sb.append(" if (color.a != u_AlphaRef) discard;\n"); + sb.append(" if (qa != qr) discard;\n"); case GL11.GL_LEQUAL -> - sb.append(" if (color.a > u_AlphaRef) discard;\n"); + sb.append(" if (qa > qr) discard;\n"); case GL11.GL_GREATER -> - sb.append(" if (color.a <= u_AlphaRef) discard;\n"); + sb.append(" if (qa <= qr) discard;\n"); case GL11.GL_NOTEQUAL -> - sb.append(" if (color.a == u_AlphaRef) discard;\n"); + sb.append(" if (qa == qr) discard;\n"); case GL11.GL_GEQUAL -> - sb.append(" if (color.a < u_AlphaRef) discard;\n"); + sb.append(" if (qa < qr) discard;\n"); case GL11.GL_ALWAYS -> {} } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java index 4c4314534..0bfc00111 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java @@ -14,6 +14,7 @@ import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -79,6 +80,9 @@ public class GLSMRedirector { glCapRedirects.put(org.lwjgl.opengl.GL11.GL_SCISSOR_TEST, "ScissorTest"); final var gl11 = RedirectMap.newMap() + // glEnable/Disable - Special cased in GLSMRedirector, but included here for the external API + .add("glEnable") + .add("glDisable") .add("glAlphaFunc") .add("glBegin") .add("glBindTexture") @@ -495,6 +499,22 @@ public class GLSMRedirector { return CORE_EXCLUSIONS.clone(); } + /** The internal-name prefix used to match GL version classes (e.g., {@code "org/lwjgl/opengl/GL"}). */ + public static String getGLPrefix() { return GL_PREFIX; } + + /** The internal name of the redirect target class. */ + public static String getTargetClassName() { return GLStateManager; } + + /** Method redirects for GL-prefix classes. Key: original method name, Value: GLStateManager method name. */ + public static Map getGLPrefixMethodRedirects() { + return Collections.unmodifiableMap(glMethodRedirects); + } + + /** Method redirects for named (non-GL-prefix) classes. Key: internal class name, Value: per-method redirect map. */ + public static Map> getNamedClassMethodRedirects() { + return Collections.unmodifiableMap(methodRedirects); + } + public boolean shouldTransform(byte[] basicClass) { return cstPoolParser.find(basicClass, true); } diff --git a/src/main/java/com/gtnewhorizons/angelica/api/GLRedirects.java b/src/main/java/com/gtnewhorizons/angelica/api/GLRedirects.java new file mode 100644 index 000000000..a134454e2 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/GLRedirects.java @@ -0,0 +1,118 @@ +package com.gtnewhorizons.angelica.api; + +import com.gtnewhorizons.angelica.glsm.redirect.GLSMRedirector; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; +import java.util.regex.Pattern; + +/** + * Public API for querying Angelica's GL call redirections. + *

+ * Angelica's bytecode transformer redirects GL calls (e.g., {@code GL11.glPushMatrix()}) to + * {@link com.gtnewhorizons.angelica.glsm.GLStateManager GLStateManager} for state tracking and + * core profile compatibility. This works for normal Java bytecode loaded through the Forge classloader, + * but callers that bypass class transformation (e.g., Nashorn/script engines, reflection, MethodHandles) + * need to perform their own redirection. + *

+ * This class provides the redirect mapping data and a precompiled regex pattern for transforming + * script source text before evaluation. + * + *

Example: transforming a Nashorn script before eval

+ * Given a script that uses {@code importPackage(Packages.org.lwjgl.opengl)} and calls + * {@code GL11.glPushMatrix()}, the text transformation rewrites those calls before evaluation: + *
{@code
+ * // Make GLStateManager available to the script -- either via importPackage:
+ * script = "importPackage(Packages.com.gtnewhorizons.angelica.glsm);\n" + script;
+ * // ... or via Java.type for an explicit binding:
+ * // script = "var GLStateManager = Java.type('" + GLRedirects.TARGET_CLASS + "');\n" + script;
+ *
+ * // Rewrite: GL11.glPushMatrix() -> GLStateManager.glPushMatrix()
+ * script = GLRedirects.getMethodRedirectPattern().matcher(script).replaceAll(mr -> {
+ *     String target = GLRedirects.getTargetMethodName(mr.group(0));
+ *     return target != null ? "GLStateManager." + target : mr.group(0);
+ * });
+ *
+ * engine.eval(script);
+ * }
+ */ +public final class GLRedirects { + /** Fully qualified name of the GLStateManager class that all methods redirect to. */ + @SuppressWarnings("unused") + public static final String TARGET_CLASS = "com.gtnewhorizons.angelica.glsm.GLStateManager"; + + private static final String SHORT_GL_PREFIX; + private static final Map> NAMED_CLASS_SHORT_NAME_MAP; + private static final Map GL_PREFIX_METHOD_REDIRECTS; + private static final Pattern METHOD_REDIRECT_PATTERN; + + static { + SHORT_GL_PREFIX = buildShortGLPrefix(); + NAMED_CLASS_SHORT_NAME_MAP = buildNamedClassShortNameMap(); + GL_PREFIX_METHOD_REDIRECTS = GLSMRedirector.getGLPrefixMethodRedirects(); + METHOD_REDIRECT_PATTERN = buildMethodRedirectPattern(); + } + + private GLRedirects() {} + + /** + * Returns a precompiled pattern that matches redirected {@code ClassName.methodName} references + * using short (simple) class names, as they might typically appear in script text. + * + * @return compiled regex pattern + */ + public static Pattern getMethodRedirectPattern() { + return METHOD_REDIRECT_PATTERN; + } + + /** + * Looks up the GLStateManager target method name for a short-name reference. + * + * @param classAndMethod short class name and method, e.g., {@code "GL11.glPushMatrix"} + * @return the target method name on GLStateManager (e.g., {@code "glPushMatrix"}), or {@code null} if this reference is not redirected + */ + public static String getTargetMethodName(String classAndMethod) { + final int dot = classAndMethod.indexOf('.'); + if (dot < 0) return null; + + final String className = classAndMethod.substring(0, dot); + final String methodName = classAndMethod.substring(dot + 1); + + final Map classRedirects = NAMED_CLASS_SHORT_NAME_MAP.get(className); + if (classRedirects != null) { + return classRedirects.get(methodName); + } + + if (className.startsWith(SHORT_GL_PREFIX)) { + return GL_PREFIX_METHOD_REDIRECTS.get(methodName); + } + + return null; + } + + private static String buildShortGLPrefix() { + final String glPrefix = GLSMRedirector.getGLPrefix(); + return glPrefix.substring(glPrefix.lastIndexOf('/') + 1); + } + + private static Map> buildNamedClassShortNameMap() { + final Map> named = new HashMap<>(); + for (final var entry : GLSMRedirector.getNamedClassMethodRedirects().entrySet()) { + final String internalName = entry.getKey(); + final String shortName = internalName.substring(internalName.lastIndexOf('/') + 1); + named.put(shortName, entry.getValue()); + } + return named; + } + + private static Pattern buildMethodRedirectPattern() { + final TreeSet alternatives = new TreeSet<>(); + alternatives.add(Pattern.quote(SHORT_GL_PREFIX) + "\\w+"); + for (final String shortName : NAMED_CLASS_SHORT_NAME_MAP.keySet()) { + alternatives.add(Pattern.quote(shortName)); + } + final String classAlt = String.join("|", alternatives); + return Pattern.compile("\\b(" + classAlt + ")\\.\\w+\\b"); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/AngelicaRfbPlugin.java b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/AngelicaRfbPlugin.java index 41df68d81..e4333adf4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/AngelicaRfbPlugin.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/AngelicaRfbPlugin.java @@ -15,6 +15,7 @@ public class AngelicaRfbPlugin implements RfbPlugin { @Override public void onConstruction(@NotNull PluginContext ctx) { Launch.blackboard.put("angelica.rfbPluginLoaded", Boolean.TRUE); + Launch.classLoader.addClassLoaderExclusion("com.gtnewhorizons.angelica.glsm.redirect."); } @Override diff --git a/src/test/java/com/gtnewhorizons/angelica/api/GLRedirectsTest.java b/src/test/java/com/gtnewhorizons/angelica/api/GLRedirectsTest.java new file mode 100644 index 000000000..904825cb2 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/api/GLRedirectsTest.java @@ -0,0 +1,181 @@ +package com.gtnewhorizons.angelica.api; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GLRedirectsTest { + + @ParameterizedTest(name = "{0}.{1} -> {2}") + @CsvSource({ + "GL11, glPushMatrix, glPushMatrix", + "GL11, glPopMatrix, glPopMatrix", + "GL11, glTranslatef, glTranslatef", + "GL11, glRotatef, glRotatef", + "GL11, glScalef, glScalef", + "GL11, glEnable, glEnable", + "GL11, glDisable, glDisable", + "GL11, glBegin, glBegin", + "GL11, glEnd, glEnd", + "GL11, glVertex3f, glVertex3f", + "GL11, glColor4f, glColor4f", + "GL11, glNormal3f, glNormal3f", + "GL11, glTexCoord2f, glTexCoord2f", + "GL11, glBindTexture, glBindTexture", + "GL11, glBlendFunc, glBlendFunc", + "GL11, glDepthMask, glDepthMask", + "GL11, glDepthFunc, glDepthFunc", + "GL11, glAlphaFunc, glAlphaFunc", + "GL11, glMatrixMode, glMatrixMode", + "GL11, glLoadIdentity, glLoadIdentity", + "GL11, glShadeModel, glShadeModel", + "GL11, glDrawArrays, glDrawArrays", + "GL11, glDrawElements, glDrawElements", + "GL11, glNewList, glNewList", + "GL11, glEndList, glEndList", + "GL11, glCallList, glCallList", + "GL11, glViewport, glViewport", + "GL12, glTexImage3D, glTexImage3D", + "GL13, glActiveTexture, glActiveTexture", + "GL13, glMultiTexCoord2f, glMultiTexCoord2f", + "GL14, glBlendFuncSeparate, tryBlendFuncSeparate", + "GL14, glBlendColor, glBlendColor", + "GL15, glGenBuffers, glGenBuffers", + "GL15, glBindBuffer, glBindBuffer", + "GL15, glBufferData, glBufferData", + "GL15, glDeleteBuffers, glDeleteBuffers", + "GL20, glUseProgram, glUseProgram", + "GL20, glCreateShader, glCreateShader", + "GL20, glShaderSource, glShaderSource", + "GL20, glLinkProgram, glLinkProgram", + "GL20, glUniform1f, glUniform1f", + "GL20, glUniform4f, glUniform4f", + "GL20, glGetUniformLocation, glGetUniformLocation", + "GL20, glVertexAttribPointer, glVertexAttribPointer", + "GL30, glGenFramebuffers, glGenFramebuffers", + "GL30, glBindFramebuffer, glBindFramebuffer", + "GL30, glGenVertexArrays, glGenVertexArrays", + "GL30, glBindVertexArray, glBindVertexArray", + "GL30, glGenerateMipmap, glGenerateMipmap", + "GL31, glDrawElementsInstanced, glDrawElementsInstanced", + "GL33, glGenSamplers, glGenSamplers", + "GL33, glBindSampler, glBindSampler", + "GL42, glTexStorage2D, glTexStorage2D", + "GL43, glDispatchCompute, glDispatchCompute", + "GL44, glBufferStorage, glBufferStorage", + }) + void glVersionClassMethodRedirects(String className, String method, String expected) { + assertEquals(expected, GLRedirects.getTargetMethodName(className + "." + method)); + } + + @ParameterizedTest(name = "{0}.{1} -> {2}") + @CsvSource({ + "GL11C, glDrawArrays, glDrawArrays", + "GL20C, glUseProgram, glUseProgram", + "GL30C, glBindFramebuffer, glBindFramebuffer", + "GL33C, glBindSampler, glBindSampler", + }) + void cVariantsUseGLPrefixMap(String className, String method, String expected) { + assertEquals(expected, GLRedirects.getTargetMethodName(className + "." + method)); + } + + @ParameterizedTest(name = "{0}.{1} -> {2}") + @CsvSource({ + "EXTBlendFuncSeparate, glBlendFuncSeparateEXT, tryBlendFuncSeparate", + "ARBMultitexture, glActiveTextureARB, glActiveTextureARB", + "ARBShaderObjects, glUseProgramObjectARB, glUseProgram", + "ARBShaderObjects, glCreateShaderObjectARB, glCreateShader", + "ARBShaderObjects, glCompileShaderARB, glCompileShader", + "ARBShaderObjects, glAttachObjectARB, glAttachShader", + "ARBShaderObjects, glUniform1fARB, glUniform1f", + "ARBShaderObjects, glUniformMatrix4ARB, glUniformMatrix4", + "ARBShaderObjects, glGetUniformLocationARB, glGetUniformLocation", + "ARBVertexArrayObject, glBindVertexArray, glBindVertexArray", + "ARBInstancedArrays, glVertexAttribDivisorARB, glVertexAttribDivisorARB", + "APPLEVertexArrayObject, glBindVertexArrayAPPLE, glBindVertexArray", + "UniversalVAO, bindVertexArray, glBindVertexArray", + "UniversalVAO, deleteVertexArrays, glDeleteVertexArrays", + "OpenGlHelper, glBlendFunc, tryBlendFuncSeparate", + "OpenGlHelper, setActiveTexture, setActiveTexture", + "OpenGlHelper, setLightmapTextureCoords, setLightmapTextureCoords", + "OpenGlHelper, isFramebufferEnabled, isFramebufferEnabled", + "GLU, gluPerspective, gluPerspective", + "GLU, gluLookAt, gluLookAt", + "GLU, gluOrtho2D, gluOrtho2D", + "Project, gluPerspective, gluPerspective", + "Project, gluPickMatrix, gluPickMatrix", + }) + void namedClassMethodRedirects(String className, String method, String expected) { + assertEquals(expected, GLRedirects.getTargetMethodName(className + "." + method)); + } + + @ParameterizedTest(name = "{0} -> null") + @CsvSource({ + "GL11.GL_TEXTURE_2D", + "GL11.GL_BLEND", + "GL20.GL_FRAGMENT_SHADER", + "Foo.bar", + "String.valueOf", + "ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB", + }) + void nonRedirectedReturnsNull(String classAndMethod) { + assertNull(GLRedirects.getTargetMethodName(classAndMethod)); + } + + @Test + void nullDotReturnsNull() { + assertNull(GLRedirects.getTargetMethodName("noDotHere")); + } + + @ParameterizedTest(name = "pattern matches {0}") + @CsvSource({ + "GL11.glPushMatrix", + "GL20C.glUseProgram", + "GL44.glBufferStorage", + "ARBShaderObjects.glUseProgramObjectARB", + "OpenGlHelper.setActiveTexture", + "GLU.gluPerspective", + "UniversalVAO.bindVertexArray", + }) + void patternMatchesRedirectedClasses(String input) { + assertTrue(GLRedirects.getMethodRedirectPattern().matcher(input).find(), + "Pattern should match: " + input); + } + + @ParameterizedTest(name = "pattern does not match {0}") + @CsvSource({ + "String.valueOf", + "Math.abs", + "Tessellator.instance", + "System.currentTimeMillis", + }) + void patternDoesNotMatchUnrelatedClasses(String input) { + assertFalse(GLRedirects.getMethodRedirectPattern().matcher(input).find(), + "Pattern should not match: " + input); + } + + @Test + void endToEndScriptTransformation() { + String script = "GL11.glPushMatrix();\nGL11.glTranslatef(1,2,3);\nGL11.glEnable(GL11.GL_BLEND);"; + + String result = GLRedirects.getMethodRedirectPattern().matcher(script).replaceAll(mr -> { + String target = GLRedirects.getTargetMethodName(mr.group(0)); + return target != null ? "GLStateManager." + target : mr.group(0); + }); + + assertTrue(result.contains("GLStateManager.glPushMatrix()"), "glPushMatrix not redirected: " + result); + assertTrue(result.contains("GLStateManager.glTranslatef(1,2,3)"), "glTranslatef not redirected: " + result); + assertTrue(result.contains("GLStateManager.glEnable(GL11.GL_BLEND)"), "glEnable not redirected or GL_BLEND mangled: " + result); + } + + @Test + void patternIsNotNull() { + assertNotNull(GLRedirects.getMethodRedirectPattern()); + } +}