diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index a0dde2164..b5ce42704 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -143,6 +143,52 @@ public class GLStateManager { return Thread.currentThread() == drawableGLHolder; } + /** + * Check if splash screen is complete. + * After splash, there's only one GL context and no locking is needed. + */ + public static boolean isSplashComplete() { + return splashComplete; + } + + /** + * Get the active texture unit for server-side state operations. + * If caching is enabled, returns cached value. + * If caching is disabled (SharedDrawable), queries actual GL state. + */ + public static int getActiveTextureUnitForServerState() { + if (isCachingEnabled()) { + return getActiveTextureUnit(); + } + // Query actual GL state for SharedDrawable context + return GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0; + } + + /** + * Get the texture bound to the current texture unit for server-side state operations. + * If caching is enabled, returns cached value. + * If caching is disabled (SharedDrawable), queries actual GL state. + */ + public static int getBoundTextureForServerState() { + if (isCachingEnabled()) { + return getBoundTexture(); + } + // Query actual GL state for SharedDrawable context + return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + } + + /** + * Get the texture bound to a specific texture unit for server-side state operations. + * If caching is enabled, returns cached value. + * If caching is disabled (SharedDrawable), returns -1 to force operations to proceed + */ + public static int getBoundTextureForServerState(int unit) { + if (isCachingEnabled()) { + return getBoundTexture(unit); + } + return -1; + } + // GLStateManager State Trackers private static final IntStack attribs = new IntArrayList(MAX_ATTRIB_STACK_DEPTH); @@ -770,7 +816,7 @@ public class GLStateManager { case GL11.GL_LIST_MODE -> DisplayListManager.getListMode(); case GL11.GL_MATRIX_MODE -> matrixMode.getMode(); case GL11.GL_SHADE_MODEL -> shadeModelState.getValue(); - case GL11.GL_TEXTURE_BINDING_2D -> getBoundTexture(); + case GL11.GL_TEXTURE_BINDING_2D -> getBoundTextureForServerState(); case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha(); case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb(); case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha(); @@ -1320,11 +1366,11 @@ public class GLStateManager { } } - public static int getBoundTexture() { + private static int getBoundTexture() { return getBoundTexture(activeTextureUnit.getValue()); } - public static int getBoundTexture(int unit) { + private static int getBoundTexture(int unit) { return textures.getTextureUnitBindings(unit).getBinding(); } @@ -1341,21 +1387,21 @@ public class GLStateManager { return; } + if (!isCachingEnabled()) { + GL11.glBindTexture(target, texture); + return; + } + final int activeUnit = GLStateManager.activeTextureUnit.getValue(); final TextureBinding textureUnit = textures.getTextureUnitBindings(activeUnit); final int cachedBinding = textureUnit.getBinding(); - final boolean bypassCache = shouldBypassCache(); - final boolean cacheMatches = cachedBinding == texture; - final boolean willBind = bypassCache || !cacheMatches; - if (willBind) { + if (cachedBinding != texture) { if (!isRecordingDisplayList()) { GL11.glBindTexture(target, texture); } - if (isCachingEnabled()) { - textureUnit.setBinding(texture); - TextureTracker.INSTANCE.onBindTexture(texture); - } + textureUnit.setBinding(texture); + TextureTracker.INSTANCE.onBindTexture(texture); } } @@ -1367,7 +1413,7 @@ public class GLStateManager { TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - RenderSystem.textureImage2D(getBoundTexture(), target, level, internalformat, width, height, border, format, type, pixels); + RenderSystem.textureImage2D(getBoundTextureForServerState(), target, level, internalformat, width, height, border, format, type, pixels); } else { // Non-main thread or proxy texture - use direct GL call GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); @@ -1402,7 +1448,7 @@ public class GLStateManager { TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels != null ? pixels.asIntBuffer() : null); if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - keeps GL binding state unchanged - RenderSystem.textureImage2D(getBoundTexture(), target, level, internalformat, width, height, border, format, type, pixels); + RenderSystem.textureImage2D(getBoundTextureForServerState(), target, level, internalformat, width, height, border, format, type, pixels); } else { // Non-main thread or proxy texture - use direct GL call GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); @@ -2538,7 +2584,7 @@ public class GLStateManager { GL11.glTexParameter(target, pname, params); return; } - if(!updateTexParameteriCache(target, getBoundTexture(), pname, params.get(0))) return; + if(!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, params.get(0))) return; GL11.glTexParameter(target, pname, params); } @@ -2548,7 +2594,7 @@ public class GLStateManager { GL11.glTexParameter(target, pname, params); return; } - if(!updateTexParameterfCache(target, getBoundTexture(), pname, params.get(0))) return; + if(!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, params.get(0))) return; GL11.glTexParameter(target, pname, params); } @@ -2566,7 +2612,7 @@ public class GLStateManager { } return; } - if (!updateTexParameteriCache(target, getBoundTexture(), pname, param)) return; + if (!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, param)) return; // Skip actual GL call during display list recording (state tracking only) if (!isRecordingDisplayList()) { @@ -2609,7 +2655,7 @@ public class GLStateManager { } return; } - if (!updateTexParameterfCache(getActiveTextureUnit(), target, pname, param)) return; + if (!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, param)) return; // Skip actual GL call during display list recording (state tracking only) if (!isRecordingDisplayList()) { @@ -2649,19 +2695,20 @@ public class GLStateManager { if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { return GL11.glGetTexParameteri(target, pname); } - return getTexParameterOrDefault(getBoundTexture(), pname, () -> GL11.glGetTexParameteri(target, pname)); + return getTexParameterOrDefault(getBoundTextureForServerState(), pname, () -> GL11.glGetTexParameteri(target, pname)); } public static float glGetTexParameterf(int target, int pname) { if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { return GL11.glGetTexParameterf(target, pname); } - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTexture()); + final int boundTexture = getBoundTextureForServerState(); + final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(boundTexture); if(info == null) { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexParameterf called during display list recording with no cached TextureInfo for texture %d. " + - "Cannot query OpenGL state during compilation!", getBoundTexture())); + "Cannot query OpenGL state during compilation!", boundTexture)); } return GL11.glGetTexParameterf(target, pname); } @@ -2673,7 +2720,7 @@ public class GLStateManager { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexParameterf called during display list recording with uncached pname 0x%s for texture %d. " + - "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), getBoundTexture())); + "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), boundTexture)); } yield GL11.glGetTexParameterf(target, pname); } @@ -2684,12 +2731,12 @@ public class GLStateManager { if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { return GL11.glGetTexLevelParameteri(target, level, pname); } - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTexture()); + final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState()); if (info == null) { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexLevelParameteri called during display list recording with no cached TextureInfo for texture %d. " + - "Cannot query OpenGL state during compilation!", getBoundTexture())); + "Cannot query OpenGL state during compilation!", getBoundTextureForServerState())); } return GL11.glGetTexLevelParameteri(target, level, pname); } @@ -2701,7 +2748,7 @@ public class GLStateManager { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( "glGetTexLevelParameteri called during display list recording with uncached pname 0x%s for texture %d. " + - "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), getBoundTexture())); + "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), getBoundTextureForServerState())); } yield GL11.glGetTexLevelParameteri(target, level, pname); } @@ -3101,7 +3148,7 @@ public class GLStateManager { } if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - keeps GL binding state unchanged - RenderSystem.textureSubImage2D(getBoundTexture(), target, level, xoffset, yoffset, width, height, format, type, pixels); + RenderSystem.textureSubImage2D(getBoundTextureForServerState(), target, level, xoffset, yoffset, width, height, format, type, pixels); } else { // Non-main thread or proxy texture - use direct GL call GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); @@ -3114,7 +3161,7 @@ public class GLStateManager { } if (shouldUseDSA(target)) { // Use DSA to upload directly to the texture - RenderSystem.textureSubImage2D(getBoundTexture(), target, level, xoffset, yoffset, width, height, format, type, pixels); + RenderSystem.textureSubImage2D(getBoundTextureForServerState(), target, level, xoffset, yoffset, width, height, format, type, pixels); } else { // Non-main thread or proxy texture - use direct GL call GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java index bfeac257d..0f2c21b1b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java @@ -84,7 +84,7 @@ public class DSAARB extends DSAUnsupported { @Override public void bindTextureToUnit(int unit, int texture) { - if(GLStateManager.getBoundTexture(unit) == texture) return; + if(GLStateManager.getBoundTextureForServerState(unit) == texture) return; if (texture == 0) { super.bindTextureToUnit(unit, texture); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java index 8cf66155f..7bb683d71 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java @@ -24,7 +24,7 @@ public class DSAUnsupported implements DSAAccess { @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { // Get what cache thinks is bound - we'll restore to this to keep cache/GL in sync - final int cachedBinding = GLStateManager.getBoundTexture(); + final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); GL11.glBindTexture(target, cachedBinding); // Restore to cache value @@ -32,7 +32,7 @@ public class DSAUnsupported implements DSAAccess { @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { - final int cachedBinding = GLStateManager.getBoundTexture(); + final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); GL11.glBindTexture(target, cachedBinding); @@ -40,7 +40,7 @@ public class DSAUnsupported implements DSAAccess { @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { - final int cachedBinding = GLStateManager.getBoundTexture(); + final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); GL11.glBindTexture(target, cachedBinding); @@ -48,7 +48,7 @@ public class DSAUnsupported implements DSAAccess { @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { - final int cachedBinding = GLStateManager.getBoundTexture(); + final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); GL11.glBindTexture(target, cachedBinding); @@ -92,7 +92,7 @@ public class DSAUnsupported implements DSAAccess { @Override public int getTexLevelParameteri(int texture, int level, int pname) { - final int previous = GLStateManager.getBoundTexture(); + final int previous = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture); final int result = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, pname); GL11.glBindTexture(GL11.GL_TEXTURE_2D, previous); @@ -101,7 +101,7 @@ public class DSAUnsupported implements DSAAccess { @Override public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) { - final int previous = GLStateManager.getBoundTexture(); + final int previous = GLStateManager.getBoundTextureForServerState(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, destTexture); GL11.glCopyTexSubImage2D(target, i, i1, i2, i3, i4, width, height); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java b/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java index a6b18887b..70b05de79 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java @@ -12,7 +12,7 @@ public class TextureInfo { protected int width = -1; protected int height = -1; - @Getter @Setter protected int minFilter = GL11.GL_LINEAR_MIPMAP_LINEAR; + @Getter @Setter protected int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR; @Getter @Setter protected int magFilter = GL11.GL_LINEAR; @Getter @Setter protected int wrapS = GL11.GL_REPEAT; @Getter @Setter protected int wrapT = GL11.GL_REPEAT; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java b/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java index 93f3b7d71..5fa290a80 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java @@ -7,48 +7,73 @@ import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import java.nio.Buffer; +import java.util.concurrent.locks.ReentrantLock; public class TextureInfoCache { /** - * Adapted from Iris for use in GLSM + * Adapted from Iris for use in GLSM. + * + * This cache stores server-side texture state (parameters, dimensions) that is shared across GL contexts. + * Locking is only used during splash when multiple contexts exist. */ - public static final TextureInfoCache INSTANCE = new TextureInfoCache(); + public static final TextureInfoCache INSTANCE = new TextureInfoCache(); - private final Int2ObjectMap cache = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectMap cache = new Int2ObjectOpenHashMap<>(); + private final ReentrantLock lock = new ReentrantLock(); - private TextureInfoCache() { - } + private TextureInfoCache() { + } - public TextureInfo getInfo(int id) { - if(id < 0) return null; - if(!GLStateManager.isCachingEnabled()) { - return new TextureInfo(id); + public TextureInfo getInfo(int id) { + if (id < 0) return null; + + if (GLStateManager.isSplashComplete()) { + return cache.computeIfAbsent(id, TextureInfo::new); } - return cache.computeIfAbsent(id, TextureInfo::new); - } - public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) { - if (target == GL11.GL_TEXTURE_2D && level == 0) { - final TextureInfo info = getInfo(GLStateManager.getBoundTexture()); - if(info == null) return; - info.internalFormat = internalformat; - info.width = width; - info.height = height; - } - } + lock.lock(); + try { + return cache.computeIfAbsent(id, TextureInfo::new); + } finally { + lock.unlock(); + } + } + + public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) { + if (target == GL11.GL_TEXTURE_2D && level == 0) { + final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); + if (info == null) return; + info.internalFormat = internalformat; + info.width = width; + info.height = height; + } + } + public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) { - if (target == GL11.GL_TEXTURE_2D && level == 0) { - final TextureInfo info = getInfo(GLStateManager.getBoundTexture()); - if(info == null) return; - info.internalFormat = internalformat; - info.width = width; - info.height = height; - } - } + if (target == GL11.GL_TEXTURE_2D && level == 0) { + final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); + if (info == null) return; + info.internalFormat = internalformat; + info.width = width; + info.height = height; + } + } - public void onDeleteTexture(int id) { - if(id >= 0) cache.remove(id); - } + public void onDeleteTexture(int id) { + if (id < 0) return; + if (GLStateManager.isSplashComplete()) { + cache.remove(id); + return; + } + + // During splash: lock for thread safety + lock.lock(); + try { + cache.remove(id); + } finally { + lock.unlock(); + } + } } diff --git a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java index 6cb74b6b0..0333931bc 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java @@ -72,7 +72,7 @@ public final class CommonUniforms { // TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform, // but we do. How will custom uniforms depending on atlasSize work? uniforms.uniform2i("atlasSize", () -> { - final int glId = GLStateManager.getBoundTexture(); + final int glId = GLStateManager.getBoundTextureForServerState(); final AbstractTexture texture = TextureTracker.INSTANCE.getTexture(glId); if (texture instanceof TextureMap) { @@ -84,7 +84,7 @@ public final class CommonUniforms { }, StateUpdateNotifiers.bindTextureNotifier); uniforms.uniform2i("gtextureSize", () -> { - final int glId = GLStateManager.getBoundTexture(); + final int glId = GLStateManager.getBoundTextureForServerState(); final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(glId); return new Vector2i(info.getWidth(), info.getHeight()); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderGlobal_DestroyBlock.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderGlobal_DestroyBlock.java index d14e5c50f..c9c5bcd4b 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderGlobal_DestroyBlock.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderGlobal_DestroyBlock.java @@ -21,7 +21,7 @@ public class MixinRenderGlobal_DestroyBlock { at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/Tessellator;startDrawingQuads()V") ) private void iris$beginDrawBlockDamageTexture(Tessellator tessellator, EntityLivingBase entity, float partialTicks, CallbackInfo ci, @Share("lastMin") LocalIntRef lastMin, @Share("lastMag") LocalIntRef lastMag) { - TextureInfo info = TextureInfoCache.INSTANCE.getInfo(GLStateManager.getBoundTexture()); + TextureInfo info = TextureInfoCache.INSTANCE.getInfo(GLStateManager.getBoundTextureForServerState()); lastMin.set(info.getMinFilter()); lastMag.set(info.getMagFilter()); GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java new file mode 100644 index 000000000..6954bb317 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java @@ -0,0 +1,475 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.AngelicaExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.LWJGLException; +import org.lwjgl.opengl.Display; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.SharedDrawable; + +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests for server-side GL state synchronization between SharedDrawable and DrawableGL contexts. + * + * Server-side state (texture parameters, texture data) is shared across GL contexts and must + * be properly synchronized in the GLSM cache. Client-side state (texture bindings, active unit) + * is per-context and should NOT be shared. + */ +@ExtendWith(AngelicaExtension.class) +public class GLSM_ServerSideState_UnitTest { + + private SharedDrawable sharedDrawable; + private Thread backgroundThread; + private CountDownLatch initLatch; + private CountDownLatch commandLatch; + private CountDownLatch completeLatch; + private CountDownLatch readyLatch; + private Runnable pendingCommand; + private Throwable backgroundError; + private volatile boolean shutdownRequested; + private boolean originalSplashComplete; + + private static void setSplashComplete(boolean value) throws Exception { + final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete"); + splashCompleteField.setAccessible(true); + splashCompleteField.setBoolean(null, value); + } + + private static boolean getSplashComplete() throws Exception { + final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete"); + splashCompleteField.setAccessible(true); + return splashCompleteField.getBoolean(null); + } + + @BeforeEach + void setupSharedDrawable() throws Exception { + originalSplashComplete = getSplashComplete(); + + // Reset splash state to simulate splash screen scenario + setSplashComplete(false); + + sharedDrawable = new SharedDrawable(Display.getDrawable()); + + // Register the sharedDrawable so makeCurrent() can detect it + GLStateManager.setSharedDrawable(sharedDrawable); + + // Main thread holds DrawableGL, so enable caching for it: This sets drawableGLHolder = current thread + GLStateManager.setCachingEnabled(true); + + // Verify main thread has caching enabled + assertTrue(GLStateManager.isCachingEnabled(), "Main thread should have caching enabled (it holds DrawableGL)"); + + shutdownRequested = false; + backgroundError = null; + initLatch = new CountDownLatch(1); + commandLatch = new CountDownLatch(1); + completeLatch = new CountDownLatch(1); + readyLatch = new CountDownLatch(1); + + backgroundThread = new Thread(() -> { + try { + GLStateManager.makeCurrent(sharedDrawable); + + if (GLStateManager.isCachingEnabled()) { + throw new AssertionError("SharedDrawable thread should have caching DISABLED"); + } + + // Signal that initialization is complete + initLatch.countDown(); + + while (!shutdownRequested) { + // Signal ready for next command + readyLatch.countDown(); + + // Wait for a command + if (commandLatch.await(100, TimeUnit.MILLISECONDS)) { + if (pendingCommand != null && !shutdownRequested) { + try { + pendingCommand.run(); + } catch (Throwable t) { + backgroundError = t; + } + pendingCommand = null; + } + completeLatch.countDown(); + } + } + } catch (InterruptedException e) { + // Normal shutdown + } catch (LWJGLException e) { + backgroundError = e; + } finally { + try { + sharedDrawable.releaseContext(); + } catch (LWJGLException e) { + // Ignore on cleanup + } + } + }, "SharedDrawable-Test-Thread"); + backgroundThread.start(); + + // Wait for background thread to complete initialization + assertTrue(initLatch.await(5, TimeUnit.SECONDS), "Background thread failed to initialize"); + } + + @AfterEach + void teardownSharedDrawable() throws Exception { + shutdownRequested = true; + commandLatch.countDown(); // Wake up the thread if waiting + + if (backgroundThread != null) { + backgroundThread.join(1000); + if (backgroundThread.isAlive()) { + backgroundThread.interrupt(); + backgroundThread.join(1000); + } + } + + if (sharedDrawable != null) { + sharedDrawable.destroy(); + } + + // Restore original state + GLStateManager.setSharedDrawable(null); + setSplashComplete(originalSplashComplete); + if (originalSplashComplete) { + GLStateManager.markSplashComplete(); + } + } + + /** + * Execute a command on the SharedDrawable thread and wait for completion. + */ + private void executeOnSharedDrawable(Runnable command) throws InterruptedException { + // Wait for background thread to be ready for a command + assertTrue(readyLatch.await(5, TimeUnit.SECONDS), "Background thread not ready"); + + // Reset latches for this command cycle + readyLatch = new CountDownLatch(1); + commandLatch = new CountDownLatch(1); + completeLatch = new CountDownLatch(1); + + // Set command and signal + pendingCommand = command; + commandLatch.countDown(); + + // Wait for completion + assertTrue(completeLatch.await(5, TimeUnit.SECONDS), "SharedDrawable command timed out"); + + if (backgroundError != null) { + fail("Background thread error: " + backgroundError.getMessage(), backgroundError); + } + } + + /** + * Diagnostic test: Verify that SharedDrawable actually shares GL namespace with Display. + * This is a prerequisite for all other tests - if sharing doesn't work, texture params won't be shared. + */ + @Test + void testContextSharingVerification() throws InterruptedException { + int texMain = GL11.glGenTextures(); + + assertTrue(GLStateManager.isCachingEnabled(), "Main thread should have caching enabled (it holds DrawableGL)"); + + final int[] sharedResult = new int[1]; + executeOnSharedDrawable(() -> { + GL11.glGetError(); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, texMain); + GL11.glGetError(); + sharedResult[0] = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + }); + + assertEquals(texMain, sharedResult[0], "SharedDrawable should be able to bind texture created on main thread - contexts must share GL namespace"); + + final int[] texShared = new int[1]; + executeOnSharedDrawable(() -> texShared[0] = GL11.glGenTextures()); + + GL11.glGetError(); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, texShared[0]); + GL11.glGetError(); + int mainBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + + assertEquals(texShared[0], mainBinding, "Main thread should be able to bind texture created on SharedDrawable - contexts must share GL namespace"); + + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GL11.glDeleteTextures(texMain); + GL11.glDeleteTextures(texShared[0]); + } + + /** + * Test: SharedDrawable sets texture MIN_FILTER, verify both GLSM and actual GL state are correct on both contexts. + */ + @Test + void testTexParameterFromSharedDrawable() throws InterruptedException { + int texId = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + + int initialGLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR, initialGLSM, "Initial GLSM should be GL_LINEAR"); + + int initialGL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR, initialGL, "Initial GL should be GL_LINEAR"); + + // SharedDrawable: bind and change params to GL_NEAREST via GLSM + executeOnSharedDrawable(() -> { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + int boundTex = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + assertEquals(texId, boundTex, "SharedDrawable should have texId bound"); + + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + + int glsmValue = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, glsmValue, "SharedDrawable GLSM should return GL_NEAREST"); + + int glValue = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, glValue, "SharedDrawable GL should be GL_NEAREST"); + }); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + int mainGLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, mainGLSM, "Main thread GLSM should return GL_NEAREST"); + + int mainGL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, mainGL, "Main thread GL should be GL_NEAREST"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texId); + } + } + + /** + * Test: SharedDrawable binds a DIFFERENT texture than main thread, then sets params. + * + * This verifies that when SharedDrawable sets params on texIdA while main thread has texIdB bound, the params go to the correct texture (texIdA). + */ + @Test + void testWrongTextureUpdatedFromSharedDrawable() throws InterruptedException { + int texIdA = GL11.glGenTextures(); + int texIdB = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA); + int initialA_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + int initialA_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR, initialA_GLSM, "texIdA initial GLSM should be LINEAR"); + assertEquals(GL11.GL_LINEAR, initialA_GL, "texIdA initial GL should be LINEAR"); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB); + int initialB_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + int initialB_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, initialB_GLSM, "texIdB initial GLSM should be LINEAR_MIPMAP_LINEAR"); + assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, initialB_GL, "texIdB initial GL should be LINEAR_MIPMAP_LINEAR"); + + assertEquals(texIdB, GLStateManager.getBoundTextureForServerState(), "Main thread should have texIdB bound"); + + // SharedDrawable: bind texIdA and change its MIN_FILTER to NEAREST + // Main thread has texIdB bound, but SharedDrawable should correctly update texIdA's params, not texIdB's + executeOnSharedDrawable(() -> { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA); + + int bound = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + assertEquals(texIdA, bound, "SharedDrawable should have texIdA bound"); + + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + + int glsmValue = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, glsmValue, "SharedDrawable GLSM should return NEAREST for texIdA"); + + int glValue = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, glValue, "SharedDrawable GL should be NEAREST for texIdA"); + }); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA); + int finalA_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + int finalA_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_NEAREST, finalA_GLSM, "texIdA final GLSM should be NEAREST (SharedDrawable's update)"); + assertEquals(GL11.GL_NEAREST, finalA_GL, "texIdA final GL should be NEAREST"); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB); + int finalB_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + int finalB_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, finalB_GLSM, "texIdB should NOT be modified by SharedDrawable"); + assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, finalB_GL, "texIdB GL should NOT be modified"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texIdA); + GLStateManager.glDeleteTextures(texIdB); + } + } + + /** + * Test that client-side state (texture binding) is correctly separate between contexts. Each context should have its own binding cache. + */ + @Test + void testClientStateSeparation() throws InterruptedException { + int texId1 = GL11.glGenTextures(); + int texId2 = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId1); + assertEquals(texId1, GLStateManager.getBoundTextureForServerState(), "Main thread cache should show texId1 bound"); + + executeOnSharedDrawable(() -> GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId2)); + + assertEquals(texId1, GLStateManager.getBoundTextureForServerState(), "Main thread cache should still show texId1 (client-side state is per-context)"); + + int actualBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + assertEquals(texId1, actualBinding, "Main thread actual GL binding should still be texId1"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texId1); + GLStateManager.glDeleteTextures(texId2); + } + } + + /** + * Test glTexParameterf (float parameters like LOD_BIAS). + */ + @Test + void testTexParameterfFromSharedDrawable() throws InterruptedException { + int texId = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0f); + + float initialGLSM = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + float initialGL = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + assertEquals(0.0f, initialGLSM, 0.001f, "Initial GLSM LOD_BIAS should be 0.0"); + assertEquals(0.0f, initialGL, 0.001f, "Initial GL LOD_BIAS should be 0.0"); + + // SharedDrawable: change LOD_BIAS + executeOnSharedDrawable(() -> { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + int bound = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + assertEquals(texId, bound, "SharedDrawable should have texId bound"); + + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 1.5f); + + float glsmValue = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + assertEquals(1.5f, glsmValue, 0.001f, "SharedDrawable GLSM should return 1.5"); + float glValue = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + assertEquals(1.5f, glValue, 0.001f, "SharedDrawable GL should be 1.5"); + }); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + float finalGLSM = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + float finalGL = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS); + assertEquals(1.5f, finalGLSM, 0.001f, "Main thread GLSM should return 1.5"); + assertEquals(1.5f, finalGL, 0.001f, "Main thread GL should be 1.5"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texId); + } + } + + /** + * Test glTexImage2D: SharedDrawable uploads texture data, verify dimensions cached correctly. + */ + @Test + void testTexImage2DFromSharedDrawable() throws InterruptedException { + int texId = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); + + int initialWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + int initialHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + assertEquals(64, initialWidth, "Initial width should be 64"); + assertEquals(64, initialHeight, "Initial height should be 64"); + + // SharedDrawable: re-upload with different dimensions + executeOnSharedDrawable(() -> { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 128, 256, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); + + int sharedWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + int sharedHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + assertEquals(128, sharedWidth, "SharedDrawable GLSM width should be 128"); + assertEquals(256, sharedHeight, "SharedDrawable GLSM height should be 256"); + + int glWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + int glHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + assertEquals(128, glWidth, "SharedDrawable GL width should be 128"); + assertEquals(256, glHeight, "SharedDrawable GL height should be 256"); + }); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + int finalWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + int finalHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + assertEquals(128, finalWidth, "Main thread GLSM width should be 128"); + assertEquals(256, finalHeight, "Main thread GLSM height should be 256"); + + int glWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + int glHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + assertEquals(128, glWidth, "Main thread GL width should be 128"); + assertEquals(256, glHeight, "Main thread GL height should be 256"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texId); + } + } + + /** + * Test glDeleteTextures: SharedDrawable deletes texture, verify cache cleared. + */ + @Test + void testDeleteTexturesFromSharedDrawable() throws InterruptedException { + int texId = GL11.glGenTextures(); + + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 32, 32, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); + + int cachedFilter = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + assertEquals(GL11.GL_LINEAR, cachedFilter, "Cache should have LINEAR before delete"); + + assertTrue(GL11.glIsTexture(texId), "Texture should exist before delete"); + + // SharedDrawable: delete the texture + executeOnSharedDrawable(() -> { + GLStateManager.glDeleteTextures(texId); + assertFalse(GL11.glIsTexture(texId), "Texture should not exist after SharedDrawable delete"); + }); + + assertFalse(GL11.glIsTexture(texId), "Texture should not exist on main thread after SharedDrawable delete"); + + } finally { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + if (GL11.glIsTexture(texId)) { + GLStateManager.glDeleteTextures(texId); + } + } + } +}