From 1772e9eae2923ce539af69bdb27e025f138fd31c Mon Sep 17 00:00:00 2001 From: Eclipse-Sol Date: Sun, 25 Oct 2026 22:25:54 -0400 Subject: [PATCH] Mipmap stuff again (#2300) --- .../angelica/glsm/GLStateManager.java | 17 +- .../angelica/glsm/RenderSystem.java | 11 +- .../glsm/backend/VertexWriteReplaySetup.java | 5 +- .../glsm/states/SamplerUnitArray.java | 17 +- .../glsm/GLSM_SamplerBinding_GLTest.java | 53 +++ .../sdlgpu/compute/VertexWriteReplayer.java | 12 +- .../angelica/common/BlockError.java | 3 +- .../gtnewhorizons/angelica/mixins/Mixins.java | 7 + .../interfaces/TextureMetadataExtension.java | 4 + .../angelica/proxy/ClientProxy.java | 2 + .../render/EmissiveTextureAutoloader.java | 3 +- .../angelica/rendering/TextureAtlasType.java | 8 + .../angelica/rendering/TextureSamplers.java | 32 ++ .../celeritas/AngelicaChunkRenderer.java | 135 +++----- .../AngelicaRenderPassConfiguration.java | 30 +- .../rendering/celeritas/SpriteExtension.java | 6 +- .../celeritas/api/IrisShaderProvider.java | 2 +- .../particles/ParticleAlphaCutoff.java | 20 ++ .../utils/CeleritasMipmapGenerator.java | 230 +++++++++++++ .../angelica/utils/MipmapGenerator.java | 261 ++------------ .../angelica/utils/MipmapStrategies.java | 5 +- .../angelica/utils/ModernMipmapBlender.java | 77 +++++ .../angelica/utils/ModernMipmapGenerator.java | 238 +++++++++++++ .../utils/VanillaMipmapGenerator.java | 97 ++++++ .../client/gui/SodiumGameOptionPages.java | 10 +- .../sodium/client/gui/SodiumGameOptions.java | 9 +- .../gui/options/named/MipmapGeneration.java | 33 ++ .../BlockRenderingSettings.java | 5 + .../IrisCeleritasChunkProgramOverrides.java | 30 +- .../IrisCeleritasChunkShaderInterface.java | 15 +- .../IrisCeleritasShaderProvider.java | 2 +- .../iris/celeritas/IrisTerrainPass.java | 4 +- .../iris/gl/program/ComputeProgram.java | 1 + .../iris/gl/program/ProgramBuilder.java | 7 +- .../iris/gl/program/ProgramSamplers.java | 94 ++--- .../coderbot/iris/gl/sampler/GlSampler.java | 20 +- .../iris/gl/sampler/SamplerBinding.java | 9 +- .../iris/gl/sampler/SamplerHolder.java | 7 +- .../DeferredWorldRenderingPipeline.java | 32 +- .../FixedFunctionWorldRenderingPipeline.java | 1 + .../iris/pipeline/VertexWriteReplays.java | 13 +- .../coderbot/iris/samplers/IrisSamplers.java | 49 ++- .../iris/shaderpack/PackDirectives.java | 7 + .../iris/shaderpack/ShaderProperties.java | 2 + .../iris/texture/pbr/PBRAtlasTexture.java | 2 +- .../resources/assets/angelica/lang/en_US.lang | 5 + .../textures/MixinRenderItem_GuiSampler.java | 33 ++ .../features/mipmaps/MixinEffectRenderer.java | 19 ++ .../mipmaps/MixinTextureAtlasSprite.java | 210 ++++++++++-- .../mipmaps/MixinTextureMetadataSection.java | 13 + ...MixinTextureMetadataSectionSerializer.java | 14 +- .../features/textures/MixinTextureMap.java | 40 ++- ...rottleableEffectRenderer_MipmapCutoff.java | 21 ++ .../celeritas/ChunkPassCleanupTest.java | 89 +++++ .../pipeline/PbrSamplerBindingGLTest.java | 323 ++++++++++++++++++ .../shaders/pbrSamplerBindingTest.fsh | 7 + 56 files changed, 1872 insertions(+), 529 deletions(-) create mode 100644 src/main/java/com/gtnewhorizons/angelica/rendering/TextureAtlasType.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/rendering/TextureSamplers.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleAlphaCutoff.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/utils/CeleritasMipmapGenerator.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapBlender.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapGenerator.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/utils/VanillaMipmapGenerator.java create mode 100644 src/main/java/me/jellysquid/mods/sodium/client/gui/options/named/MipmapGeneration.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinRenderItem_GuiSampler.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinEffectRenderer.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_MipmapCutoff.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/ChunkPassCleanupTest.java create mode 100644 src/test/java/net/coderbot/iris/pipeline/PbrSamplerBindingGLTest.java create mode 100644 src/test/resources/assets/angelica/shaders/pbrSamplerBindingTest.fsh 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 e7ccbb223..2c0dbd2e5 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -5333,7 +5333,7 @@ public class GLStateManager { RENDER_BACKEND.frontFace(glCtx.polygonState.getFrontFace()); final SamplerUnitArray samplerUnits = glCtx.samplerUnits; - for (int i = 0; i < samplerUnits.size(); i++) { + for (int i = 0; i <= samplerUnits.getHighestBoundUnit(); i++) { final int sampler = samplerUnits.get(i); if (sampler != 0) RENDER_BACKEND.bindSampler(i, sampler); } @@ -6460,8 +6460,11 @@ public class GLStateManager { } public static void glBindSampler(int unit, int sampler) { + bindSampler(ctx().samplerUnits, unit, sampler); + } + + private static void bindSampler(SamplerUnitArray units, int unit, int sampler) { rejectExitCapture(); - final SamplerUnitArray units = ctx().samplerUnits; if (isCachingEnabled() && unit >= 0 && unit < units.size() && units.get(unit) == sampler) return; beforeUncapturedStateChange(); if (!units.set(unit, sampler)) { @@ -6470,6 +6473,16 @@ public class GLStateManager { RENDER_BACKEND.bindSampler(unit, sampler); } + public static void unbindAllSamplers() { + final SamplerUnitArray units = ctx().samplerUnits; + if (units.getHighestBoundUnit() < 0) return; + beforeUncapturedStateChange(); + for (int unit = units.getHighestBoundUnit(); unit >= 0; unit = units.getHighestBoundUnit()) { + units.set(unit, 0); + RENDER_BACKEND.bindSampler(unit, 0); + } + } + public static void glBindSamplers(int first, int count, IntBuffer samplers) { if (samplers == null) { for (int i = 0; i < count; i++) glBindSampler(first + i, 0); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java index 1159e1285..170d1dcd7 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java @@ -158,8 +158,8 @@ public class RenderSystem { maxSSBOBindings = 0; } - // Check for sampler objects support (GL 3.3+ or ARB extension) - supportsSamplerObjects = GLStateManager.capabilities.OpenGL33 || GLStateManager.capabilities.GL_ARB_sampler_objects; + supportsSamplerObjects = isGLES ? glesVersion >= 300 + : GLStateManager.capabilities.OpenGL33 || GLStateManager.capabilities.GL_ARB_sampler_objects; if (supportsSamplerObjects) { maxCombinedTextureImageUnits = RENDER_BACKEND.getInteger(GL20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS); } @@ -713,12 +713,7 @@ public class RenderSystem { public static void unbindAllSamplers() { if (!supportsSamplerObjects) return; - final int count = GLStateManager.getSamplerUnitCount(); - for (int i = 0; i < count; i++) { - if (GLStateManager.getSamplerBinding(i) != 0) { - GLStateManager.glBindSampler(i, 0); - } - } + GLStateManager.unbindAllSamplers(); } /** Parse a GL version string (e.g. "4.6.0 NVIDIA ...") into concatenated digits "460". Strips diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/VertexWriteReplaySetup.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/VertexWriteReplaySetup.java index 118be84d4..4b8dcda41 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/VertexWriteReplaySetup.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/VertexWriteReplaySetup.java @@ -11,13 +11,14 @@ import java.util.function.IntSupplier; * @param samplerNames samplers the graphics program may not have, because only the stripped writes read them * @param samplerUnits per sampler name, the texture unit it reads at each draw, or -1 to use samplerTextures * @param samplerTextures per sampler name, its texture when samplerUnits is -1 - * @param samplerObjects per sampler name, the GL sampler object to sample it with when samplerUnits is -1, or 0 + * @param samplerObjects per sampler name, supplies its current GL sampler object when samplerUnits is -1; + * null for unassigned or external bindings, and returns 0 to use the texture's own filtering * @param vertexBufferBinding storage buffer binding of the first vertex buffer the replay program declares * @param vertexBufferCount how many vertex buffers it declares, at consecutive bindings * @param indexBufferBinding storage buffer binding of its index buffer */ public record VertexWriteReplaySetup(int replayProgram, String[] inputNames, int[] inputLocations, IntSupplier[] images, int writtenImageCount, - String[] samplerNames, int[] samplerUnits, IntSupplier[] samplerTextures, int[] samplerObjects, + String[] samplerNames, int[] samplerUnits, IntSupplier[] samplerTextures, IntSupplier[] samplerObjects, int vertexBufferBinding, int vertexBufferCount, int indexBufferBinding) { } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/SamplerUnitArray.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/SamplerUnitArray.java index fbce0fc53..8500b8a03 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/SamplerUnitArray.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/SamplerUnitArray.java @@ -1,12 +1,15 @@ package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import lombok.Getter; public class SamplerUnitArray { private static final int MIN_UNITS = 16; private int[] samplers; + @Getter + private int highestBoundUnit = -1; public int get(int unit) { final int[] local = samplers; @@ -22,15 +25,27 @@ public class SamplerUnitArray { } if (unit >= local.length) return false; local[unit] = sampler; + if (sampler != 0) { + highestBoundUnit = Math.max(highestBoundUnit, unit); + } else if (unit == highestBoundUnit) { + trimUnboundUnits(); + } return true; } public void unbindEverywhere(int sampler) { final int[] local = samplers; if (local == null) return; - for (int i = 0; i < local.length; i++) { + for (int i = 0; i <= highestBoundUnit; i++) { if (local[i] == sampler) local[i] = 0; } + trimUnboundUnits(); + } + + private void trimUnboundUnits() { + while (highestBoundUnit >= 0 && samplers[highestBoundUnit] == 0) { + highestBoundUnit--; + } } public int size() { diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SamplerBinding_GLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SamplerBinding_GLTest.java index ed5b2fa8c..dd732c800 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SamplerBinding_GLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SamplerBinding_GLTest.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm; +import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,6 +11,7 @@ import org.lwjgl.opengl.GL33; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -115,37 +117,88 @@ class GLSM_SamplerBinding_GLTest { @Test void unbindAllSamplersClearsUnitsBoundThroughGlsm() { final int sampler = RenderSystem.genSampler(); + final Runnable previousFlush = BatchStateGuard.flush; + final AtomicInteger flushes = new AtomicInteger(); try { GLStateManager.glBindSampler(1, sampler); GLStateManager.glBindSampler(3, sampler); + BatchStateGuard.flush = () -> { + assertEquals(sampler, driverBinding(1), "deferred draws must see the original bindings"); + assertEquals(sampler, driverBinding(3), "deferred draws must see the original bindings"); + flushes.incrementAndGet(); + }; + RenderSystem.unbindAllSamplers(); RenderSystem.unbindAllSamplers(); + assertEquals(1, flushes.get(), "bulk unbind should drain deferred draws once"); assertEquals(0, driverBinding(1), "unit 1 still bound on the driver"); assertEquals(0, driverBinding(3), "unit 3 still bound on the driver"); assertEquals(0, GLStateManager.getSamplerBinding(1)); assertEquals(0, GLStateManager.getSamplerBinding(3)); } finally { + BatchStateGuard.flush = previousFlush; RenderSystem.destroySampler(sampler); } } @Test void replayForwardsCachedSamplerBindings() { + final int highUnit = RenderSystem.getMaxCombinedTextureImageUnits() - 1; final int sampler = RenderSystem.genSampler(); try { GLStateManager.glBindSampler(2, sampler); + GLStateManager.glBindSampler(highUnit, sampler); GL33.glBindSampler(2, 0); + GL33.glBindSampler(highUnit, 0); assertEquals(0, driverBinding(2), "setup failed to diverge the driver"); + assertEquals(0, driverBinding(highUnit), "setup failed to diverge the driver"); GLStateManager.replayStateToBackend(); assertEquals(sampler, driverBinding(2), "replay dropped a cached sampler binding"); + assertEquals(sampler, driverBinding(highUnit), "replay skipped the highest bound unit"); } finally { RenderSystem.destroySampler(sampler); } } + @Test + void sparseBindingsKeepTheCleanupLimitAccurateAfterUnbindAndDeletion() { + final int highUnit = RenderSystem.getMaxCombinedTextureImageUnits() - 1; + final int low = RenderSystem.genSampler(); + final int high = RenderSystem.genSampler(); + try { + GLStateManager.glBindSampler(1, low); + GLStateManager.glBindSampler(3, high); + GLStateManager.glBindSampler(highUnit, high); + assertEquals(highUnit, GLStateManager.ctx().samplerUnits.getHighestBoundUnit()); + + GLStateManager.glBindSampler(highUnit, 0); + assertEquals(3, GLStateManager.ctx().samplerUnits.getHighestBoundUnit()); + assertEquals(0, driverBinding(highUnit)); + + GLStateManager.glBindSampler(highUnit, high); + RenderSystem.destroySampler(high); + assertEquals(1, GLStateManager.ctx().samplerUnits.getHighestBoundUnit()); + assertEquals(0, driverBinding(highUnit)); + assertEquals(0, driverBinding(3)); + + RenderSystem.unbindAllSamplers(); + assertEquals(-1, GLStateManager.ctx().samplerUnits.getHighestBoundUnit()); + assertEquals(0, driverBinding(1)); + + GLStateManager.glBindSampler(highUnit, low); + RenderSystem.unbindAllSamplers(); + RenderSystem.unbindAllSamplers(); + assertEquals(-1, GLStateManager.ctx().samplerUnits.getHighestBoundUnit()); + assertEquals(0, driverBinding(highUnit)); + } finally { + RenderSystem.destroySampler(low); + RenderSystem.destroySampler(high); + } + } + @Test void intBufferGenFillsFromPositionWithBindableSamplers() { final IntBuffer buf = ints(-1, 0, 0); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VertexWriteReplayer.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VertexWriteReplayer.java index f22ed30ae..1b7b096c8 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VertexWriteReplayer.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VertexWriteReplayer.java @@ -47,7 +47,6 @@ public final class VertexWriteReplayer { private static final int MAX_DIVISOR = 0xFFFF; private static final int UNCHANGED = -1; private static final int TEXTURE_UNITS = 32; - private static final int SAMPLER_OBJECT_OF_DRAW = -1; public static final class Replay { final int replayProgram; @@ -60,7 +59,7 @@ public final class VertexWriteReplayer { int[] uniformTargets; int[] samplerUnits; IntSupplier[] samplerSources; - int[] samplerObjects; + IntSupplier[] samplerObjects; int[] packStorageSlots; int[] packRwStorageSlots; int[] uniformBlockIndices; @@ -143,7 +142,7 @@ public final class VertexWriteReplayer { private void resolveSamplers(ShaderManager.ProgramObject graphics, ShaderManager.ProgramObject replay, List names) { final IntArrayList units = new IntArrayList(); final List sources = new ArrayList<>(); - final IntArrayList objects = new IntArrayList(); + final List objects = new ArrayList<>(); final IntArrayList ownTextureIndices = new IntArrayList(); final List ownTextureNames = new ArrayList<>(); final List pipelineNames = Arrays.asList(setup.samplerNames()); @@ -164,7 +163,7 @@ public final class VertexWriteReplayer { if (!units.contains(unit)) { units.add(unit); sources.add(null); - objects.add(SAMPLER_OBJECT_OF_DRAW); + objects.add(null); } } int free = TEXTURE_UNITS - 1; @@ -179,7 +178,7 @@ public final class VertexWriteReplayer { } samplerUnits = units.toIntArray(); samplerSources = sources.toArray(new IntSupplier[0]); - samplerObjects = objects.toIntArray(); + samplerObjects = objects.toArray(new IntSupplier[0]); } } @@ -306,7 +305,8 @@ public final class VertexWriteReplayer { final int unit = replay.samplerUnits[i]; final IntSupplier source = replay.samplerSources[i]; c.samplerTextures[i] = source != null ? source.getAsInt() : st.boundTextures[unit]; - final int samplerObject = replay.samplerObjects[i] != SAMPLER_OBJECT_OF_DRAW ? replay.samplerObjects[i] : st.boundSamplerObjects[unit]; + final IntSupplier sampler = replay.samplerObjects[i]; + final int samplerObject = sampler != null ? sampler.getAsInt() : st.boundSamplerObjects[unit]; c.samplerHandles[i] = computeBinder.samplerHandle(samplerObject, c.samplerTextures[i]); } if (c.imageTextures.length != images.length) c.imageTextures = new int[images.length]; diff --git a/src/main/java/com/gtnewhorizons/angelica/common/BlockError.java b/src/main/java/com/gtnewhorizons/angelica/common/BlockError.java index 0038562a6..808fc2fe9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/common/BlockError.java +++ b/src/main/java/com/gtnewhorizons/angelica/common/BlockError.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.common; +import com.gtnewhorizons.angelica.rendering.TextureAtlasType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; @@ -39,7 +40,7 @@ public class BlockError extends Block { @SubscribeEvent @SideOnly(Side.CLIENT) public void onTextureStitch(TextureStitchEvent.Pre event) { - if (event.map.getTextureType() == 0) { + if (event.map.getTextureType() == TextureAtlasType.BLOCK) { for (int i = 0; i < icons.length; i++) { icons[i] = event.map.registerIcon("angelica:error_block_" + i); } diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 07cbd6de0..efd8e1ecf 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -73,6 +73,7 @@ public enum Mixins implements IMixins { , "angelica.textures.MixinRenderItem_GuiSupersampling" , "angelica.textures.MixinTileEntityRendererDispatcher_GuiSupersampling" , "angelica.gui.MixinGuiIngameForge_ModernF3" + , "angelica.textures.MixinRenderItem_GuiSampler" ) ), @@ -456,6 +457,7 @@ public enum Mixins implements IMixins { , "celeritas.frustum.MixinClippingHelperImpl" , "celeritas.frustum.MixinFrustrum" , "celeritas.features.culling.MixinEffectRenderer" + , "celeritas.features.mipmaps.MixinEffectRenderer" , "celeritas.features.mipmaps.MixinTextureAtlasSprite" , "celeritas.features.mipmaps.MixinTextureMetadataSection" , "celeritas.features.mipmaps.MixinTextureMetadataSectionSerializer" @@ -894,6 +896,11 @@ public enum Mixins implements IMixins { .setApplyIf(() -> AngelicaConfig.enableIris) .addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer") ), + DRAGONAPI_PARTICLE_CUTOFF(new MixinBuilder("Modern 26.2 mipmap alpha cutoff for DragonAPI's terrain particles") + .setPhase(Phase.LATE) + .addRequiredMod(TargetedMod.DRAGON_API) + .addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer_MipmapCutoff") + ), DRAGONAPI_PARTICLE_BATCH(new MixinBuilder("Particle instancing for DragonAPI's replacement particle renderer") .setPhase(Phase.LATE) .addRequiredMod(TargetedMod.DRAGON_API) diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/TextureMetadataExtension.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/TextureMetadataExtension.java index ecdec33bc..079fd0d26 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/TextureMetadataExtension.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/TextureMetadataExtension.java @@ -7,4 +7,8 @@ public interface TextureMetadataExtension { void angelica$setMipmapStrategy(MipmapStrategy strategy); MipmapStrategy angelica$getMipmapStrategy(); + + void angelica$setAlphaCutoffBias(float bias); + + float angelica$getAlphaCutoffBias(); } diff --git a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java index 8a81ff5ed..01b846400 100644 --- a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java +++ b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java @@ -79,6 +79,7 @@ import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry; import com.gtnewhorizons.angelica.rendering.FpsReducer; import com.gtnewhorizons.angelica.rendering.FramePacer; import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer; +import com.gtnewhorizons.angelica.rendering.TextureSamplers; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; @@ -169,6 +170,7 @@ public final class ClientProxy extends CommonProxy { HUDCaching.init(); } CeleritasSetup.ensureInitialized(); + TextureSamplers.initRenderer(); DarkModeUtils.init(); final SodiumGameOptions opts = options(); if (opts.advanced.vsyncMode == null) { diff --git a/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java b/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java index 5897efd79..45729b705 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.render; +import com.gtnewhorizons.angelica.rendering.TextureAtlasType; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -22,7 +23,7 @@ public class EmissiveTextureAutoloader { @SubscribeEvent public void onTextureStitchPre(TextureStitchEvent.Pre event) { - if (event.map.getTextureType() != 0) return; + if (event.map.getTextureType() != TextureAtlasType.BLOCK) return; TextureMap map = event.map; EmissiveTextureHelper.clearCache(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/TextureAtlasType.java b/src/main/java/com/gtnewhorizons/angelica/rendering/TextureAtlasType.java new file mode 100644 index 000000000..df69d98b6 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/TextureAtlasType.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.rendering; + +public final class TextureAtlasType { + public static final int BLOCK = 0; + public static final int ITEM = 1; + + private TextureAtlasType() {} +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/TextureSamplers.java b/src/main/java/com/gtnewhorizons/angelica/rendering/TextureSamplers.java new file mode 100644 index 000000000..6feed53a0 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/TextureSamplers.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.rendering; + +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import lombok.Getter; +import net.coderbot.iris.gl.sampler.GlSampler; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; + +public final class TextureSamplers { + private static final GlSampler[][] TERRAIN_SAMPLERS = new GlSampler[2][17]; + @Getter + private static GlSampler guiSampler; + + private TextureSamplers() { + } + + public static void initRenderer() { + guiSampler = new GlSampler(false, false, false, false, false, true); + } + + public static GlSampler getTerrainSampler(boolean linear, int anisotropy) { + final GlSampler[] samplers = TERRAIN_SAMPLERS[linear ? 1 : 0]; + GlSampler sampler = samplers[anisotropy]; + if (sampler == null) { + sampler = new GlSampler(linear, true, true, false, false, true); + if (anisotropy > 1) { + RenderSystem.samplerParameterf(sampler.getId(), EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy); + } + samplers[anisotropy] = sampler; + } + return sampler; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java index 8b9823b4d..495b3f425 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java @@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.glsm.backend.BackendManager; import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.proxy.ClientProxy; +import com.gtnewhorizons.angelica.rendering.TextureSamplers; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; @@ -20,6 +21,7 @@ import net.coderbot.iris.Iris; import net.coderbot.iris.gl.program.ComputeProgram; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.samplers.IrisSamplers; import net.coderbot.iris.shadows.ShadowRenderingState; import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.DirectMultiDrawBatch; @@ -52,9 +54,6 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.EXTTextureFilterAnisotropic; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL20; import java.util.ArrayList; @@ -65,15 +64,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { private static final Tracy.ZoneId Z_CHUNK_BEGIN = Tracy.zoneId("chunkBegin", Tracy.COLOR_TERRAIN); private static final Tracy.ZoneId Z_CHUNK_ASSEMBLE_REGION = Tracy.zoneId("chunkAssembleRegion", Tracy.COLOR_TERRAIN); - private GlProgram irisProgram; - private boolean usingIrisProgram; - private int terrainSampler; - private boolean terrainSamplerResolved; - private int terrainSamplerAnisotropy = -1; - private boolean terrainSamplerNearest; - private int packTerrainSampler; - private boolean packTerrainSamplerResolved; - private int packTerrainSamplerAnisotropy = -1; + private GlProgram irisProgram; private boolean terrainSamplerBound; private final GpuTerrainCuller culler; private final SdlShadowVoxelizationSink shadowVoxelSink = new SdlShadowVoxelizationSink(); @@ -160,21 +151,19 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { // Check if Iris shaders are active and we have an override if (provider != null && provider.isShadersEnabled()) { - final GlProgram override = provider.getShaderOverride(pass); + final GlProgram override = provider.getShaderOverride(pass); if (override != null) { pass.startDrawing(); + this.irisProgram = override; + this.activeProgram = override; override.bind(); override.getInterface().setupState(pass); - this.activeProgram = (GlProgram) override; - this.irisProgram = override; - this.usingIrisProgram = true; bindPackTerrainSampler(); return; } } // Fall back to default shader - this.usingIrisProgram = false; this.irisProgram = null; beginDefault(pass); bindTerrainSampler(); @@ -211,85 +200,43 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { @Override protected void end(TerrainRenderPass pass) { - unbindTerrainSampler(); - - if (usingIrisProgram && irisProgram != null) { - irisProgram.getInterface().restoreState(); - irisProgram.unbind(); - irisProgram = null; - usingIrisProgram = false; - this.activeProgram = null; - pass.endDrawing(); - return; + if (irisProgram != null) { + endIrisPass(pass); + } else { + super.end(pass); } + } - super.end(pass); + private void endIrisPass(TerrainRenderPass pass) { + final GlProgram program = irisProgram; + irisProgram = null; + activeProgram = null; + try { + program.getInterface().restoreState(); + } finally { + try { + program.unbind(); + } finally { + pass.endDrawing(); + } + } } private void bindTerrainSampler() { - if (!SodiumGameOptions.usesTerrainTexelSnap()) { - return; - } - - final int anisotropy = SodiumGameOptions.resolvedAnisotropicFiltering(); - final boolean nearest = ClientProxy.options().quality.texelSampling.isNearest(); - - if (!terrainSamplerResolved || terrainSamplerAnisotropy != anisotropy - || terrainSamplerNearest != nearest) { - if (!terrainSamplerResolved) { - terrainSampler = RenderSystem.genSampler(); - if (terrainSampler == 0) { - AngelicaMod.LOGGER.warn("Sampler objects unavailable; terrain filtering will fall back to the atlas texture's own parameters"); - } - } - terrainSamplerResolved = true; - terrainSamplerAnisotropy = anisotropy; - terrainSamplerNearest = nearest; - - configureTerrainSampler(terrainSampler, nearest, anisotropy); - } - - if (terrainSampler != 0) { - RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, terrainSampler); - terrainSamplerBound = true; + if (SodiumGameOptions.usesTerrainTexelSnap()) { + bindBlockSampler(TextureSamplers.getTerrainSampler(!ClientProxy.options().quality.texelSampling.isNearest(), + SodiumGameOptions.resolvedAnisotropicFiltering()).getId()); } } private void bindPackTerrainSampler() { - final int anisotropy = SodiumGameOptions.resolvedAnisotropicFiltering(); - - if (!packTerrainSamplerResolved || packTerrainSamplerAnisotropy != anisotropy) { - if (!packTerrainSamplerResolved) { - packTerrainSampler = RenderSystem.genSampler(); - if (packTerrainSampler == 0) { - AngelicaMod.LOGGER.warn("Sampler objects unavailable; shader pack terrain filtering will fall back to the atlas texture's own parameters"); - } - } - packTerrainSamplerResolved = true; - packTerrainSamplerAnisotropy = anisotropy; - - configureTerrainSampler(packTerrainSampler, true, anisotropy); - } - - if (packTerrainSampler != 0) { - RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, packTerrainSampler); - terrainSamplerBound = true; - } + bindBlockSampler(IrisSamplers.getTerrainSampler(SodiumGameOptions.resolvedAnisotropicFiltering()).getId()); } - private static void configureTerrainSampler(int sampler, boolean nearest, int anisotropy) { - if (sampler == 0) { - return; - } - RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); - RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); - RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_MIN_FILTER, - nearest ? GL11.GL_NEAREST_MIPMAP_LINEAR : GL11.GL_LINEAR_MIPMAP_LINEAR); - RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_MAG_FILTER, - nearest ? GL11.GL_NEAREST : GL11.GL_LINEAR); - if (SodiumGameOptions.anisotropySupported()) { - RenderSystem.samplerParameterf(sampler, - EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) anisotropy); + private void bindBlockSampler(int id) { + if (id != 0) { + RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, id); + terrainSamplerBound = true; } } @@ -311,15 +258,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { shadowVoxelSink.delete(); unbindTerrainSampler(); - RenderSystem.destroySampler(terrainSampler); - terrainSampler = 0; - terrainSamplerResolved = false; - terrainSamplerAnisotropy = -1; - terrainSamplerNearest = false; - RenderSystem.destroySampler(packTerrainSampler); - packTerrainSampler = 0; - packTerrainSamplerResolved = false; - packTerrainSamplerAnisotropy = -1; } @Override @@ -357,8 +295,11 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { voxelizeShadowTerrain(matrices, renderLists, renderPass, occlusionCamera, camera); super.render(matrices, commandList, renderLists, renderPass, occlusionCamera, camera); } finally { - if (culler != null) { - culler.endPass(); + try { + if (irisProgram != null) endIrisPass(renderPass); + } finally { + unbindTerrainSampler(); + if (culler != null) culler.endPass(); } } } @@ -469,7 +410,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { @Override protected void configureShaderInterface(ChunkShaderInterface shader) { - if (!usingIrisProgram) { + if (irisProgram == null) { shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0); shader.setTextureSlot(ChunkShaderTextureSlot.LIGHT, 1); } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java index 07d2c22a5..d98575c5e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java @@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.utils.SpritePadding; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import lombok.Getter; import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; @@ -27,9 +28,11 @@ public class AngelicaRenderPassConfiguration { @Getter private static boolean rgssEnabled; - private static TerrainRenderPass.TerrainRenderPassBuilder builderForRenderType(int pass, boolean disableAlphaTest, ChunkVertexType vertexType) { + private static TerrainRenderPass.TerrainRenderPassBuilder builderForRenderType(int pass, boolean disableAlphaTest, + AlphaCutoffParameter alphaCutoff, ChunkVertexType vertexType) { final TerrainRenderPass.TerrainRenderPassBuilder builder = TerrainRenderPass.builder() - .pipelineState(new AngelicaPipelineState(pass, disableAlphaTest)) + .pipelineState(new AngelicaPipelineState(pass, disableAlphaTest, alphaCutoff)) + .fragmentDiscard(!disableAlphaTest && alphaCutoff != AlphaCutoffParameter.ZERO) .vertexType(vertexType) .primitiveType(QuadPrimitiveType.TRIANGULATED); @@ -61,27 +64,25 @@ public class AngelicaRenderPassConfiguration { public static RenderPassConfiguration build(ChunkVertexType vertexType) { rgssEnabled = SodiumGameOptions.effectiveTextureFilterMode().usesRgss(); + final AlphaCutoffParameter translucentCutoff = MipmapGeneration.alphaFloorCutoff(); - SOLID_PASS = builderForRenderType(0, true, vertexType) + SOLID_PASS = builderForRenderType(0, true, AlphaCutoffParameter.HALF, vertexType) .name("solid") - .fragmentDiscard(false) .useReverseOrder(false) .build(); - CUTOUT_MIPPED_PASS = builderForRenderType(0, false, vertexType) + CUTOUT_MIPPED_PASS = builderForRenderType(0, false, AlphaCutoffParameter.HALF, vertexType) .name("cutout_mipped") - .fragmentDiscard(true) .useReverseOrder(false) .build(); - TRANSLUCENT_PASS = builderForRenderType(1, false, vertexType) + TRANSLUCENT_PASS = builderForRenderType(1, false, translucentCutoff, vertexType) .name("translucent") - .fragmentDiscard(false) .useReverseOrder(true) .useTranslucencySorting(ClientProxy.options().performance.translucencySorting) .build(); - TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, AlphaCutoffParameter.ZERO, true); + TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, translucentCutoff, true); SOLID_MATERIAL = new Material(SOLID_PASS, AlphaCutoffParameter.ZERO, true); CUTOUT_MIPPED_MATERIAL = new Material(CUTOUT_MIPPED_PASS, AlphaCutoffParameter.HALF, true); CUTOUT_MATERIAL = new Material(CUTOUT_MIPPED_PASS, AlphaCutoffParameter.ONE_TENTH, false); @@ -105,24 +106,29 @@ public class AngelicaRenderPassConfiguration { private static final class AngelicaPipelineState implements TerrainRenderPass.PipelineState { private final int pass; private final boolean disableAlphaTest; + private final float alphaCutoff; private int alphaStateDepth = -1; - private AngelicaPipelineState(int pass, boolean disableAlphaTest) { + private AngelicaPipelineState(int pass, boolean disableAlphaTest, AlphaCutoffParameter alphaCutoff) { this.pass = pass; this.disableAlphaTest = disableAlphaTest; + this.alphaCutoff = alphaCutoff.cutoff(); } @Override public void setup() { GLStateManager.glDepthMask(true); - if (pass == 0) { + if (alphaCutoff > 0.0f) { if (alphaStateDepth >= 0) { GLStateManager.popStateTo(alphaStateDepth); alphaStateDepth = -1; } alphaStateDepth = GLStateManager.pushState(StateSet.ALPHA); - GLStateManager.glAlphaFunc(GL11.GL_GREATER, AlphaCutoffParameter.HALF.cutoff()); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, alphaCutoff); + if (pass == 1) { + GLStateManager.enableAlphaTest(); + } } if (disableAlphaTest) { GLStateManager.disableAlphaTest(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SpriteExtension.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SpriteExtension.java index 14447baa9..d40786aa3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SpriteExtension.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SpriteExtension.java @@ -11,7 +11,11 @@ public interface SpriteExtension { /** One-shot: returns true if marked, then resets. */ boolean celeritas$shouldUpdate(); - void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit, int textureType); + void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit); + + void angelica$setTextureType(int textureType); + + void angelica$setAlphaCutoffBias(float bias); /** Width of the replicated-edge border reserved around this sprite in its stitcher slot. */ int angelica$getGutterWidth(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java index 789a03f09..206e0a966 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java @@ -19,7 +19,7 @@ public interface IrisShaderProvider { boolean shouldUseFaceCulling(); - @Nullable GlProgram getShaderOverride(TerrainRenderPass pass); + @Nullable GlProgram getShaderOverride(TerrainRenderPass pass); ChunkVertexType getVertexType(ChunkVertexType defaultType); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleAlphaCutoff.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleAlphaCutoff.java new file mode 100644 index 000000000..2f3d3338d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleAlphaCutoff.java @@ -0,0 +1,20 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; +import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter; + +public final class ParticleAlphaCutoff { + + private static final int TERRAIN_PARTICLE_LAYER = 1; + + private ParticleAlphaCutoff() { + } + + public static float forLayer(float original, int layer) { + if (layer != TERRAIN_PARTICLE_LAYER) { + return original; + } + final AlphaCutoffParameter cutoff = MipmapGeneration.alphaFloorCutoff(); + return cutoff == AlphaCutoffParameter.ZERO ? original : cutoff.cutoff(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/CeleritasMipmapGenerator.java b/src/main/java/com/gtnewhorizons/angelica/utils/CeleritasMipmapGenerator.java new file mode 100644 index 000000000..e500f8a9b --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/utils/CeleritasMipmapGenerator.java @@ -0,0 +1,230 @@ +package com.gtnewhorizons.angelica.utils; + +import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; +import org.embeddedt.embeddium.api.util.ColorARGB; +import org.embeddedt.embeddium.impl.texture.MipmapHelper; + +import static com.gtnewhorizons.angelica.utils.MipmapGenerator.ALPHA_BIAS; +import static org.joml.Math.clamp; + +final class CeleritasMipmapGenerator { + + private CeleritasMipmapGenerator() { + } + + static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips, + boolean isCutout, boolean darkCutout, float cutoutRef) { + final int[][] result = new int[mipLevel + 1][]; + final int[] base = currentMips[0]; + + if (mipLevel > 0 && (currentMips.length == 1 || currentMips[1] == null)) { + if (darkCutout) { + MipmapGenerator.fillEmptyAreasWithDarkColor(base, 1); + } else { + solidify(base, width, base.length / width); + } + } + + result[0] = base; + if (mipLevel <= 0) { + return result; + } + + final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f) : 0.0f; + + for (int level = 1; level <= mipLevel; level++) { + final int levelWidth = width >> level; + final int[] provided = level < currentMips.length ? currentMips[level] : null; + + if (provided != null) { + result[level] = provided; + } else { + final int[] input = result[level - 1]; + final int prevWidth = width >> (level - 1); + final int prevHeight = input.length / prevWidth; + final int levelHeight = prevHeight >> 1; + final int[] output = new int[levelWidth * levelHeight]; + + for (int y = 0; y < levelHeight; y++) { + for (int x = 0; x < levelWidth; x++) { + final int i = x * 2 + y * 2 * prevWidth; + output[x + y * levelWidth] = MipmapHelper.weightedAverageColor( + MipmapHelper.weightedAverageColor(input[i], input[i + 1]), + MipmapHelper.weightedAverageColor(input[i + prevWidth], input[i + prevWidth + 1])); + } + } + result[level] = output; + } + + if (isCutout) { + scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef); + } + } + + return result; + } + + private static void solidify(int[] image, int width, int height) { + final int size = Math.min(width * height, image.length); + if (size <= 0) { + return; + } + + boolean hasTransparent = false; + for (int i = 0; i < size; i++) { + if (ColorARGB.unpackAlpha(image[i]) == 0) { + hasTransparent = true; + break; + } + } + if (!hasTransparent) { + return; + } + + final int[] color = new int[size]; + final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64); + + for (int i = 0; i < size; i++) { + final int pixel = image[i]; + if (ColorARGB.unpackAlpha(pixel) == 0) { + continue; + } + color[i] = pixel; + if (hasTransparentNeighbor(image, i, width, size)) { + queue.enqueue(i); + } + } + + if (queue.isEmpty()) { + return; + } + + while (!queue.isEmpty()) { + final int index = queue.dequeueInt(); + final int x = index % width; + final int source = color[index]; + + if (x > 0) { + fill(index - 1, source, color, queue); + } + if (x < width - 1) { + fill(index + 1, source, color, queue); + } + if (index >= width) { + fill(index - width, source, color, queue); + } + if (index + width < size) { + fill(index + width, source, color, queue); + } + } + + for (int i = 0; i < size; i++) { + if (ColorARGB.unpackAlpha(image[i]) == 0) { + image[i] = color[i] & 0x00FFFFFF; + } + } + } + + private static boolean hasTransparentNeighbor(int[] image, int index, int width, int size) { + final int x = index % width; + return (x > 0 && ColorARGB.unpackAlpha(image[index - 1]) == 0) + || (x < width - 1 && ColorARGB.unpackAlpha(image[index + 1]) == 0) + || (index >= width && ColorARGB.unpackAlpha(image[index - width]) == 0) + || (index + width < size && ColorARGB.unpackAlpha(image[index + width]) == 0); + } + + private static void fill(int neighbor, int source, int[] color, IntArrayFIFOQueue queue) { + if (color[neighbor] == 0) { + color[neighbor] = source; + queue.enqueue(neighbor); + } + } + + private static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale) { + final int height = image.length / width; + final float alphaFactor = alphaScale / 255.0f; + float total = 0.0f; + int quads = 0; + + for (int y = 0; y < height - 1; y++) { + for (int x = 0; x < width - 1; x++) { + final int i = x + y * width; + final float a00 = scaledAlpha(image[i], alphaFactor); + final float a10 = scaledAlpha(image[i + 1], alphaFactor); + final float a01 = scaledAlpha(image[i + width], alphaFactor); + final float a11 = scaledAlpha(image[i + width + 1], alphaFactor); + + final float lo = Math.min(Math.min(a00, a10), Math.min(a01, a11)); + if (lo > alphaRef) { + total += 1.0f; + quads++; + continue; + } + final float hi = Math.max(Math.max(a00, a10), Math.max(a01, a11)); + if (hi <= alphaRef) { + quads++; + continue; + } + + int hits = 0; + for (int sy = 0; sy < 4; sy++) { + final float fy = (sy + 0.5f) / 4.0f; + for (int sx = 0; sx < 4; sx++) { + final float fx = (sx + 0.5f) / 4.0f; + final float top = a00 + (a10 - a00) * fx; + final float bottom = a01 + (a11 - a01) * fx; + if (top + (bottom - top) * fy > alphaRef) { + hits++; + } + } + } + total += hits / 16.0f; + quads++; + } + } + + if (quads == 0) { + return scaledAlpha(image[0], alphaFactor) > alphaRef ? 1.0f : 0.0f; + } + return total / quads; + } + + private static float scaledAlpha(int color, float alphaFactor) { + return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor); + } + + private static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef) { + float min = 0.0f; + float max = 4.0f; + float scale = 1.0f; + float bestScale = 1.0f; + float bestError = Float.POSITIVE_INFINITY; + + for (int i = 0; i < 5; i++) { + final float coverage = alphaTestCoverage(image, width, alphaRef, scale); + final float error = Math.abs(coverage - desiredCoverage); + if (error < bestError) { + bestError = error; + bestScale = scale; + } + + if (coverage < desiredCoverage) { + min = scale; + } else if (!(coverage > desiredCoverage)) { + break; + } else { + max = scale; + } + scale = (min + max) / 2.0f; + } + + for (int i = 0; i < image.length; i++) { + final int color = image[i]; + final int rawAlpha = ColorARGB.unpackAlpha(color); + final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f; + final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f); + image[i] = ColorARGB.withAlpha(color, alpha); + } + } + +} diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java index 5be6e9ad6..9efc25d9c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java +++ b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java @@ -1,19 +1,16 @@ package com.gtnewhorizons.angelica.utils; -import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; import org.embeddedt.embeddium.api.util.ColorARGB; -import org.embeddedt.embeddium.impl.texture.MipmapHelper; - -import static org.joml.Math.clamp; /** * Mipmap downsampling for atlas sprites, replacing vanilla's {@code TextureUtil.generateMipmapData}. */ public final class MipmapGenerator { + static final float ALPHA_BIAS = 0.025f; private static final float CUTOUT_ALPHA_REF = 0.5f; private static final float STRICT_CUTOUT_ALPHA_REF = 0.3f; - private static final float ALPHA_BIAS = 0.025f; private MipmapGenerator() { } @@ -25,101 +22,29 @@ public final class MipmapGenerator { return strategy; } - static boolean isCutoutStrategy(MipmapStrategy strategy, boolean hasTransparentPixel) { - final MipmapStrategy resolved = resolve(strategy, hasTransparentPixel); + private static boolean isCutoutStrategy(MipmapStrategy resolved) { return resolved == MipmapStrategy.CUTOUT || resolved == MipmapStrategy.STRICT_CUTOUT || resolved == MipmapStrategy.DARK_CUTOUT; } - static void solidify(int[] image, int width, int height) { - final int size = Math.min(width * height, image.length); - if (size <= 0) { - return; - } - - boolean hasTransparent = false; - for (int i = 0; i < size; i++) { - if (ColorARGB.unpackAlpha(image[i]) == 0) { - hasTransparent = true; - break; - } - } - if (!hasTransparent) { - return; - } - - final int[] color = new int[size]; - final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64); - - for (int i = 0; i < size; i++) { - final int pixel = image[i]; - if (ColorARGB.unpackAlpha(pixel) == 0) { - continue; - } - color[i] = pixel; - if (hasTransparentNeighbour(image, i, width, size)) { - queue.enqueue(i); - } - } - - if (queue.isEmpty()) { - return; - } - - while (!queue.isEmpty()) { - final int index = queue.dequeueInt(); - final int x = index % width; - final int source = color[index]; - - if (x > 0) { - fill(index - 1, source, color, queue); - } - if (x < width - 1) { - fill(index + 1, source, color, queue); - } - if (index >= width) { - fill(index - width, source, color, queue); - } - if (index + width < size) { - fill(index + width, source, color, queue); - } - } - - for (int i = 0; i < size; i++) { - if (ColorARGB.unpackAlpha(image[i]) == 0) { - image[i] = color[i] & 0x00FFFFFF; - } - } - } - - private static boolean hasTransparentNeighbour(int[] image, int index, int width, int size) { - final int x = index % width; - return (x > 0 && ColorARGB.unpackAlpha(image[index - 1]) == 0) - || (x < width - 1 && ColorARGB.unpackAlpha(image[index + 1]) == 0) - || (index >= width && ColorARGB.unpackAlpha(image[index - width]) == 0) - || (index + width < size && ColorARGB.unpackAlpha(image[index + width]) == 0); - } - - private static void fill(int neighbour, int source, int[] color, IntArrayFIFOQueue queue) { - if (color[neighbour] == 0) { - color[neighbour] = source; - queue.enqueue(neighbour); - } - } - - static void fillEmptyAreasWithDarkColor(int[] image) { + // Scan order controls which equally dark color wins. + static void fillEmptyAreasWithDarkColor(int[] image, int columns) { + final int rows = image.length / columns; int darkest = ColorARGB.pack(255, 255, 255, 255); - int darkestSum = 255 * 3; + int darkestSum = Integer.MAX_VALUE; - for (final int pixel : image) { - if (ColorARGB.unpackAlpha(pixel) == 0) { - continue; - } - final int sum = ColorARGB.unpackRed(pixel) + ColorARGB.unpackGreen(pixel) + ColorARGB.unpackBlue(pixel); - if (sum < darkestSum) { - darkestSum = sum; - darkest = pixel; + for (int x = 0; x < columns; x++) { + for (int y = 0; y < rows; y++) { + final int pixel = image[x + y * columns]; + if (ColorARGB.unpackAlpha(pixel) == 0) { + continue; + } + final int sum = ColorARGB.unpackRed(pixel) + ColorARGB.unpackGreen(pixel) + ColorARGB.unpackBlue(pixel); + if (sum < darkestSum) { + darkestSum = sum; + darkest = pixel; + } } } @@ -133,152 +58,22 @@ public final class MipmapGenerator { } } - /** - * Estimates the fraction of the image that survives, with bilinear filtering modeled by - * supersampling each texel quad on a 4x4 interior grid. - */ - static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale) { - final int height = image.length / width; - final float alphaFactor = alphaScale / 255.0f; - float total = 0.0f; - int quads = 0; - - for (int y = 0; y < height - 1; y++) { - for (int x = 0; x < width - 1; x++) { - final int i = x + y * width; - final float a00 = scaledAlpha(image[i], alphaFactor); - final float a10 = scaledAlpha(image[i + 1], alphaFactor); - final float a01 = scaledAlpha(image[i + width], alphaFactor); - final float a11 = scaledAlpha(image[i + width + 1], alphaFactor); - - final float lo = Math.min(Math.min(a00, a10), Math.min(a01, a11)); - if (lo > alphaRef) { - total += 1.0f; - quads++; - continue; - } - final float hi = Math.max(Math.max(a00, a10), Math.max(a01, a11)); - if (hi <= alphaRef) { - quads++; - continue; - } - - int hits = 0; - for (int sy = 0; sy < 4; sy++) { - final float fy = (sy + 0.5f) / 4.0f; - for (int sx = 0; sx < 4; sx++) { - final float fx = (sx + 0.5f) / 4.0f; - final float top = a00 + (a10 - a00) * fx; - final float bottom = a01 + (a11 - a01) * fx; - if (top + (bottom - top) * fy > alphaRef) { - hits++; - } - } - } - total += hits / 16.0f; - quads++; - } - } - - if (quads == 0) { - return scaledAlpha(image[0], alphaFactor) > alphaRef ? 1.0f : 0.0f; - } - return total / quads; - } - - private static float scaledAlpha(int color, float alphaFactor) { - return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor); - } - - static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef) { - float min = 0.0f; - float max = 4.0f; - float scale = 1.0f; - float bestScale = 1.0f; - float bestError = Float.POSITIVE_INFINITY; - - for (int i = 0; i < 5; i++) { - final float coverage = alphaTestCoverage(image, width, alphaRef, scale); - final float error = Math.abs(coverage - desiredCoverage); - if (error < bestError) { - bestError = error; - bestScale = scale; - } - - if (coverage < desiredCoverage) { - min = scale; - } else if (!(coverage > desiredCoverage)) { - break; - } else { - max = scale; - } - scale = (min + max) / 2.0f; - } - - for (int i = 0; i < image.length; i++) { - final int color = image[i]; - final int rawAlpha = ColorARGB.unpackAlpha(color); - final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f; - final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f); - image[i] = ColorARGB.withAlpha(color, alpha); - } - } - public static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips, - MipmapStrategy strategy, boolean hasTransparentPixel) { + MipmapStrategy strategy, boolean hasTransparentPixel, MipmapGeneration generation, + float alphaCutoffBias, boolean isItem) { + if (generation == MipmapGeneration.VANILLA_1_7_10) { + return VanillaMipmapGenerator.generateMipLevels(mipLevel, width, currentMips); + } final MipmapStrategy resolved = resolve(strategy, hasTransparentPixel); - final boolean isCutout = isCutoutStrategy(strategy, hasTransparentPixel); + final boolean isCutout = isCutoutStrategy(resolved); final boolean darkCutout = resolved == MipmapStrategy.DARK_CUTOUT; - - final int[][] result = new int[mipLevel + 1][]; - final int[] base = currentMips[0]; - - if (mipLevel > 0 && (currentMips.length == 1 || currentMips[1] == null)) { - if (darkCutout) { - fillEmptyAreasWithDarkColor(base); - } else { - solidify(base, width, base.length / width); - } - } - - result[0] = base; - if (mipLevel <= 0) { - return result; - } - final float cutoutRef = resolved == MipmapStrategy.STRICT_CUTOUT ? STRICT_CUTOUT_ALPHA_REF : CUTOUT_ALPHA_REF; - final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f) : 0.0f; - - for (int level = 1; level <= mipLevel; level++) { - final int levelWidth = width >> level; - final int[] provided = level < currentMips.length ? currentMips[level] : null; - - if (provided != null) { - result[level] = provided; - } else { - final int[] input = result[level - 1]; - final int prevWidth = width >> (level - 1); - final int prevHeight = input.length / prevWidth; - final int levelHeight = prevHeight >> 1; - final int[] output = new int[levelWidth * levelHeight]; - - for (int y = 0; y < levelHeight; y++) { - for (int x = 0; x < levelWidth; x++) { - final int i = x * 2 + y * 2 * prevWidth; - output[x + y * levelWidth] = MipmapHelper.weightedAverageColor( - MipmapHelper.weightedAverageColor(input[i], input[i + 1]), - MipmapHelper.weightedAverageColor(input[i + prevWidth], input[i + prevWidth + 1])); - } - } - result[level] = output; - } - - if (isCutout) { - scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef); - } + if (generation == MipmapGeneration.MODERN_VANILLA) { + return ModernMipmapGenerator.generateMipLevels(mipLevel, width, currentMips, + isCutout, darkCutout, cutoutRef, alphaCutoffBias, isItem); } - return result; + return CeleritasMipmapGenerator.generateMipLevels(mipLevel, width, currentMips, isCutout, darkCutout, cutoutRef); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapStrategies.java b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapStrategies.java index 9fe40d419..8c68703ae 100644 --- a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapStrategies.java +++ b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapStrategies.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.utils; +import com.gtnewhorizons.angelica.rendering.TextureAtlasType; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.BlockFlower; @@ -55,7 +56,7 @@ public final class MipmapStrategies { } MipmapStrategy strategy = STRATEGY_STACK.get().peek(); - if (strategy == null && textureType == 0 && iconName.contains("leaves")) { + if (strategy == null && textureType == TextureAtlasType.BLOCK && iconName.contains("leaves")) { strategy = MipmapStrategy.DARK_CUTOUT; } if (strategy == null) { @@ -67,7 +68,7 @@ public final class MipmapStrategies { } public static MipmapStrategy inheritedFor(int textureType, String iconName) { - if (iconName == null || textureType != 0) { + if (iconName == null || textureType != TextureAtlasType.BLOCK) { return null; } return SPRITE_RULES.get(iconName); diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapBlender.java b/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapBlender.java new file mode 100644 index 000000000..32125a748 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapBlender.java @@ -0,0 +1,77 @@ +package com.gtnewhorizons.angelica.utils; + +import org.embeddedt.embeddium.api.util.ColorARGB; + +/** + * Minecraft 26.2's ARGB.meanLinear and MipmapGenerator.darkenedAlphaBlend, using its 10-bit linear color tables. + */ +final class ModernMipmapBlender { + private static final int[] SRGB_TO_LINEAR = new int[256]; + private static final float[] SRGB_TO_LINEAR_FLOAT = new float[256]; + private static final int[] LINEAR_TO_SRGB = new int[1024]; + + static { + for (int i = 0; i < SRGB_TO_LINEAR.length; i++) { + final float channel = i / 255.0f; + final float linear = channel >= 0.04045f ? (float) Math.pow((channel + 0.055) / 1.055, 2.4) : channel / 12.92f; + SRGB_TO_LINEAR[i] = Math.round(linear * 1023.0f); + SRGB_TO_LINEAR_FLOAT[i] = SRGB_TO_LINEAR[i] / 1023.0f; + } + for (int i = 0; i < LINEAR_TO_SRGB.length; i++) { + final float channel = i / 1023.0f; + final float srgb = channel >= 0.0031308f ? (float) (1.055 * Math.pow(channel, 1.0 / 2.4) - 0.055) : 12.92f * channel; + LINEAR_TO_SRGB[i] = Math.round(srgb * 255.0f); + } + } + + private ModernMipmapBlender() { + } + + static int blend(int a, int b, int c, int d, boolean darkCutout) { + if (darkCutout) { + return darkenedAlphaBlend(a, b, c, d); + } + return ColorARGB.pack(meanChannel(a, b, c, d, 16), meanChannel(a, b, c, d, 8), meanChannel(a, b, c, d, 0), (ColorARGB.unpackAlpha(a) + ColorARGB.unpackAlpha(b) + ColorARGB.unpackAlpha(c) + ColorARGB.unpackAlpha(d)) / 4); + } + + private static int meanChannel(int a, int b, int c, int d, int shift) { + final int linear = (SRGB_TO_LINEAR[(a >>> shift) & 255] + SRGB_TO_LINEAR[(b >>> shift) & 255] + SRGB_TO_LINEAR[(c >>> shift) & 255] + SRGB_TO_LINEAR[(d >>> shift) & 255]) / 4; + return LINEAR_TO_SRGB[linear]; + } + + private static int darkenedAlphaBlend(int a, int b, int c, int d) { + float alpha = 0.0f; + float red = 0.0f; + float green = 0.0f; + float blue = 0.0f; + if (ColorARGB.unpackAlpha(a) != 0) { + alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(a)]; + red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(a)]; + green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(a)]; + blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(a)]; + } + if (ColorARGB.unpackAlpha(b) != 0) { + alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(b)]; + red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(b)]; + green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(b)]; + blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(b)]; + } + if (ColorARGB.unpackAlpha(c) != 0) { + alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(c)]; + red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(c)]; + green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(c)]; + blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(c)]; + } + if (ColorARGB.unpackAlpha(d) != 0) { + alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(d)]; + red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(d)]; + green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(d)]; + blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(d)]; + } + return ColorARGB.pack(toSrgb(red), toSrgb(green), toSrgb(blue), toSrgb(alpha)); + } + + private static int toSrgb(float sum) { + return LINEAR_TO_SRGB[(int) (sum * 0.25f * 1023.0f)]; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapGenerator.java b/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapGenerator.java new file mode 100644 index 000000000..4d78f8d91 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/utils/ModernMipmapGenerator.java @@ -0,0 +1,238 @@ +package com.gtnewhorizons.angelica.utils; + +import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; +import it.unimi.dsi.fastutil.ints.IntArrays; +import org.embeddedt.embeddium.api.util.ColorARGB; + +import java.util.Arrays; + +import static com.gtnewhorizons.angelica.utils.MipmapGenerator.ALPHA_BIAS; +import static org.joml.Math.clamp; + +/** + * Minecraft 26.2's mipmap generation and texture preparation. + */ +final class ModernMipmapGenerator { + + private static final float[] NORMALIZED_ALPHA = new float[256]; + + static { + for (int i = 0; i < NORMALIZED_ALPHA.length; i++) { + NORMALIZED_ALPHA[i] = i / 255.0f; + } + } + + private ModernMipmapGenerator() { + } + + static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips, boolean isCutout, boolean darkCutout, float cutoutRef, float alphaCutoffBias, boolean isItem) { + final int[] base = currentMips[0]; + + // Unlike modern NativeImage arrays, 1.7.10 preallocates null slots for missing mip levels. + boolean hasProvidedMips = false; + boolean complete = mipLevel < currentMips.length; + int maxPixels = base.length; + for (int level = 1; level < currentMips.length; level++) { + if (currentMips[level] != null) { + hasProvidedMips = true; + if (level <= mipLevel) { + maxPixels = Math.max(maxPixels, currentMips[level].length); + } + } else if (level <= mipLevel) { + complete = false; + } + } + if (!hasProvidedMips && !isItem && isCutout) { + if (darkCutout) { + MipmapGenerator.fillEmptyAreasWithDarkColor(base, width); + } else { + solidify(base, width); + } + } + + if (complete) { + return currentMips.length == mipLevel + 1 ? currentMips : Arrays.copyOf(currentMips, mipLevel + 1); + } + + final int[][] result = Arrays.copyOf(currentMips, mipLevel + 1); + final float[] alphaScratch = isCutout ? new float[maxPixels] : null; + final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f, alphaScratch) : 0.0f; + + for (int level = 1; level <= mipLevel; level++) { + final int levelWidth = width >> level; + if (levelWidth == 0) { + if (result[level] == null) { + result[level] = IntArrays.EMPTY_ARRAY; + } + continue; + } + if (result[level] == null) { + final int[] input = result[level - 1]; + final int prevWidth = width >> (level - 1); + final int levelHeight = (input.length / prevWidth) >> 1; + if (levelHeight == 0) { + result[level] = IntArrays.EMPTY_ARRAY; + continue; + } + final int[] output = new int[levelWidth * levelHeight]; + for (int y = 0; y < levelHeight; y++) { + for (int x = 0; x < levelWidth; x++) { + final int i = x * 2 + y * 2 * prevWidth; + output[x + y * levelWidth] = ModernMipmapBlender.blend(input[i], input[i + 1], input[i + prevWidth], input[i + prevWidth + 1], darkCutout); + } + } + result[level] = output; + } + if (isCutout && result[level].length > 0) { + scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef, alphaCutoffBias, alphaScratch); + } + } + return result; + } + + private static void solidify(int[] image, int width) { + boolean hasTransparentPixel = false; + boolean hasOpaquePixel = false; + for (int color : image) { + if (ColorARGB.unpackAlpha(color) == 0) { + hasTransparentPixel = true; + } else { + hasOpaquePixel = true; + } + if (hasTransparentPixel && hasOpaquePixel) { + break; + } + } + if (!hasTransparentPixel) { + return; + } + + if (!hasOpaquePixel) { + Arrays.fill(image, 0); + return; + } + final int height = image.length / width; + final int[] nearestColor = new int[image.length]; + final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64); + + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + final int i = x + y * width; + if (ColorARGB.unpackAlpha(image[i]) != 0) { + nearestColor[i] = image[i]; + if (hasTransparentNeighbor(image, width, i, x)) { + queue.enqueue(i); + } + } + } + } + while (!queue.isEmpty()) { + final int i = queue.dequeueInt(); + final int x = i % width; + final int color = nearestColor[i]; + if (x < width - 1) { + fill(i + 1, color, nearestColor, queue); + } + if (x > 0) { + fill(i - 1, color, nearestColor, queue); + } + if (i + width < image.length) { + fill(i + width, color, nearestColor, queue); + } + if (i >= width) { + fill(i - width, color, nearestColor, queue); + } + } + for (int i = 0; i < image.length; i++) { + if (ColorARGB.unpackAlpha(image[i]) == 0) { + image[i] = nearestColor[i] & 0x00FFFFFF; + } + } + } + + private static boolean hasTransparentNeighbor(int[] image, int width, int i, int x) { + return (x < width - 1 && ColorARGB.unpackAlpha(image[i + 1]) == 0) || (x > 0 && ColorARGB.unpackAlpha(image[i - 1]) == 0) || (i + width < image.length && ColorARGB.unpackAlpha(image[i + width]) == 0) + || (i >= width && ColorARGB.unpackAlpha(image[i - width]) == 0); + } + + private static void fill(int i, int color, int[] nearestColor, IntArrayFIFOQueue queue) { + if (nearestColor[i] == 0) { + nearestColor[i] = color; + queue.enqueue(i); + } + } + + private static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale, float[] alphaScratch) { + final int height = image.length / width; + for (int i = 0; i < image.length; i++) { + alphaScratch[i] = clamp(0.0f, 1.0f, NORMALIZED_ALPHA[ColorARGB.unpackAlpha(image[i])] * alphaScale); + } + final float margin = 8.0f * Math.ulp(alphaRef); + final float safelyAbove = alphaRef + margin; + final float safelyBelow = alphaRef - margin; + float coverage = 0.0f; + for (int y = 0; y < height - 1; y++) { + for (int x = 0; x < width - 1; x++) { + final int i = x + y * width; + final float a00 = alphaScratch[i]; + final float a10 = alphaScratch[i + 1]; + final float a01 = alphaScratch[i + width]; + final float a11 = alphaScratch[i + width + 1]; + if (a00 > safelyAbove && a10 > safelyAbove && a01 > safelyAbove && a11 > safelyAbove) { + coverage += 1.0f; + continue; + } + if (a00 < safelyBelow && a10 < safelyBelow && a01 < safelyBelow && a11 < safelyBelow) { + continue; + } + float texelCoverage = 0.0f; + for (int sy = 0; sy < 4; sy++) { + final float fy = (sy + 0.5f) / 4.0f; + for (int sx = 0; sx < 4; sx++) { + final float fx = (sx + 0.5f) / 4.0f; + final float alpha = a00 * (1.0f - fx) * (1.0f - fy) + a10 * fx * (1.0f - fy) + a01 * (1.0f - fx) * fy + a11 * fx * fy; + if (alpha > alphaRef) { + texelCoverage++; + } + } + } + coverage += texelCoverage / 16.0f; + } + } + return coverage / ((width - 1) * (height - 1)); + } + + private static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef, float alphaCutoffBias, float[] alphaScratch) { + float min = 0.0f; + float max = 4.0f; + float scale = 1.0f; + float bestScale = 1.0f; + float bestError = Float.MAX_VALUE; + + if (width > 1 && image.length / width > 1) { + for (int i = 0; i < 5; i++) { + final float coverage = alphaTestCoverage(image, width, alphaRef, scale, alphaScratch); + final float error = Math.abs(coverage - desiredCoverage); + if (error < bestError) { + bestError = error; + bestScale = scale; + } + if (coverage < desiredCoverage) { + min = scale; + } else if (coverage > desiredCoverage) { + max = scale; + } else { + break; + } + scale = (min + max) * 0.5f; + } + } + + for (int i = 0; i < image.length; i++) { + final int color = image[i]; + final float alpha = NORMALIZED_ALPHA[ColorARGB.unpackAlpha(color)] * bestScale + alphaCutoffBias + ALPHA_BIAS; + image[i] = ColorARGB.withAlpha(color, (int) (clamp(0.0f, 1.0f, alpha) * 255.0f)); + } + } + +} diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/VanillaMipmapGenerator.java b/src/main/java/com/gtnewhorizons/angelica/utils/VanillaMipmapGenerator.java new file mode 100644 index 000000000..038104cdc --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/utils/VanillaMipmapGenerator.java @@ -0,0 +1,97 @@ +package com.gtnewhorizons.angelica.utils; + +import it.unimi.dsi.fastutil.ints.IntArrays; +import org.embeddedt.embeddium.api.util.ColorARGB; + +/** + * Minecraft 1.7.10's TextureUtil mipmap generator without its shared mutable color buffer. + */ +final class VanillaMipmapGenerator { + + private static final float[] TO_LINEAR = new float[256]; + + static { + for (int i = 0; i < TO_LINEAR.length; i++) { + TO_LINEAR[i] = (float) Math.pow(i / 255.0f, 2.2); + } + } + + private VanillaMipmapGenerator() { + } + + static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips) { + final int[][] result = new int[mipLevel + 1][]; + result[0] = currentMips[0]; + if (mipLevel <= 0) { + return result; + } + + boolean hasTransparentPixel = false; + for (int i = 0; i < Math.min(currentMips.length, result[0].length); i++) { + if (ColorARGB.unpackAlpha(result[0][i]) == 0) { + hasTransparentPixel = true; + break; + } + } + + for (int level = 1; level <= mipLevel; level++) { + final int[] provided = level < currentMips.length ? currentMips[level] : null; + if (provided != null) { + result[level] = provided; + continue; + } + + final int levelWidth = width >> level; + if (levelWidth == 0) { + result[level] = IntArrays.EMPTY_ARRAY; + continue; + } + final int[] input = result[level - 1]; + final int[] output = new int[input.length >> 2]; + final int levelHeight = output.length / levelWidth; + final int stride = levelWidth << 1; + for (int y = 0; y < levelHeight; y++) { + for (int x = 0; x < levelWidth; x++) { + final int i = 2 * (x + y * stride); + output[x + y * levelWidth] = blend(input[i], input[i + 1], input[i + stride], input[i + stride + 1], hasTransparentPixel); + } + } + result[level] = output; + } + return result; + } + + private static int blend(int a, int b, int c, int d, boolean hasTransparentPixel) { + if (hasTransparentPixel) { + int alpha = transparentChannel(a, b, c, d, 24); + if (alpha < 96) { + alpha = 0; + } + return ColorARGB.pack(transparentChannel(a, b, c, d, 16), transparentChannel(a, b, c, d, 8), transparentChannel(a, b, c, d, 0), alpha); + } + return ColorARGB.pack(meanChannel(a, b, c, d, 16), meanChannel(a, b, c, d, 8), meanChannel(a, b, c, d, 0), meanChannel(a, b, c, d, 24)); + } + + private static int meanChannel(int a, int b, int c, int d, int shift) { + final float sum = TO_LINEAR[(a >>> shift) & 255] + TO_LINEAR[(b >>> shift) & 255] + TO_LINEAR[(c >>> shift) & 255] + TO_LINEAR[(d >>> shift) & 255]; + final float value = (float) Math.pow(sum * 0.25, 1.0 / 2.2); + return (int) (value * 255.0); + } + + private static int transparentChannel(int a, int b, int c, int d, int shift) { + float sum = 0.0f; + if (ColorARGB.unpackAlpha(a) != 0) { + sum += TO_LINEAR[(a >>> shift) & 255]; + } + if (ColorARGB.unpackAlpha(b) != 0) { + sum += TO_LINEAR[(b >>> shift) & 255]; + } + if (ColorARGB.unpackAlpha(c) != 0) { + sum += TO_LINEAR[(c >>> shift) & 255]; + } + if (ColorARGB.unpackAlpha(d) != 0) { + sum += TO_LINEAR[(d >>> shift) & 255]; + } + return (int) (Math.pow(sum / 4.0f, 1.0 / 2.2) * 255.0); + } +} diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java index a34426d20..c9db93d55 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java @@ -42,6 +42,7 @@ import me.jellysquid.mods.sodium.client.gui.options.named.BiomeBlendMode; import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsMode; import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality; import me.jellysquid.mods.sodium.client.gui.options.named.LightingQuality; +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import me.jellysquid.mods.sodium.client.gui.options.named.ParticleMode; import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling; @@ -313,6 +314,14 @@ public class SodiumGameOptionPages { groups.add(OptionGroup.createBuilder() .add(mipmapLevels) + .add(OptionImpl.createBuilder(MipmapGeneration.class, sodiumOpts) + .setName(I18n.format("sodium.options.mipmap_generation.name")) + .setTooltip(I18n.format("sodium.options.mipmap_generation.tooltip")) + .setControl(option -> new CyclingControl<>(option, MipmapGeneration.class)) + .setBinding((opts, value) -> opts.quality.mipmapGeneration = value, opts -> opts.quality.mipmapGeneration) + .setImpact(OptionImpact.LOW) + .setFlags(OptionFlag.REQUIRES_ASSET_RELOAD) + .build()) .build()); groups.add(OptionGroup.createBuilder() .add(Settings.MODE_GLINT_INV.option) @@ -765,7 +774,6 @@ public class SodiumGameOptionPages { (opts, value) -> opts.anisotropicFiltering = 1 << MathHelper.clamp_int(value, min, max), opts -> MathHelper.clamp_int(Integer.numberOfTrailingZeros(Math.max(opts.anisotropicFiltering, 1)), min, max)) .setImpact(OptionImpact.MEDIUM) - .setFlags(OptionFlag.REQUIRES_ASSET_RELOAD) .build(); option.iris$dynamicallyEnable(() -> mode.get().usesAnisotropy() && SodiumGameOptions.hasAnisotropyRange()); diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java index 2fb4bd346..f36a8df2c 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java @@ -11,6 +11,7 @@ import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; import com.gtnewhorizons.angelica.proxy.ClientProxy; import me.jellysquid.mods.sodium.client.gui.options.named.BiomeBlendMode; import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality; +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling; import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode; @@ -61,7 +62,8 @@ public class SodiumGameOptions { final TextureMap atlas = mc.getTextureMapBlocks(); atlas.setMipmapLevels(mc.gameSettings.mipmapLevels); - atlas.setAnisotropicFiltering(resolvedAnisotropicFiltering()); + // Drivers may ignore NEAREST when anisotropy is enabled + atlas.setAnisotropicFiltering(1); } public static int resolvedAnisotropicFiltering() { @@ -153,6 +155,10 @@ public class SodiumGameOptions { } config.quality.guiBlockSupersampling = Integer.highestOneBit(MathHelper.clamp_int(config.quality.guiBlockSupersampling, 1, 16)); + if (config.quality.mipmapGeneration == null) { + config.quality.mipmapGeneration = MipmapGeneration.MODERN_VANILLA; + } + if (GLStateManager.capabilities != null) { if (!GLStateManager.capabilities.OpenGL32) { config.performance.cpuRenderAheadLimit = 0; @@ -251,6 +257,7 @@ public class SodiumGameOptions { public boolean useCeleritasSmoothLighting = true; public TextureFilterMode textureFilterMode = TextureFilterMode.RGSS_ANISOTROPIC; public TexelSampling texelSampling = TexelSampling.LINEAR; + public MipmapGeneration mipmapGeneration = MipmapGeneration.MODERN_VANILLA; public int guiBlockSupersampling = 1; } diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/options/named/MipmapGeneration.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/options/named/MipmapGeneration.java new file mode 100644 index 000000000..4b522d0e8 --- /dev/null +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/options/named/MipmapGeneration.java @@ -0,0 +1,33 @@ +package me.jellysquid.mods.sodium.client.gui.options.named; + +import com.gtnewhorizons.angelica.proxy.ClientProxy; +import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter; + +public enum MipmapGeneration implements NamedState { + VANILLA_1_7_10("sodium.options.mipmap_generation.vanilla_1_7_10"), + CELERITAS("sodium.options.mipmap_generation.celeritas"), + MODERN_VANILLA("sodium.options.mipmap_generation.modern_vanilla"); + + private final String name; + + MipmapGeneration(String name) { + this.name = name; + } + + public static MipmapGeneration current() { + return ClientProxy.options().quality.mipmapGeneration; + } + + public static boolean usesModernMipmaps() { + return current() == MODERN_VANILLA; + } + + public static AlphaCutoffParameter alphaFloorCutoff() { + return usesModernMipmaps() ? AlphaCutoffParameter.ONE_TENTH : AlphaCutoffParameter.ZERO; + } + + @Override + public String getKey() { + return this.name; + } +} diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java index 75cc38b96..c5adc8995 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java +++ b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java @@ -93,6 +93,7 @@ public class BlockRenderingSettings { private float ambientOcclusionLevel; private boolean disableDirectionalShading; private boolean useSeparateAo; + @Setter private boolean breaksAnisotropy; private boolean useExtendedVertexFormat; @Setter private boolean hasSnowyEntries; @@ -213,6 +214,10 @@ public class BlockRenderingSettings { return useSeparateAo; } + public boolean breaksAnisotropy() { + return breaksAnisotropy; + } + public void setUseSeparateAo(boolean useSeparateAo) { if (useSeparateAo == this.useSeparateAo) { return; diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkProgramOverrides.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkProgramOverrides.java index bacd17092..d8d8a986f 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkProgramOverrides.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkProgramOverrides.java @@ -27,7 +27,7 @@ import java.util.Optional; import java.util.function.Function; public class IrisCeleritasChunkProgramOverrides { - private final EnumMap> programs = new EnumMap<>(IrisTerrainPass.class); + private final EnumMap> programs = new EnumMap<>(IrisTerrainPass.class); private boolean shadersCreated = false; private int versionCounterForShaderReload = -1; @@ -80,19 +80,19 @@ public class IrisCeleritasChunkProgramOverrides { return key; } - private static final class SavedProgram extends GlProgram { - SavedProgram(int program, Function factory) { + private static final class SavedProgram extends GlProgram { + SavedProgram(int program, Function factory) { super(program, factory); } } @Nullable - private GlProgram createShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline, ChunkVertexType vertexType) { + private GlProgram createShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline, ChunkVertexType vertexType) { final CeleritasTerrainPipeline.PassInfo passInfo = pipeline.getPassInfo(pass); final String name = "iris:celeritas-chunk-" + pass.getName(); final BlendModeOverride blendOverride = passInfo.blendModeOverride(); final List bufferOverrides = passInfo.bufferBlendOverrides(); - final Function factory = context -> new IrisCeleritasChunkShaderInterface( + final Function factory = context -> new IrisCeleritasChunkShaderInterface( ((GlObject) context).handle(), context, pipeline, pass.isShadow(), blendOverride, bufferOverrides, pipeline.getCustomUniforms()); final ProgramBinaryCache.Key cacheKey = cacheKey(passInfo, vertexType); @@ -130,7 +130,7 @@ public class IrisCeleritasChunkProgramOverrides { builder.bindAttribute(attr.getName(), attrIndex++); } - final GlProgram program = builder.link(factory); + final GlProgram program = builder.link(factory); if (cacheKey != null) { ProgramBinaryCache.save(cacheKey, program.handle()); } @@ -169,7 +169,7 @@ public class IrisCeleritasChunkProgramOverrides { } @Nullable - public GlProgram getProgramOverride(TerrainRenderPass pass, RenderPassConfiguration configuration) { + public GlProgram getProgramOverride(TerrainRenderPass pass, RenderPassConfiguration configuration) { // Check for shader pack reload if (versionCounterForShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) { versionCounterForShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload(); @@ -186,23 +186,13 @@ public class IrisCeleritasChunkProgramOverrides { createShaders(celeritasPipeline, configuration); } - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + final boolean isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); + if (isShadow) { if (celeritasPipeline != null && !celeritasPipeline.hasShadowPass()) { throw new IllegalStateException("Shadow program requested, but shader pack has no shadow pass"); } - if (pass.isReverseOrder()) { - return programs.get(IrisTerrainPass.SHADOW_TRANSLUCENT); - } - return programs.get(pass.supportsFragmentDiscard() ? IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW); - } else { - if (pass.supportsFragmentDiscard()) { - return programs.get(IrisTerrainPass.GBUFFER_CUTOUT); - } else if (pass.isReverseOrder()) { - return programs.get(IrisTerrainPass.GBUFFER_TRANSLUCENT); - } else { - return programs.get(IrisTerrainPass.GBUFFER_SOLID); - } } + return programs.get(IrisTerrainPass.fromTerrainPass(pass, isShadow)); } public void deleteShaders() { diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java index c38c1fc91..b0ad197a9 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java @@ -241,20 +241,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { } final boolean isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); - final IrisTerrainPass irisPass; - if (isShadow) { - if (pass.isReverseOrder()) { - irisPass = IrisTerrainPass.SHADOW_TRANSLUCENT; - } else { - irisPass = pass.supportsFragmentDiscard() ? IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW; - } - } else if (pass.isReverseOrder()) { - irisPass = IrisTerrainPass.GBUFFER_TRANSLUCENT; - } else if (pass.supportsFragmentDiscard()) { - irisPass = IrisTerrainPass.GBUFFER_CUTOUT; - } else { - irisPass = IrisTerrainPass.GBUFFER_SOLID; - } + final IrisTerrainPass irisPass = IrisTerrainPass.fromTerrainPass(pass, isShadow); final GlFramebuffer framebuffer = pipeline.getPassInfo(irisPass).framebuffer(); if (framebuffer != null) { diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java index 686d3cb28..f2bef1d1a 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java @@ -40,7 +40,7 @@ public class IrisCeleritasShaderProvider implements IrisShaderProvider { @Override @Nullable - public GlProgram getShaderOverride(TerrainRenderPass pass) { + public GlProgram getShaderOverride(TerrainRenderPass pass) { if (!isShadersEnabled() || renderPassConfiguration == null) { return null; } diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisTerrainPass.java b/src/main/java/net/coderbot/iris/celeritas/IrisTerrainPass.java index 38a970598..8843a9f6f 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisTerrainPass.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisTerrainPass.java @@ -41,10 +41,10 @@ public enum IrisTerrainPass { return SHADOW_TRANSLUCENT; } return pass.supportsFragmentDiscard() ? SHADOW_CUTOUT : SHADOW; - } else if (pass.supportsFragmentDiscard()) { - return GBUFFER_CUTOUT; } else if (pass.isReverseOrder()) { return GBUFFER_TRANSLUCENT; + } else if (pass.supportsFragmentDiscard()) { + return GBUFFER_CUTOUT; } else { return GBUFFER_SOLID; } diff --git a/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java b/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java index b46fb2e9c..d95501fe6 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java +++ b/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java @@ -93,6 +93,7 @@ public final class ComputeProgram extends GlResource { public static void unbind() { ProgramUniforms.clearActiveUniforms(); + ProgramSamplers.clearActiveSamplers(); GLStateManager.glUseProgram(0); } diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java b/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java index f08c1b6f4..ba079434b 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java @@ -18,6 +18,7 @@ import com.gtnewhorizons.angelica.glsm.texture.TextureType; import org.jetbrains.annotations.Nullable; import java.util.function.IntSupplier; +import java.util.function.Supplier; public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHolder, ImageHolder { private final int program; @@ -196,17 +197,17 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo } @Override - public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { + public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { return samplers.addDefaultSampler(type, texture, notifier, sampler, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) { + public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, String... names) { return samplers.addDynamicSampler(type, texture, sampler, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { + public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { return samplers.addDynamicSampler(type, texture, notifier, sampler, names); } diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java b/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java index 4f19b9281..de8247e2e 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.IntSupplier; +import java.util.function.Supplier; public class ProgramSamplers { private static ProgramSamplers active; @@ -39,23 +40,25 @@ public class ProgramSamplers { active = this; - if (initializer != null) { - for (GlUniform1iCall call : initializer) { - RenderSystem.uniform1i(call.getLocation(), call.getValue()); + int activeTexture = GLStateManager.getActiveTextureUnit(); + try { + if (initializer != null) { + for (GlUniform1iCall call : initializer) { + RenderSystem.uniform1i(call.getLocation(), call.getValue()); + } + + initializer = null; } - initializer = null; + for (int i = 0, n = samplerBindings.size(); i < n; i++) { + samplerBindings.get(i).update(); + } + } catch (RuntimeException | Error e) { + clearActiveSamplers(); + throw e; + } finally { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture); } - - // We need to keep the active texture intact, since if we mess it up - // in the middle of RenderType setup, bad things will happen. - int activeTexture = GLStateManager.getActiveTextureUnit(); - - for (int i = 0, n = samplerBindings.size(); i < n; i++) { - samplerBindings.get(i).update(); - } - - GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture); } public void removeListeners() { @@ -70,6 +73,7 @@ public class ProgramSamplers { if (active != null) { active.removeListeners(); } + RenderSystem.unbindAllSamplers(); } public static Builder builder(int program, Set reservedTextureUnits) { @@ -148,31 +152,30 @@ public class ProgramSamplers { } @Override - public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { + public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { if (nextUnit != 0) { // TODO: Relax this restriction! throw new IllegalStateException("Texture unit 0 is already used."); } - if (notifier != null) { - notifiersToReset.add(notifier); - } - return addDynamicSampler(type, texture, sampler, true, notifier, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) { + public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, String... names) { return addDynamicSampler(type, texture, sampler, false, null, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { - notifiersToReset.add(notifier); + public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { return addDynamicSampler(type, texture, sampler, false, notifier, names); } - private boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, boolean used, ValueUpdateNotifier notifier, String... names) { + private boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, boolean used, ValueUpdateNotifier notifier, String... names) { + if (notifier != null) { + notifiersToReset.add(notifier); + } + for (String name : names) { int location = RenderSystem.getUniformLocation(program, name); @@ -236,26 +239,22 @@ public class ProgramSamplers { this.deactivatedOverrides = deactivatedOverrides.build(); } - private IntSupplier getOverride(IntSupplier existing, String... names) { + private TextureAccess getOverride(String... names) { for (String name : names) { if (customTextureIds.containsKey(name) && !deactivatedOverrides.contains(name)) { - return customTextureIds.get(name).getTextureId(); + return customTextureIds.get(name); } } - return existing; + return null; } @Override public void addExternalSampler(int textureUnit, String... names) { - IntSupplier override = getOverride(null, names); + TextureAccess override = getOverride(names); if (override != null) { - if (textureUnit == 0) { - samplerHolder.addDefaultSampler(override, names); - } else { - samplerHolder.addDynamicSampler(override, names); - } + addOverride(override, textureUnit == 0, names); } else { samplerHolder.addExternalSampler(textureUnit, names); } @@ -267,21 +266,34 @@ public class ProgramSamplers { } @Override - public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { - texture = getOverride(texture, names); - return samplerHolder.addDefaultSampler(type, texture, notifier, sampler, names); + public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { + return addSampler(type, texture, notifier, sampler, true, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) { - texture = getOverride(texture, names); - return samplerHolder.addDynamicSampler(type, texture, sampler, names); + public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, String... names) { + return addSampler(type, texture, null, sampler, false, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { - texture = getOverride(texture, names); - return samplerHolder.addDynamicSampler(type, texture, notifier, sampler, names); + public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { + return addSampler(type, texture, notifier, sampler, false, names); + } + + private boolean addSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, boolean defaultSampler, String... names) { + final TextureAccess override = getOverride(names); + if (override != null) { + return addOverride(override, defaultSampler, names); + } + return defaultSampler + ? samplerHolder.addDefaultSampler(type, texture, notifier, sampler, names) + : samplerHolder.addDynamicSampler(type, texture, notifier, sampler, names); + } + + private boolean addOverride(TextureAccess override, boolean defaultSampler, String... names) { + return defaultSampler + ? samplerHolder.addDefaultSampler(override.getType(), override.getTextureId(), null, null, names) + : samplerHolder.addDynamicSampler(override.getType(), override.getTextureId(), null, names); } } } diff --git a/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java b/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java index 7ca3a30f7..ebf3ea5a1 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java +++ b/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java @@ -7,8 +7,10 @@ import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; +import java.util.function.Supplier; + public class GlSampler extends GlObject { - public GlSampler(boolean linear, boolean mipmapped, boolean shadow, boolean hardwareShadow) { + public GlSampler(boolean linear, boolean linearMips, boolean mipmapped, boolean shadow, boolean hardwareShadow, boolean clamp) { if (!RenderSystem.supportsSamplerObjects()) { this.setHandle(0); return; @@ -16,13 +18,16 @@ public class GlSampler extends GlObject { this.setHandle(RenderSystem.genSampler()); - RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST); RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MAG_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST); - RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); - RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); + RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_S, clamp ? GL12.GL_CLAMP_TO_EDGE : GL11.GL_REPEAT); + RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_T, clamp ? GL12.GL_CLAMP_TO_EDGE : GL11.GL_REPEAT); if (mipmapped) { - RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST_MIPMAP_NEAREST); + RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linearMips + ? (linear ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST_MIPMAP_LINEAR) + : (linear ? GL11.GL_LINEAR_MIPMAP_NEAREST : GL11.GL_NEAREST_MIPMAP_NEAREST)); + } else { + RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST); } if (hardwareShadow) { @@ -38,4 +43,9 @@ public class GlSampler extends GlObject { public int getId() { return handle(); } + + public static int idOf(Supplier supplier) { + final GlSampler sampler = supplier == null ? null : supplier.get(); + return sampler == null ? 0 : sampler.getId(); + } } diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java b/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java index e213da29c..6f627bdf9 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java +++ b/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java @@ -5,20 +5,21 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier; import com.gtnewhorizons.angelica.glsm.texture.TextureType; import java.util.function.IntSupplier; +import java.util.function.Supplier; public class SamplerBinding { private final Runnable updateListener = this::updateSampler; private final TextureType textureType; private final int textureUnit; private final IntSupplier texture; - private final int sampler; + private final Supplier sampler; private final ValueUpdateNotifier notifier; - public SamplerBinding(TextureType type, int textureUnit, IntSupplier texture, GlSampler sampler, ValueUpdateNotifier notifier) { + public SamplerBinding(TextureType type, int textureUnit, IntSupplier texture, Supplier sampler, ValueUpdateNotifier notifier) { this.textureType = type; this.textureUnit = textureUnit; this.texture = texture; - this.sampler = sampler == null ? 0 : sampler.getId(); + this.sampler = sampler; this.notifier = notifier; } @@ -31,7 +32,7 @@ public class SamplerBinding { } private void updateSampler() { - RenderSystem.bindSamplerToUnit(textureUnit, sampler); + RenderSystem.bindSamplerToUnit(textureUnit, GlSampler.idOf(sampler)); RenderSystem.bindTextureToUnit(textureType.getGlType(), textureUnit, texture.getAsInt()); } } diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java b/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java index 696f5ccda..c40e412ef 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java +++ b/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java @@ -4,6 +4,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier; import com.gtnewhorizons.angelica.glsm.texture.TextureType; import java.util.function.IntSupplier; +import java.util.function.Supplier; public interface SamplerHolder { void addExternalSampler(int textureUnit, String... names); @@ -20,7 +21,7 @@ public interface SamplerHolder { return addDefaultSampler(TextureType.TEXTURE_2D, texture, null, null, names); } - boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names); + boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names); default boolean addDynamicSampler(IntSupplier texture, String... names) { return addDynamicSampler(TextureType.TEXTURE_2D, texture, null, names); @@ -30,11 +31,11 @@ public interface SamplerHolder { return addDynamicSampler(type, texture, null, names); } - boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names); + boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, String... names); default boolean addDynamicSampler(IntSupplier texture, ValueUpdateNotifier notifier, String... names) { return addDynamicSampler(TextureType.TEXTURE_2D, texture, notifier, null, names); } - boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names); + boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names); } diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 822090bb6..4f03b9c53 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -9,6 +9,7 @@ import com.google.common.primitives.Ints; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLDebug; +import lombok.Getter; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; import org.joml.Matrix3f; @@ -25,6 +26,7 @@ import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; import com.gtnewhorizons.angelica.rendering.tesr.TesrInstancingPipeline; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; import net.coderbot.iris.Iris; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; @@ -52,6 +54,7 @@ import net.coderbot.iris.gl.program.Program; import net.coderbot.iris.gl.program.ProgramBuilder; import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; +import net.coderbot.iris.gl.sampler.GlSampler; import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.state.FogMode; import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; @@ -232,6 +235,13 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private boolean shouldBindPBR; private int currentNormalTexture; private int currentSpecularTexture; + @Getter + private GlSampler normalSampler; + @Getter + private GlSampler specularSampler; + private TextureFormat samplerFormat; + private int samplerAnisotropy = -1; + private boolean samplerBreaksAnisotropy; private PackDirectives packDirectives; private final Set activeFeatures; private final ProgramFallbackResolver resolver; @@ -377,7 +387,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programs.getPackDirectives().getAmbientOcclusionLevel()); BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); BlockRenderingSettings.INSTANCE.setUseSeparateAo(programs.getPackDirectives().shouldUseSeparateAo()); + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(programs.getPackDirectives().breaksAnisotropy()); BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(true); + updatePbrSamplers(TextureFormatLoader.getFormat(), SodiumGameOptions.resolvedAnisotropicFiltering()); // Don't clobber anything in texture unit 0. It probably won't cause issues, but we're just being cautious here. GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); @@ -2293,6 +2305,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return; } + updatePbrSamplers(TextureFormatLoader.getFormat(), SodiumGameOptions.resolvedAnisotropicFiltering()); + isRenderingFullScreenPass = false; isRenderingWorld = true; isBeforeTranslucent = true; @@ -2517,6 +2531,18 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return currentSpecularTexture; } + void updatePbrSamplers(TextureFormat format, int anisotropy) { + final boolean breaksAnisotropy = BlockRenderingSettings.INSTANCE.breaksAnisotropy(); + if (samplerFormat == format && samplerAnisotropy == anisotropy && samplerBreaksAnisotropy == breaksAnisotropy) { + return; + } + normalSampler = IrisSamplers.getPbrSampler(format, PBRType.NORMAL, anisotropy); + specularSampler = IrisSamplers.getPbrSampler(format, PBRType.SPECULAR, anisotropy); + samplerFormat = format; + samplerAnisotropy = anisotropy; + samplerBreaksAnisotropy = breaksAnisotropy; + } + @Override public void onBindTexture(int id) { if (shouldBindPBR && isRenderingWorld) { @@ -2536,12 +2562,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R BatchStateGuard.suspend(); try { - final TextureFormat textureFormat = TextureFormatLoader.getFormat(); - if (textureFormat != null) { - textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); - textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); - } - PBRTextureManager.notifyPBRTexturesChanged(); } finally { BatchStateGuard.resume(); diff --git a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java index 9d249c452..81828bc9e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java @@ -28,6 +28,7 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli public FixedFunctionWorldRenderingPipeline() { BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); BlockRenderingSettings.INSTANCE.setUseSeparateAo(false); + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(false); BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f); BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false); BlockRenderingSettings.INSTANCE.setBlockTypeIds(null); diff --git a/src/main/java/net/coderbot/iris/pipeline/VertexWriteReplays.java b/src/main/java/net/coderbot/iris/pipeline/VertexWriteReplays.java index 971fa73ec..bcaaa0d16 100644 --- a/src/main/java/net/coderbot/iris/pipeline/VertexWriteReplays.java +++ b/src/main/java/net/coderbot/iris/pipeline/VertexWriteReplays.java @@ -27,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.IntSupplier; +import java.util.function.Supplier; /** * SDL-GPU only allows image writes from compute, so a gbuffers/shadow vertex shader that writes images gets a compute @@ -105,7 +106,7 @@ final class VertexWriteReplays { final List samplerNames; final int[] samplerUnits; final IntSupplier[] samplerTextures; - final int[] samplerObjects; + final IntSupplier[] samplerObjects; ResourceCollector(List imageNames, List samplerNames) { this.imageNames = imageNames; @@ -114,7 +115,7 @@ final class VertexWriteReplays { this.samplerUnits = new int[samplerNames.size()]; Arrays.fill(samplerUnits, -1); this.samplerTextures = new IntSupplier[samplerNames.size()]; - this.samplerObjects = new int[samplerNames.size()]; + this.samplerObjects = new IntSupplier[samplerNames.size()]; } @Override @@ -142,17 +143,17 @@ final class VertexWriteReplays { } @Override - public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { + public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { return addDynamicSampler(type, texture, notifier, sampler, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) { + public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier sampler, String... names) { return addDynamicSampler(type, texture, null, sampler, names); } @Override - public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) { + public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier sampler, String... names) { boolean used = false; for (String name : names) { final int index = samplerNames.indexOf(name); @@ -160,7 +161,7 @@ final class VertexWriteReplays { used = true; if (unassigned(index)) { samplerTextures[index] = texture; - samplerObjects[index] = sampler != null ? sampler.getId() : 0; + samplerObjects[index] = () -> GlSampler.idOf(sampler); } } return used; diff --git a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java b/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java index 473934a75..131db54b0 100644 --- a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java +++ b/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java @@ -3,7 +3,9 @@ package net.coderbot.iris.samplers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.rendering.TextureSamplers; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.gl.image.GlImage; import net.coderbot.iris.gl.sampler.GlSampler; @@ -11,12 +13,15 @@ import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.gl.texture.TextureAccess; import com.gtnewhorizons.angelica.glsm.texture.TextureType; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.rendertarget.RenderTargets; import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; import net.coderbot.iris.shaderpack.PackShadowDirectives; import net.coderbot.iris.shadows.ShadowRenderTargets; +import net.coderbot.iris.texture.format.TextureFormat; +import net.coderbot.iris.texture.pbr.PBRType; import net.minecraft.client.renderer.texture.AbstractTexture; import java.util.Set; @@ -39,6 +44,7 @@ public class IrisSamplers { private static GlSampler SHADOW_SAMPLER_NEAREST; private static GlSampler SHADOW_SAMPLER_LINEAR; + private static GlSampler MIPPED_NEAREST_NEAREST; private IrisSamplers() { // no construction allowed @@ -49,8 +55,23 @@ public class IrisSamplers { // Leave as null - callers handle null gracefully return; } - SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, true, true); - SHADOW_SAMPLER_LINEAR = new GlSampler(true, false, true, true); + SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, false, true, true, true); + SHADOW_SAMPLER_LINEAR = new GlSampler(true, true, false, true, true, true); + MIPPED_NEAREST_NEAREST = new GlSampler(false, false, true, false, false, true); + } + + public static GlSampler getTerrainSampler(int anisotropy) { + if (BlockRenderingSettings.INSTANCE.breaksAnisotropy()) { + anisotropy = 1; + } + return TextureSamplers.getTerrainSampler(false, anisotropy); + } + + public static GlSampler getPbrSampler(TextureFormat format, PBRType type, int anisotropy) { + if (format != null && !format.canInterpolateValues(type)) { + return MIPPED_NEAREST_NEAREST; + } + return getTerrainSampler(anisotropy); } public static void addRenderTargetSamplers(SamplerHolder samplers, Supplier> flipped, @@ -94,8 +115,8 @@ public class IrisSamplers { // Add the DH depth textures (stub implementation returns 0 until DH is integrated) if (pipeline != null) { - samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTex(), (GlSampler) null, "dhDepthTex", "dhDepthTex0"); - samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTexNoTranslucent(), (GlSampler) null, "dhDepthTex1"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTex(), "dhDepthTex", "dhDepthTex0"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTexNoTranslucent(), "dhDepthTex1"); } } @@ -137,13 +158,13 @@ public class IrisSamplers { final GlSampler sampler1 = separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(1) ? (shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST) : null); if (waterShadowEnabled) { - samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "watershadow"); - if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1", "shadow")) { + samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> sampler0, "shadowtex0", "watershadow"); + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> sampler1, "shadowtex1", "shadow")) { usage |= USAGE_SHADOWTEX1; } } else { - samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "shadow"); - if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1")) { + samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> sampler0, "shadowtex0", "shadow"); + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> sampler1, "shadowtex1")) { usage |= USAGE_SHADOWTEX1; } } @@ -176,12 +197,12 @@ public class IrisSamplers { // Hardware-filtered shadow samplers for separate HW sampler access if (shadowRenderTargets.isHardwareFiltered(0) && separateHardwareSamplers) { final GlSampler hwSampler0 = shadowRenderTargets.isLinearFiltered(0) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST; - samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, hwSampler0, "shadowtex0HW"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> hwSampler0, "shadowtex0HW"); } if (shadowRenderTargets.isHardwareFiltered(1) && separateHardwareSamplers) { final GlSampler hwSampler1 = shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST; - if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, hwSampler1, "shadowtex1HW")) { + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> hwSampler1, "shadowtex1HW")) { usage |= USAGE_SHADOWTEX1; } } @@ -207,8 +228,12 @@ public class IrisSamplers { samplers.addDynamicSampler(whitePixel::getGlTextureId, "lightmap"); } - samplers.addDynamicSampler(pipeline::getCurrentNormalTexture, StateUpdateNotifiers.normalTextureChangeNotifier, "normals"); - samplers.addDynamicSampler(pipeline::getCurrentSpecularTexture, StateUpdateNotifiers.specularTextureChangeNotifier, "specular"); + if (pipeline instanceof DeferredWorldRenderingPipeline deferred) { + samplers.addDynamicSampler(TextureType.TEXTURE_2D, pipeline::getCurrentNormalTexture, + StateUpdateNotifiers.normalTextureChangeNotifier, deferred::getNormalSampler, "normals"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, pipeline::getCurrentSpecularTexture, + StateUpdateNotifiers.specularTextureChangeNotifier, deferred::getSpecularSampler, "specular"); + } } public static int addWorldDepthSamplers(SamplerHolder samplers, RenderTargets renderTargets) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java b/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java index 2044c32fe..e9222a89a 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java +++ b/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java @@ -41,6 +41,7 @@ public class PackDirectives { private boolean weatherParticles; private boolean rainDepth; private boolean separateAo; + private boolean breaksAnisotropy; private boolean voxelizeLightBlocks; private boolean separateEntityDraws; private boolean frustumCulling; @@ -89,6 +90,7 @@ public class PackDirectives { weatherParticles = properties.getWeatherParticles().orElse(true); rainDepth = properties.getRainDepth().orElse(false); separateAo = properties.getSeparateAo().orElse(false); + breaksAnisotropy = properties.getBreaksAnisotropy().orElse(false); voxelizeLightBlocks = properties.getVoxelizeLightBlocks().orElse(false); separateEntityDraws = properties.getSeparateEntityDraws().orElse(false); frustumCulling = properties.getFrustumCulling().orElse(true); @@ -111,6 +113,7 @@ public class PackDirectives { this(supportedRenderTargets, new PackShadowDirectives(directives.getShadowDirectives())); cloudSetting = directives.cloudSetting; separateAo = directives.separateAo; + breaksAnisotropy = directives.breaksAnisotropy; voxelizeLightBlocks = directives.voxelizeLightBlocks; separateEntityDraws = directives.separateEntityDraws; frustumCulling = directives.frustumCulling; @@ -166,6 +169,10 @@ public class PackDirectives { return separateAo; } + public boolean breaksAnisotropy() { + return breaksAnisotropy; + } + public boolean shouldVoxelizeLightBlocks() { return voxelizeLightBlocks; } diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java index 5619077fb..760c673e0 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java +++ b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java @@ -87,6 +87,7 @@ public class ShaderProperties { @Getter private OptionalBoolean concurrentCompute = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean beaconBeamDepth = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean separateAo = OptionalBoolean.DEFAULT; + @Getter private OptionalBoolean breaksAnisotropy = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean voxelizeLightBlocks = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean separateEntityDraws = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean frustumCulling = OptionalBoolean.DEFAULT; @@ -221,6 +222,7 @@ public class ShaderProperties { handleBooleanDirective(key, value, "allowConcurrentCompute", bool -> concurrentCompute = bool); handleBooleanDirective(key, value, "beacon.beam.depth", bool -> beaconBeamDepth = bool); handleBooleanDirective(key, value, "separateAo", bool -> separateAo = bool); + handleBooleanDirective(key, value, "breaksAnisotropy", bool -> breaksAnisotropy = bool); handleBooleanDirective(key, value, "voxelizeLightBlocks", bool -> voxelizeLightBlocks = bool); handleBooleanDirective(key, value, "separateEntityDraws", bool -> separateEntityDraws = bool); handleBooleanDirective(key, value, "frustum.culling", bool -> frustumCulling = bool); diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java b/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java index 1d9209359..a8c8cc2b7 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java +++ b/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java @@ -113,7 +113,7 @@ public class PBRAtlasTexture extends AutoClosableAbstractTexture { protected void uploadSprite(TextureAtlasSprite sprite) { final int gutter = ((SpriteExtension) sprite).angelica$getGutterWidth(); - if (sprite.animationMetadata.getFrameCount() > 1) { + if (sprite.animationMetadata.getFrameCount() > 0) { final AnimationMetadataSection metadata = sprite.animationMetadata; final int frameCount = sprite.getFrameCount(); for (int frame = sprite.frameCounter; frame >= 0; frame--) { diff --git a/src/main/resources/assets/angelica/lang/en_US.lang b/src/main/resources/assets/angelica/lang/en_US.lang index 48e2de526..55c7754f0 100644 --- a/src/main/resources/assets/angelica/lang/en_US.lang +++ b/src/main/resources/assets/angelica/lang/en_US.lang @@ -68,6 +68,11 @@ sodium.options.entity_shadows.tooltip=If enabled, basic shadows will be rendered sodium.options.vignette.name=Vignette sodium.options.vignette.tooltip=If enabled, a vignette effect will be rendered on the player's view. This is very unlikely to make a difference to frame rates unless you are fill-rate limited. sodium.options.mipmap_levels.tooltip=Controls the number of mipmaps which will be used for block model textures. Higher values provide better rendering of blocks in the distance, but may adversely affect performance with many animated textures. +sodium.options.mipmap_generation.name=Mipmap Generation +sodium.options.mipmap_generation.tooltip=Chooses how smaller versions of textures are generated. +sodium.options.mipmap_generation.vanilla_1_7_10=Minecraft 1.7.10 +sodium.options.mipmap_generation.celeritas=Celeritas +sodium.options.mipmap_generation.modern_vanilla=Minecraft 26.2 sodium.options.use_vertex_objects.name=Vertex Array Objects sodium.options.use_vertex_objects.tooltip=Helps to improve performance by moving information about how vertex data should be rendered into the driver, allowing it to better optimize for repeated rendering of the same objects. There is generally no reason to disable this unless you're using incompatible mods. sodium.options.use_block_face_culling.name=Block Face Culling diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinRenderItem_GuiSampler.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinRenderItem_GuiSampler.java new file mode 100644 index 000000000..4f1a9404b --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinRenderItem_GuiSampler.java @@ -0,0 +1,33 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.textures; + +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.rendering.RenderingState; +import com.gtnewhorizons.angelica.rendering.TextureSamplers; +import net.minecraft.client.renderer.entity.RenderItem; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(RenderItem.class) +public class MixinRenderItem_GuiSampler { + + @Surround( + method = "renderItemIntoGUI(Lnet/minecraft/client/gui/FontRenderer;Lnet/minecraft/client/renderer/texture/TextureManager;Lnet/minecraft/item/ItemStack;IIZ)V", + remap = false, + at = { + @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBlocks;renderBlockAsItem(Lnet/minecraft/block/Block;IF)V", remap = true), + @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderItem;renderIcon(IILnet/minecraft/util/IIcon;II)V", remap = true) + } + ) + private void angelica$beginGuiSampling() { + @Surround.Carry("gui") final boolean gui = !RenderingState.INSTANCE.isRenderingWorld(); + @Surround.Carry("sampler") final int sampler = gui ? GLStateManager.getSamplerBinding(0) : 0; + if (gui) RenderSystem.bindSamplerToUnit(0, TextureSamplers.getGuiSampler().getId()); + } + + @Surround.Finally + private void angelica$endGuiSampling(@Surround.Carry("gui") boolean gui, @Surround.Carry("sampler") int sampler) { + if (gui) RenderSystem.bindSamplerToUnit(0, sampler); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinEffectRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinEffectRenderer.java new file mode 100644 index 000000000..d678501bd --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinEffectRenderer.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.features.mipmaps; + +import com.gtnewhorizons.angelica.rendering.particles.ParticleAlphaCutoff; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.particle.EffectRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(EffectRenderer.class) +public class MixinEffectRenderer { + + @ModifyArg(method = "renderParticles", + at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glAlphaFunc(IF)V", ordinal = 0, remap = false), + index = 1) + private float angelica$terrainParticleCutoff(float alphaRef, @Local(name = "k") int layer) { + return ParticleAlphaCutoff.forLayer(alphaRef, layer); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureAtlasSprite.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureAtlasSprite.java index be9e93c6a..b001ed1e7 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureAtlasSprite.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureAtlasSprite.java @@ -1,12 +1,19 @@ package com.gtnewhorizons.angelica.mixins.early.celeritas.features.mipmaps; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.rendering.TextureAtlasType; import com.gtnewhorizons.angelica.rendering.celeritas.SpriteExtension; import com.gtnewhorizons.angelica.utils.MipmapGenerator; import com.gtnewhorizons.angelica.utils.MipmapStrategies; import com.gtnewhorizons.angelica.utils.MipmapStrategy; import com.gtnewhorizons.angelica.utils.SpritePadding; +import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.data.AnimationFrame; +import net.minecraft.client.resources.data.AnimationMetadataSection; +import net.minecraft.crash.CrashReport; +import net.minecraft.crash.CrashReportCategory; +import net.minecraft.util.ReportedException; import org.embeddedt.embeddium.api.util.ColorARGB; import org.embeddedt.embeddium.impl.render.chunk.sprite.SpriteTransparencyLevel; import org.spongepowered.asm.mixin.Final; @@ -15,10 +22,13 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -38,6 +48,12 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { @Shadow public List framesTextureData; @Shadow + public AnimationMetadataSection animationMetadata; + @Shadow + protected int width; + @Shadow + protected int height; + @Shadow @Final private String iconName; @Unique @@ -47,7 +63,9 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { @Unique private boolean celeritas$mipmapStrategyExplicit; @Unique - private int celeritas$textureType; + private int angelica$textureType; + @Unique + private float angelica$alphaCutoffBias; @Unique private boolean celeritas$hasTransparentTexels; @Unique @@ -56,6 +74,10 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { private int angelica$gutterWidth; @Unique private boolean angelica$uploaded; + @Unique + private int[][] angelica$animationImage; + @Unique + private int angelica$animationWidth; @Unique private static boolean celeritas$isAlwaysTranslucent(String name) { @@ -67,18 +89,145 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { return false; } - @Inject(method = "generateMipmaps", at = @At("HEAD")) + @Unique + private static int celeritas$classifyPixels(int[] pixels, int seen) { + for (int base = 0; base < pixels.length; base += SCAN_BLOCK) { + final int end = Math.min(base + SCAN_BLOCK, pixels.length); + for (int i = base; i < end; i++) { + final int alpha = ColorARGB.unpackAlpha(pixels[i]); + if (alpha == 0) { + seen |= SEEN_TRANSPARENT; + } else if (alpha < 255) { + seen |= SEEN_TRANSLUCENT; + } + } + if (seen == SEEN_ALL) break; + } + return seen; + } + + @Shadow + public abstract void setFramesTextureData(List frames); + + @Inject(method = "generateMipmaps", at = @At("HEAD"), cancellable = true) private void celeritas$processSprite(int level, CallbackInfo ci) { this.celeritas$hasTransparentTexels = false; this.celeritas$alwaysTranslucent = celeritas$isAlwaysTranslucent(this.iconName); - if (this.framesTextureData.isEmpty()) { + this.angelica$animationImage = null; return; } + if (!MipmapGeneration.usesModernMipmaps() || !angelica$updateAnimationImage(level)) { + this.angelica$animationImage = null; + } celeritas$classifyFrames(); if (this.celeritas$alwaysTranslucent) { this.celeritas$transparencyLevel = SpriteTransparencyLevel.TRANSLUCENT; } + if (this.angelica$animationImage != null) { + angelica$generateAnimationMipmaps(level); + ci.cancel(); + } + } + + @ModifyArg(method = "loadSprite", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;getFrameTextureData([[IIII)[[I"), + index = 0) + private int[][] angelica$rememberAnimationImage(int[][] image) { + if (MipmapGeneration.usesModernMipmaps()) { + this.angelica$animationImage = image; + this.angelica$animationWidth = this.width; + } + return image; + } + + @Inject(method = {"setFramesTextureData", "clearFramesTextureData", "initSprite"}, at = @At("HEAD")) + private void angelica$releaseAnimationImage(CallbackInfo ci) { + this.angelica$animationImage = null; + } + + @Unique + private boolean angelica$updateAnimationImage(int mipLevel) { + if (this.angelica$animationImage == null || this.width != this.angelica$animationWidth || this.height != this.width) { + return false; + } + // 1.7.10 can request levels beyond the frame's power-of-two factor + if (Integer.numberOfTrailingZeros(this.width) < mipLevel) { + return false; + } + for (int frameIndex = 0; frameIndex < this.framesTextureData.size(); frameIndex++) { + final int[][] frame = this.framesTextureData.get(frameIndex); + if (frame == null) continue; + for (int level = 0; level < frame.length; level++) { + if (frame[level] == null) continue; + final int size = (this.width >> level) * (this.height >> level); + if (level >= this.angelica$animationImage.length || this.angelica$animationImage[level] == null + || frame[level].length != size || (long) (frameIndex + 1) * size > this.angelica$animationImage[level].length) { + return false; + } + System.arraycopy(frame[level], 0, this.angelica$animationImage[level], frameIndex * size, size); + } + } + return true; + } + + @Unique + private void angelica$generateAnimationMipmaps(int level) { + try { + final int[][] mips = celeritas$generateMipmapData(level, this.width, this.angelica$animationImage); + final List frames = new ArrayList<>(this.framesTextureData.size()); + for (int frameIndex = 0; frameIndex < this.framesTextureData.size(); frameIndex++) { + final int[][] existing = this.framesTextureData.get(frameIndex); + if (existing == null) continue; + final int[][] frame = Arrays.copyOf(existing, level + 1); + for (int mip = 0; mip <= level; mip++) { + final int size = (this.width >> mip) * (this.height >> mip); + if (frame[mip] == null || frame[mip].length != size) { + frame[mip] = new int[size]; + } + System.arraycopy(mips[mip], frameIndex * size, frame[mip], 0, size); + } + frames.add(frame); + } + angelica$remapAnimationFrames(); + this.setFramesTextureData(frames); + } catch (Throwable error) { + final CrashReport report = CrashReport.makeCrashReport(error, "Generating mipmaps for animation"); + final CrashReportCategory category = report.makeCategory("Sprite being generated"); + category.addCrashSection("Sprite", this.iconName); + category.addCrashSection("Frame count", this.framesTextureData.size()); + throw new ReportedException(report); + } finally { + this.angelica$animationImage = null; + } + } + + @Inject(method = "generateMipmaps", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;setFramesTextureData(Ljava/util/List;)V")) + private void angelica$remapGeneratedFrames(int level, CallbackInfo ci) { + angelica$remapAnimationFrames(); + } + + @Unique + private void angelica$remapAnimationFrames() { + if (this.animationMetadata == null || !this.framesTextureData.contains(null)) { + return; + } + final int[] indices = new int[this.framesTextureData.size()]; + int next = 0; + for (int i = 0; i < indices.length; i++) { + indices[i] = this.framesTextureData.get(i) == null ? -1 : next++; + } + final AnimationMetadataSection metadata = this.animationMetadata; + final List frames = new ArrayList<>(metadata.getFrameCount()); + for (int i = 0; i < metadata.getFrameCount(); i++) { + final int sourceIndex = metadata.getFrameIndex(i); + final int frameIndex = sourceIndex >= 0 && sourceIndex < indices.length ? indices[sourceIndex] : -1; + frames.add(new AnimationFrame(frameIndex, + metadata.frameHasTime(i) ? metadata.getFrameTimeSingle(i) : -1)); + } + this.animationMetadata = new AnimationMetadataSection(frames, + metadata.getFrameWidth(), metadata.getFrameHeight(), metadata.getFrameTime()); } @Unique @@ -91,7 +240,7 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { boolean explicit = this.celeritas$mipmapStrategyExplicit; if (strategy == null) { - strategy = MipmapStrategies.inheritedFor(this.celeritas$textureType, this.iconName); + strategy = MipmapStrategies.inheritedFor(this.angelica$textureType, this.iconName); explicit = false; } @@ -106,24 +255,16 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { private void celeritas$classifyFrames() { int seen = 0; - outer: - for (final int[][] frame : this.framesTextureData) { - if (frame == null || frame.length == 0 || frame[0] == null) { - continue; - } - final int[] pixels = frame[0]; - for (int base = 0; base < pixels.length; base += SCAN_BLOCK) { - final int end = Math.min(base + SCAN_BLOCK, pixels.length); - for (int i = base; i < end; i++) { - final int alpha = ColorARGB.unpackAlpha(pixels[i]); - if (alpha == 0) { - seen |= SEEN_TRANSPARENT; - } else if (alpha < 255) { - seen |= SEEN_TRANSLUCENT; - } + if (this.angelica$animationImage != null) { + seen = celeritas$classifyPixels(this.angelica$animationImage[0], seen); + } else { + for (final int[][] frame : this.framesTextureData) { + if (frame == null || frame.length == 0 || frame[0] == null) { + continue; } + seen = celeritas$classifyPixels(frame[0], seen); if (seen == SEEN_ALL) { - break outer; + break; } } } @@ -144,11 +285,17 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { at = @At( value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureUtil;generateMipmapData(II[[I)[[I")) - private int[][] celeritas$generateMipmapData(int p_147949_0_, int p_147949_1_, int[][] p_147949_2_) { - final MipmapStrategy strategy = celeritas$resolvedStrategy(); + private int[][] celeritas$generateMipmapData(int level, int width, int[][] pixels) { + return MipmapGenerator.generateMipLevels(level, width, pixels, celeritas$resolvedStrategy(), + this.celeritas$hasTransparentTexels, MipmapGeneration.current(), + this.angelica$alphaCutoffBias, this.angelica$textureType == TextureAtlasType.ITEM); + } - return MipmapGenerator.generateMipLevels(p_147949_0_, p_147949_1_, p_147949_2_, strategy, - this.celeritas$hasTransparentTexels); + @Inject(method = "fixTransparentPixels", at = @At("HEAD"), cancellable = true) + private void angelica$useModernTexturePreparation(int[][] pixels, CallbackInfo ci) { + if (MipmapGeneration.usesModernMipmaps()) { + ci.cancel(); + } } /** @@ -176,7 +323,7 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureUtil;uploadTextureMipmap([[IIIIIZZ)V")) private void angelica$uploadPaddedFrame(int[][] frameData, int width, int height, int originX, int originY, - boolean blur, boolean clamp) { + boolean blur, boolean clamp) { SpritePadding.uploadPadded(frameData, width, height, originX, originY, this.angelica$gutterWidth, blur, clamp); } @@ -209,9 +356,18 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension { } @Override - public void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit, int textureType) { + public void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit) { this.celeritas$mipmapStrategy = strategy; this.celeritas$mipmapStrategyExplicit = explicit; - this.celeritas$textureType = textureType; + } + + @Override + public void angelica$setTextureType(int textureType) { + this.angelica$textureType = textureType; + } + + @Override + public void angelica$setAlphaCutoffBias(float bias) { + this.angelica$alphaCutoffBias = bias; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSection.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSection.java index e11bbc994..23849c699 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSection.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSection.java @@ -12,6 +12,9 @@ public class MixinTextureMetadataSection implements TextureMetadataExtension { @Unique private MipmapStrategy angelica$mipmapStrategy; + @Unique + private float angelica$alphaCutoffBias; + @Override public void angelica$setMipmapStrategy(MipmapStrategy strategy) { this.angelica$mipmapStrategy = strategy; @@ -21,4 +24,14 @@ public class MixinTextureMetadataSection implements TextureMetadataExtension { public MipmapStrategy angelica$getMipmapStrategy() { return this.angelica$mipmapStrategy; } + + @Override + public void angelica$setAlphaCutoffBias(float bias) { + this.angelica$alphaCutoffBias = bias; + } + + @Override + public float angelica$getAlphaCutoffBias() { + return this.angelica$alphaCutoffBias; + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSectionSerializer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSectionSerializer.java index 88684ec98..9a662fa57 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSectionSerializer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/mipmaps/MixinTextureMetadataSectionSerializer.java @@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.lang.reflect.Type; /** - * Reads the modern {@code "mipmap_strategy"} key out of a sprite's {@code texture} mcmeta section. + * Reads modern mipmap settings from a sprite's {@code texture} mcmeta section. */ @Mixin(TextureMetadataSectionSerializer.class) public class MixinTextureMetadataSectionSerializer { @@ -23,13 +23,21 @@ public class MixinTextureMetadataSectionSerializer { @Inject( method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/client/resources/data/TextureMetadataSection;", at = @At("RETURN")) - private void angelica$readMipmapStrategy(JsonElement json, Type type, JsonDeserializationContext context, + private void angelica$readMipmapSettings(JsonElement json, Type type, JsonDeserializationContext context, CallbackInfoReturnable cir) { final TextureMetadataSection section = cir.getReturnValue(); if (section == null || !json.isJsonObject()) { return; } final JsonObject object = json.getAsJsonObject(); + final TextureMetadataExtension extension = (TextureMetadataExtension) section; + final JsonElement biasValue = object.get("alpha_cutoff_bias"); + if (biasValue != null && biasValue.isJsonPrimitive() && biasValue.getAsJsonPrimitive().isNumber()) { + final float parsed = biasValue.getAsFloat(); + if (Float.isFinite(parsed)) { + extension.angelica$setAlphaCutoffBias(parsed); + } + } if (!object.has("mipmap_strategy")) { return; } @@ -37,6 +45,6 @@ public class MixinTextureMetadataSectionSerializer { if (!value.isJsonPrimitive()) { return; } - ((TextureMetadataExtension) section).angelica$setMipmapStrategy(MipmapStrategy.byName(value.getAsString())); + extension.angelica$setMipmapStrategy(MipmapStrategy.byName(value.getAsString())); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/textures/MixinTextureMap.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/textures/MixinTextureMap.java index 55dd41656..078e62651 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/textures/MixinTextureMap.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/textures/MixinTextureMap.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.mixins.early.celeritas.features.textures; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.TextureMetadataExtension; +import com.gtnewhorizons.angelica.rendering.TextureAtlasType; import com.gtnewhorizons.angelica.rendering.celeritas.SpriteExtension; import com.gtnewhorizons.angelica.rendering.celeritas.TextureMapExtension; import com.gtnewhorizons.angelica.textures.atlas.AtlasAssembler; @@ -63,9 +64,14 @@ public class MixinTextureMap implements TextureMapExtension { @Unique private int celeritas$height; + @Unique + private boolean angelica$isBlockAtlas() { + return (Object) this == Minecraft.getMinecraft().getTextureMapBlocks(); + } + @Inject(method = { "loadTexture", "loadTextureAtlas" }, at = @At("HEAD")) private void angelica$applyAtlasSettings(CallbackInfo ci) { - if ((Object) this == Minecraft.getMinecraft().getTextureMapBlocks()) { + if (angelica$isBlockAtlas()) { SodiumGameOptions.applyAtlasSettings(); } } @@ -74,8 +80,7 @@ public class MixinTextureMap implements TextureMapExtension { method = "loadTextureAtlas", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/Stitcher;doStitch()V")) private void angelica$assignGutters(CallbackInfo ci) { - final boolean blocksAtlas = (Object) this == Minecraft.getMinecraft().getTextureMapBlocks(); - final int gutter = SpritePadding.gutterFor(this.mipmapLevels, blocksAtlas); + final int gutter = SpritePadding.gutterFor(this.mipmapLevels, angelica$isBlockAtlas()); for (TextureAtlasSprite sprite : this.mapRegisteredSprites.values()) { ((SpriteExtension) sprite).angelica$setGutterWidth(gutter); @@ -88,7 +93,7 @@ public class MixinTextureMap implements TextureMapExtension { */ @Inject(method = "registerIcons", at = @At("HEAD")) private void angelica$resetMipmapStrategies(CallbackInfo ci) { - if (this.textureType == 0) { + if (this.textureType == TextureAtlasType.BLOCK) { MipmapStrategies.reset(); } } @@ -118,6 +123,16 @@ public class MixinTextureMap implements TextureMapExtension { MipmapStrategies.recordSprite(this.textureType, p_94245_1_); } + @Inject( + method = "loadTextureAtlas", + at = @At(value = "INVOKE", target = "Ljava/util/Map;entrySet()Ljava/util/Set;", remap = false)) + private void angelica$assignSpriteAtlas(CallbackInfo ci) { + for (TextureAtlasSprite sprite : this.mapRegisteredSprites.values()) { + ((SpriteExtension) sprite).angelica$setTextureType(this.textureType); + } + ((SpriteExtension) this.missingImage).angelica$setTextureType(this.textureType); + } + /** * Forces vanilla's unpadded branch. */ @@ -156,7 +171,7 @@ public class MixinTextureMap implements TextureMapExtension { } /** - * Assigns the sprite's mipmap strategy. + * Assigns the sprite's mipmap settings, resetting metadata defaults on resource reload. */ @Inject( method = "loadTextureAtlas", @@ -165,20 +180,21 @@ public class MixinTextureMap implements TextureMapExtension { target = "Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;loadSprite([Ljava/awt/image/BufferedImage;Lnet/minecraft/client/resources/data/AnimationMetadataSection;Z)V")) private void celeritas$assignMipmapStrategy(CallbackInfo ci, @Local(ordinal = 0) TextureAtlasSprite sprite, @Local(ordinal = 0) TextureMetadataSection metadata) { - final MipmapStrategy declared = metadata != null - ? ((TextureMetadataExtension) metadata).angelica$getMipmapStrategy() - : null; + final SpriteExtension extension = (SpriteExtension) sprite; + final TextureMetadataExtension textureMetadata = (TextureMetadataExtension) metadata; + final MipmapStrategy declared = textureMetadata != null ? textureMetadata.angelica$getMipmapStrategy() : null; + extension.angelica$setAlphaCutoffBias(textureMetadata != null ? textureMetadata.angelica$getAlphaCutoffBias() : 0.0f); if (declared != null) { - ((SpriteExtension) sprite).celeritas$setMipmapStrategy(declared, true, this.textureType); + extension.celeritas$setMipmapStrategy(declared, true); } else { - ((SpriteExtension) sprite).celeritas$setMipmapStrategy( - MipmapStrategies.inheritedFor(this.textureType, sprite.getIconName()), false, this.textureType); + extension.celeritas$setMipmapStrategy( + MipmapStrategies.inheritedFor(this.textureType, sprite.getIconName()), false); } } @Inject(method = "loadTextureAtlas", at = @At("RETURN")) private void celeritas$generateQuadTree(CallbackInfo ci, @Local(ordinal = 0) Stitcher stitcher) { - if ((Object) this == Minecraft.getMinecraft().getTextureMapBlocks()) { + if (angelica$isBlockAtlas()) { GLStateManager.markTextureAsAtlas(((TextureMap) (Object) this).getGlTextureId(), ((SpriteExtension) this.missingImage).angelica$getGutterWidth()); SodiumGameOptions.recordAtlasMipmapClamp(Minecraft.getMinecraft().gameSettings.mipmapLevels, diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_MipmapCutoff.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_MipmapCutoff.java new file mode 100644 index 000000000..5cbbc956a --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_MipmapCutoff.java @@ -0,0 +1,21 @@ +package com.gtnewhorizons.angelica.mixins.late.client.dragonapi; + +import com.gtnewhorizons.angelica.rendering.particles.ParticleAlphaCutoff; +import com.llamalad7.mixinextras.sugar.Local; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Pseudo +@Mixin(targets = "Reika/DragonAPI/Extras/ThrottleableEffectRenderer", remap = false) +public class MixinThrottleableEffectRenderer_MipmapCutoff { + + @ModifyArg(method = "doRenderParticles", + at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glAlphaFunc(IF)V", ordinal = 0), + index = 1, + require = 1) + private float angelica$terrainParticleCutoff(float alphaRef, @Local(ordinal = 0) int layer) { + return ParticleAlphaCutoff.forLayer(alphaRef, layer); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/ChunkPassCleanupTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/ChunkPassCleanupTest.java new file mode 100644 index 000000000..6ba5780e3 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/ChunkPassCleanupTest.java @@ -0,0 +1,89 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.proxy.ClientProxy; +import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; +import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; +import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; +import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.gl.device.RenderDevice; +import org.embeddedt.embeddium.impl.gl.shader.GlProgram; +import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices; +import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; +import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; +import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter; +import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@GLCoreTest +class ChunkPassCleanupTest { + @Test + void failedIrisSetupRestoresThePassAndDoesNotRepeatCleanupOnAnEmptyPass() throws ReflectiveOperationException { + final IrisShaderProvider previous = IrisShaderProviderHolder.getProvider(); + final IrisShaderProvider provider = mock(IrisShaderProvider.class); + final ChunkShaderInterface shader = mock(ChunkShaderInterface.class); + final GlProgram program = mock(GlProgram.class); + final TerrainRenderPass pass = spy(new TerrainRenderPass("cleanup", TerrainRenderPass.PipelineState.DEFAULT, + false, false, false, false, ChunkMeshFormats.VANILLA_LIKE, QuadPrimitiveType.TRIANGULATED, Map.of())); + final Material material = new Material(pass, AlphaCutoffParameter.ZERO, false); + final RenderPassConfiguration config = new RenderPassConfiguration<>( + Map.of("solid", material), Map.of("solid", List.of(pass)), material, material, material); + final ChunkRenderMatrices matrices = new ChunkRenderMatrices(new Matrix4f(), new Matrix4f()); + final CameraTransform camera = new CameraTransform(0, 0, 0); + final ChunkRenderListIterable lists = mock(ChunkRenderListIterable.class); + final Field optionsField = ClientProxy.class.getDeclaredField("CONFIG"); + optionsField.setAccessible(true); + final Object previousOptions = optionsField.get(null); + final SodiumGameOptions options = new SodiumGameOptions(); + options.advanced.multiDrawMode = MultiDrawMode.DIRECT; + final RuntimeException failure = new IllegalStateException("Failed Iris setup"); + when(provider.isShadersEnabled()).thenReturn(true); + doReturn(program).when(provider).getShaderOverride(pass); + doReturn(shader).when(program).getInterface(); + when(lists.hasPass(pass)).thenReturn(true, false); + doThrow(failure).when(shader).setupState(pass); + IrisShaderProviderHolder.setProvider(provider); + optionsField.set(null, options); + RenderDevice.enterManagedCode(); + try { + final CommandList commandList = RenderDevice.INSTANCE.createCommandList(); + final AngelicaChunkRenderer renderer = new AngelicaChunkRenderer(RenderDevice.INSTANCE, config); + try { + assertSame(failure, assertThrows(RuntimeException.class, + () -> renderer.render(matrices, commandList, lists, pass, camera, camera))); + renderer.render(matrices, commandList, lists, pass, camera, camera); + + verify(shader, times(1)).restoreState(); + verify(program, times(1)).unbind(); + verify(pass, times(1)).endDrawing(); + } finally { + renderer.delete(commandList); + } + } finally { + RenderDevice.exitManagedCode(); + IrisShaderProviderHolder.setProvider(previous); + optionsField.set(null, previousOptions); + } + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/PbrSamplerBindingGLTest.java b/src/test/java/net/coderbot/iris/pipeline/PbrSamplerBindingGLTest.java new file mode 100644 index 000000000..a925b1ebf --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/PbrSamplerBindingGLTest.java @@ -0,0 +1,323 @@ +package net.coderbot.iris.pipeline; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GlTestSupport; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; +import com.gtnewhorizons.angelica.rendering.TextureSamplers; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.gl.program.ComputeProgram; +import net.coderbot.iris.gl.program.Program; +import net.coderbot.iris.gl.program.ProgramSamplers; +import net.coderbot.iris.gl.sampler.GlSampler; +import net.coderbot.iris.gl.sampler.SamplerHolder; +import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.coderbot.iris.gl.texture.TextureAccess; +import net.coderbot.iris.gl.texture.TextureWrapper; +import net.coderbot.iris.samplers.IrisSamplers; +import net.coderbot.iris.texture.format.LabPBRTextureFormat; +import net.coderbot.iris.texture.format.TextureFormat; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL33; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; + +@GLCoreTest +class PbrSamplerBindingGLTest { + private static final int ANISOTROPY = EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT; + private static final int NORMAL_UNIT = 3; + private static final int SPECULAR_UNIT = 4; + + private final Notifier normalNotifier = new Notifier(); + private final Notifier specularNotifier = new Notifier(); + private final DeferredWorldRenderingPipeline pipeline = mock(DeferredWorldRenderingPipeline.class, CALLS_REAL_METHODS); + private TextureFormat format; + private int anisotropy = 2; + private int program; + private int normal; + private int specular; + private int custom; + + @BeforeAll + static void initSamplers() { + TextureSamplers.initRenderer(); + IrisSamplers.initRenderer(); + } + + @BeforeEach + void setUp() { + assumeTrue(BackendManager.RENDER_BACKEND.isAnisotropicSupported()); + assumeTrue(GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT) >= 4); + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(false); + program = GlTestSupport.program(GlTestSupport.TRIVIAL_VS, + TestPaths.readString("src/test/resources/assets/angelica/shaders/pbrSamplerBindingTest.fsh")); + GLStateManager.glUseProgram(program); + normal = texture(); + specular = texture(); + custom = texture(); + } + + @AfterEach + void tearDown() { + ProgramSamplers.clearActiveSamplers(); + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(false); + GLStateManager.glUseProgram(0); + GLStateManager.glDeleteProgram(program); + GLStateManager.glDeleteTextures(normal); + GLStateManager.glDeleteTextures(specular); + GLStateManager.glDeleteTextures(custom); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + + private static int texture() { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + final int texture = GLStateManager.glGenTextures(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + return texture; + } + + private ProgramSamplers.Builder builder() { + return ProgramSamplers.builder(program, Set.of(0, 1, 2)); + } + + private void addPbrSamplers(SamplerHolder holder) { + refreshPbrSamplers(); + holder.addDynamicSampler(TextureType.TEXTURE_2D, () -> normal, normalNotifier, + pipeline::getNormalSampler, "normals"); + holder.addDynamicSampler(TextureType.TEXTURE_2D, () -> specular, specularNotifier, + pipeline::getSpecularSampler, "specular"); + } + + private void refreshPbrSamplers() { + pipeline.updatePbrSamplers(format, anisotropy); + } + + private static int boundSampler(int unit) { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit); + return GL11.glGetInteger(GL33.GL_SAMPLER_BINDING); + } + + private static void assertFiltering(int unit, int texture, float expectedAnisotropy, int minFilter) { + final int sampler = boundSampler(unit); + assertNotEquals(0, sampler); + assertEquals(texture, GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D)); + assertEquals(expectedAnisotropy, GL33.glGetSamplerParameterf(sampler, ANISOTROPY)); + assertEquals(minFilter, GL33.glGetSamplerParameteri(sampler, GL11.GL_TEXTURE_MIN_FILTER)); + assertEquals(1.0f, GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, ANISOTROPY)); + assertEquals(GL11.GL_NEAREST, GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER)); + } + + @Test + void anisotropyChangesReachBothUnitsWithoutRebuildingTheProgramOrChangingTextures() { + final ProgramSamplers.Builder builder = builder(); + addPbrSamplers(builder); + final ProgramSamplers samplers = builder.build(); + samplers.update(); + assertFiltering(NORMAL_UNIT, normal, 2, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 2, GL11.GL_NEAREST_MIPMAP_LINEAR); + final int before = boundSampler(NORMAL_UNIT); + + anisotropy = 4; + refreshPbrSamplers(); + normalNotifier.fire(); + specularNotifier.fire(); + assertNotEquals(before, boundSampler(NORMAL_UNIT)); + assertFiltering(NORMAL_UNIT, normal, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + + anisotropy = 1; + refreshPbrSamplers(); + samplers.update(); + assertFiltering(NORMAL_UNIT, normal, 1, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 1, GL11.GL_NEAREST_MIPMAP_LINEAR); + } + + @Test + void labPbrFormatChangeStopsSpecularInterpolationWithoutDisablingNormalAnisotropy() { + final ProgramSamplers.Builder builder = builder(); + addPbrSamplers(builder); + final ProgramSamplers samplers = builder.build(); + samplers.update(); + + format = new LabPBRTextureFormat("lab-pbr", "1.3"); + refreshPbrSamplers(); + normalNotifier.fire(); + specularNotifier.fire(); + assertFiltering(NORMAL_UNIT, normal, 2, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 1, GL11.GL_NEAREST_MIPMAP_NEAREST); + + format = null; + refreshPbrSamplers(); + samplers.update(); + assertFiltering(SPECULAR_UNIT, specular, 2, GL11.GL_NEAREST_MIPMAP_LINEAR); + } + + @Test + void linearTerrainSamplingDoesNotChangeTheSharedPackAndPbrSampler() { + anisotropy = 4; + final ProgramSamplers.Builder builder = builder(); + addPbrSamplers(builder); + builder.build().update(); + final GlSampler nearest = IrisSamplers.getTerrainSampler(4); + final GlSampler linear = TextureSamplers.getTerrainSampler(true, 4); + + assertNotEquals(nearest.getId(), linear.getId()); + RenderSystem.bindSamplerToUnit(0, linear.getId()); + RenderSystem.bindTextureToUnit(GL11.GL_TEXTURE_2D, 0, normal); + assertFiltering(0, normal, 4, GL11.GL_LINEAR_MIPMAP_LINEAR); + assertEquals(GL11.GL_LINEAR, GL33.glGetSamplerParameteri(linear.getId(), GL11.GL_TEXTURE_MAG_FILTER)); + + assertSame(linear, TextureSamplers.getTerrainSampler(true, 4)); + assertEquals(nearest.getId(), boundSampler(NORMAL_UNIT)); + assertFiltering(NORMAL_UNIT, normal, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertEquals(GL11.GL_NEAREST, GL33.glGetSamplerParameteri(nearest.getId(), GL11.GL_TEXTURE_MAG_FILTER)); + } + + @ParameterizedTest + @EnumSource(Registration.class) + void customTextureDiscardsTheCallersCompareSamplerAndNotifier(Registration registration) { + final boolean defaultUnit = registration == Registration.DEFAULT || registration == Registration.EXTERNAL_DEFAULT; + final int unit = defaultUnit ? 0 : NORMAL_UNIT; + final GlSampler shadowSampler = new GlSampler(false, false, false, true, true, true); + RenderSystem.bindSamplerToUnit(unit, shadowSampler.getId()); + final Object2ObjectOpenHashMap overrides = new Object2ObjectOpenHashMap<>(); + overrides.put("normals", new TextureWrapper(() -> custom, TextureType.TEXTURE_2D)); + final ProgramSamplers.Builder builder = defaultUnit + ? ProgramSamplers.builder(program, Set.of()) : builder(); + final SamplerHolder holder = ProgramSamplers.customTextureSamplerInterceptor(builder, overrides); + try { + switch (registration) { + case DEFAULT -> holder.addDefaultSampler(TextureType.TEXTURE_2D, () -> normal, + normalNotifier, () -> shadowSampler, "normals"); + case DYNAMIC -> holder.addDynamicSampler(TextureType.TEXTURE_2D, () -> normal, + () -> shadowSampler, "normals"); + case NOTIFIER -> holder.addDynamicSampler(TextureType.TEXTURE_2D, () -> normal, + normalNotifier, () -> shadowSampler, "normals"); + case EXTERNAL_DEFAULT -> holder.addExternalSampler(0, "normals"); + case EXTERNAL_DYNAMIC -> holder.addExternalSampler(2, "normals"); + } + builder.build().update(); + + assertEquals(0, boundSampler(unit)); + assertEquals(custom, GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D)); + assertEquals(GL11.GL_NEAREST, GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER)); + assertNull(normalNotifier.listener); + } finally { + shadowSampler.destroy(); + } + } + + @ParameterizedTest + @EnumSource(ProgramKind.class) + void programExitClearsSamplersIncludingUnitsUsedByThePreviousProgram(ProgramKind kind) { + final ProgramSamplers.Builder first = builder(); + addPbrSamplers(first); + first.build().update(); + assertNotEquals(0, boundSampler(NORMAL_UNIT)); + assertNotEquals(0, boundSampler(SPECULAR_UNIT)); + + final ProgramSamplers.Builder second = ProgramSamplers.builder(program, Set.of(0, 1, 2, 3, 4)); + addPbrSamplers(second); + second.build().update(); + assertNotEquals(0, boundSampler(5)); + assertNotEquals(0, boundSampler(6)); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); + switch (kind) { + case GRAPHICS -> Program.unbind(); + case COMPUTE -> ComputeProgram.unbind(); + } + assertEquals(GL13.GL_TEXTURE2, GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + for (int unit = NORMAL_UNIT; unit <= 6; unit++) { + assertEquals(0, boundSampler(unit)); + } + assertNull(normalNotifier.listener); + assertNull(specularNotifier.listener); + } + + @Test + void failedBindingClearsPartialSamplerStateAndRestoresTheActiveTextureUnit() { + final ProgramSamplers.Builder builder = builder(); + builder.addDynamicSampler(TextureType.TEXTURE_2D, () -> normal, normalNotifier, + () -> IrisSamplers.getTerrainSampler(2), "normals"); + builder.addDynamicSampler(TextureType.TEXTURE_2D, () -> specular, specularNotifier, + () -> { throw new IllegalStateException("Failed sampler lookup"); }, "specular"); + final ProgramSamplers samplers = builder.build(); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); + assertThrows(IllegalStateException.class, samplers::update); + assertEquals(GL13.GL_TEXTURE2, GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + assertEquals(0, boundSampler(NORMAL_UNIT)); + assertEquals(0, boundSampler(SPECULAR_UNIT)); + assertNull(normalNotifier.listener); + assertNull(specularNotifier.listener); + } + + @Test + void packAnisotropyOptOutAppliesToTerrainAndPbrWithoutChangingCachedSamplers() { + final GlSampler original = IrisSamplers.getTerrainSampler(4); + final ProgramSamplers.Builder builder = builder(); + anisotropy = 4; + addPbrSamplers(builder); + final ProgramSamplers samplers = builder.build(); + samplers.update(); + assertEquals(original.getId(), boundSampler(NORMAL_UNIT)); + + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(true); + refreshPbrSamplers(); + samplers.update(); + assertEquals(IrisSamplers.getTerrainSampler(4).getId(), boundSampler(NORMAL_UNIT)); + assertFiltering(NORMAL_UNIT, normal, 1, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 1, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertEquals(4.0f, GL33.glGetSamplerParameterf(original.getId(), ANISOTROPY)); + assertSame(original, TextureSamplers.getTerrainSampler(false, 4)); + + BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(false); + refreshPbrSamplers(); + samplers.update(); + assertSame(original, IrisSamplers.getTerrainSampler(4)); + assertFiltering(NORMAL_UNIT, normal, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + assertFiltering(SPECULAR_UNIT, specular, 4, GL11.GL_NEAREST_MIPMAP_LINEAR); + } + + private enum Registration { DEFAULT, DYNAMIC, NOTIFIER, EXTERNAL_DEFAULT, EXTERNAL_DYNAMIC } + + private enum ProgramKind { GRAPHICS, COMPUTE } + + private static final class Notifier implements ValueUpdateNotifier { + private Runnable listener; + + @Override + public void setListener(Runnable listener) { + this.listener = listener; + } + + void fire() { + if (listener != null) listener.run(); + } + } +} diff --git a/src/test/resources/assets/angelica/shaders/pbrSamplerBindingTest.fsh b/src/test/resources/assets/angelica/shaders/pbrSamplerBindingTest.fsh new file mode 100644 index 000000000..e81edb3e0 --- /dev/null +++ b/src/test/resources/assets/angelica/shaders/pbrSamplerBindingTest.fsh @@ -0,0 +1,7 @@ +#version 330 core +uniform sampler2D normals; +uniform sampler2D specular; +out vec4 color; +void main() { + color = texture(normals, vec2(0.5)) + texture(specular, vec2(0.5)); +}