Merge branch 'master' into DMTarget

This commit is contained in:
Ranzu authored and GitHub committed 2026-11-27 23:08:30 +01:00
commit 0afec3ee7d
19 files changed
+724 -116

No files matched your search

+3 -1
View File
@@ -17,7 +17,7 @@
* HUD caching
* Custom fonts and text effects
* MCPatcher - connected textures, custom item textures, custom colors, random mobs, better skies
* Bundled NotFine, zoom, FPS reducer
* Bundled NotFine, zoom, FPS reducer, menu blur
## Status
* OpenGL + Celeritas terrain - Default
@@ -129,5 +129,7 @@ Targets GL 3.3+ core profile
* FFP vertex shader generation inspired by ffvertex_prog.c (Copyright 2007 VMware, Inc.)
* FFP fragment shader generation inspired by ff_fragment_shader.c (Copyright 2007, 2009 VMware, Inc. / 2010-2011 Intel Corporation)
* Fog parameter optimization inspired by st_nir_lower_fog.c (Copyright 2023 Google LLC) and prog_statevars.c (Copyright 1999-2007 Brian Paul)
* Blur
* tterrag for [Blur](https://github.com/tterrag1098/Blur) - Menu blur based on Blur under the MIT license
* RGSS Terrain Texture Filtering
* Indiesoft for [defold-sharp-sprite](https://github.com/indiesoftby/defold-sharp-sprite), used as the reference implementation under the MIT license
@@ -8,13 +8,21 @@ import java.util.List;
public final class ClipZRemap {
private static final String INJECTION_STD = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;\n";
private static final String PRECISE_POSITION = "precise gl_Position;\n";
private ClipZRemap() {}
public static boolean collectEdits(GLSLParser.Translation_unitContext root, List<Edit> edits) {
boolean preciseInserted = false;
for (GLSLParser.External_declarationContext external : root.external_declaration()) {
final GLSLParser.Function_definitionContext function = external.function_definition();
if (function == null || function.function_prototype().IDENTIFIER() == null) continue;
if (function == null) continue;
if (!preciseInserted) {
final int start = external.getStart().getStartIndex();
edits.add(new Edit(start, start - 1, PRECISE_POSITION));
preciseInserted = true;
}
if (function.function_prototype().IDENTIFIER() == null) continue;
if (!"main".equals(function.function_prototype().IDENTIFIER().getText())) continue;
final GLSLParser.Compound_statement_no_new_scopeContext body = function.compound_statement_no_new_scope();
if (body == null || body.RIGHT_BRACE() == null) return false;
@@ -0,0 +1,92 @@
package com.gtnewhorizons.angelica.sdlgpu;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import org.lwjgl.opengl.GL20;
import org.lwjgl.sdl.SDLError;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Consumer;
import javax.imageio.ImageIO;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERSTAGE_FRAGMENT;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERSTAGE_VERTEX;
public final class GpuTestPrograms {
private GpuTestPrograms() {}
public static int link(ShaderManager sm, String vertex, String fragment) {
final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, vertex);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragment);
sm.compileShader(fs);
final int program = sm.createProgram();
sm.attachShader(program, vs);
sm.attachShader(program, fs);
sm.linkProgram(program);
final ShaderManager.ProgramObject po = sm.getProgram(program);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
final ShaderManager.ResourceCounts vr = po.vertexResources;
final ShaderManager.ResourceCounts fr = po.fragmentResources;
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures());
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures());
assertTrue(po.sdlVertexShader != 0 && po.sdlFragmentShader != 0, "SDL shader creation failed: " + SDLError.SDL_GetError());
return program;
}
public static String solidFragment(String rgb) {
return """
#version 460 core
layout(location = 0) out vec4 fragColor;
void main() { fragColor = vec4(%s, 1.0); }
""".formatted(rgb);
}
public static long pipeline(PipelineStore store, ShaderManager sm, int program, int colorFormat, int depthFormat, Consumer<PipelineCache> state) {
final ShaderManager.ProgramObject po = sm.getProgram(program);
final ContextState cs = new ContextState();
final PipelineCache cache = cs.pipeline;
cache.vertexShader = po.sdlVertexShader;
cache.fragmentShader = po.sdlFragmentShader;
cache.programId = program;
cache.maxFragOutputLocation = po.maxFragOutputLocation;
cache.setVertexInputs(po.vertexInputMask, po.vertexInputVecSize, po.vertexInputBaseType, po.vertexInputName, po.vertexInputSetId);
cache.setColorTargetFormats(new int[]{ colorFormat });
cache.setDrawBuffers(new int[]{ 0 });
cache.hasDepthTarget = true;
cache.depthTargetFormat = depthFormat;
state.accept(cache);
cache.markShaderDirty();
cache.markOutputDirty();
final long pipeline = cache.getOrCreatePipeline(store, cs);
assertTrue(pipeline != 0, "pipeline creation failed: " + SDLError.SDL_GetError());
return pipeline;
}
public static Path dumpPng(ByteBuffer rgba, int width, int height, String name) throws IOException {
final Path out = Path.of("build", "test-artifacts");
Files.createDirectories(out);
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int i = (y * width + x) * 4;
img.setRGB(x, y, ((rgba.get(i) & 0xFF) << 16) | ((rgba.get(i + 1) & 0xFF) << 8) | (rgba.get(i + 2) & 0xFF));
}
}
final Path file = out.resolve(name + ".png").toAbsolutePath();
ImageIO.write(img, "png", file.toFile());
return file;
}
}
@@ -84,7 +84,7 @@ public final class SdlTestRig {
}
}
private static long realSdlDevice;
private static SdlTestRig realRig;
private static final int SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL;
@@ -95,19 +95,19 @@ public final class SdlTestRig {
public static SdlTestRig acquireRealDevice() {
initSdlVideo();
realSdlDevice = SDL_CreateGPUDevice(SHADER_FORMATS, true, (CharSequence) null);
assertTrue(realSdlDevice != 0, "No SDL GPU device: " + SDLError.SDL_GetError());
final long handle = SDL_CreateGPUDevice(SHADER_FORMATS, true, (CharSequence) null);
assertTrue(handle != 0, "No SDL GPU device: " + SDLError.SDL_GetError());
final SdlTestRig rig = new SdlTestRig(realSdlDevice);
rig.frameManager.setResourceManager(rig.resourceManager);
return rig;
realRig = new SdlTestRig(handle);
realRig.frameManager.setResourceManager(realRig.resourceManager);
return realRig;
}
public static void releaseRealDevice() {
if (realSdlDevice != 0) {
SDL_WaitForGPUIdle(realSdlDevice);
SDL_DestroyGPUDevice(realSdlDevice);
realSdlDevice = 0;
}
if (realRig == null) return;
SDL_WaitForGPUIdle(realRig.sdlHandle);
realRig.resourceManager.shutdown();
SDL_DestroyGPUDevice(realRig.sdlHandle);
realRig = null;
}
}
@@ -1,16 +1,15 @@
package com.gtnewhorizons.angelica.sdlgpu.pipeline;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL20;
import org.lwjgl.sdl.SDLError;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo;
import org.lwjgl.system.MemoryStack;
@@ -49,13 +48,7 @@ class StencilMaskGpuTest {
"}",
"");
private static final String FILL_FRAGMENT = String.join("\n",
"#version 460 core",
"layout(location = 0) out vec4 fragColor;",
"void main() {",
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);",
"}",
"");
private static final String FILL_FRAGMENT = GpuTestPrograms.solidFragment("1.0, 0.0, 0.0");
@BeforeAll
static void setUp() throws Exception {
@@ -76,56 +69,28 @@ class StencilMaskGpuTest {
fillPipeline = createPipeline(FILL_FRAGMENT, false);
}
@AfterAll
static void tearDown() {
if (store != null) store.shutdown();
if (sm != null) sm.shutdown();
}
private static long createPipeline(String fragmentSource, boolean writesMask) {
final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragmentSource);
sm.compileShader(fs);
final int prog = sm.createProgram();
sm.attachShader(prog, vs);
sm.attachShader(prog, fs);
sm.linkProgram(prog);
final ShaderManager.ProgramObject po = sm.getProgram(prog);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, po.vertexResources.numSamplers(), po.vertexResources.numUBOs(), po.vertexResources.numStorageBuffers(), po.vertexResources.numStorageTextures());
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, po.fragmentResources.numSamplers(), po.fragmentResources.numUBOs(), po.fragmentResources.numStorageBuffers(), po.fragmentResources.numStorageTextures());
assertTrue(po.sdlVertexShader != 0 && po.sdlFragmentShader != 0, "SDL shader creation failed");
final ContextState cs = new ContextState();
final PipelineCache cache = cs.pipeline;
cache.vertexShader = po.sdlVertexShader;
cache.fragmentShader = po.sdlFragmentShader;
cache.programId = prog;
cache.maxFragOutputLocation = po.maxFragOutputLocation;
cache.shaderInputMask = po.vertexInputMask;
cache.shaderInputVecSize = po.vertexInputVecSize;
cache.shaderInputBaseType = po.vertexInputBaseType;
cache.shaderInputName = po.vertexInputName;
cache.setColorTargetFormats(new int[]{ colorFormat });
cache.setDrawBuffers(new int[]{ 0 });
cache.hasDepthTarget = true;
cache.depthTargetFormat = depthFormat;
cache.depthTestEnabled = false;
cache.depthWriteEnabled = false;
cache.stencilTestEnabled = true;
cache.stencilCompareMask = 0xFF;
cache.stencilWriteMask = writesMask ? 0xFF : 0x00;
final int prog = GpuTestPrograms.link(sm, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX, fragmentSource);
final int compareOp = writesMask ? SDL_GPU_COMPAREOP_ALWAYS : SDL_GPU_COMPAREOP_EQUAL;
final int passOp = writesMask ? SDL_GPU_STENCILOP_REPLACE : SDL_GPU_STENCILOP_KEEP;
cache.stencilFrontCompareOp = compareOp;
cache.stencilBackCompareOp = compareOp;
cache.stencilFrontPassOp = passOp;
cache.stencilBackPassOp = passOp;
cache.markShaderDirty();
cache.markOutputDirty();
assertTrue(cache.effectiveStencilTestEnabled(), "stencil must survive the depth-format gate");
final long pipeline = cache.getOrCreatePipeline(store, cs);
assertTrue(pipeline != 0, "pipeline creation failed: " + SDLError.SDL_GetError());
return pipeline;
return GpuTestPrograms.pipeline(store, sm, prog, colorFormat, depthFormat, cache -> {
cache.depthTestEnabled = false;
cache.depthWriteEnabled = false;
cache.stencilTestEnabled = true;
cache.stencilCompareMask = 0xFF;
cache.stencilWriteMask = writesMask ? 0xFF : 0x00;
cache.stencilFrontCompareOp = compareOp;
cache.stencilBackCompareOp = compareOp;
cache.stencilFrontPassOp = passOp;
cache.stencilBackPassOp = passOp;
assertTrue(cache.effectiveStencilTestEnabled(), "stencil must survive the depth-format gate");
});
}
private static void render(int secondPassStencilLoad) {
@@ -3,7 +3,6 @@ package com.gtnewhorizons.angelica.sdlgpu.resource;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -30,11 +29,6 @@ class BufferSizeGpuExactnessTest {
resourceManager = rig.resourceManager;
}
@AfterAll
static void tearDown() {
if (resourceManager != null) resourceManager.shutdown();
}
@ParameterizedTest(name = "{0}")
@CsvSource({"sub-bucket,9001,1000", "bucket boundary,9002,4096"})
void createdBufferReportsRequestedSize(String name, int glId, long size) {
@@ -0,0 +1,186 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore;
import org.joml.Matrix4f;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLGPU.*;
@ExtendWith(RealDeviceExtension.class)
@Tag("sdl-gpu-device")
class CoplanarDepthGpuTest {
private static final int SIZE = 256;
private static final int GRID = 32;
private static final int UBO_BYTES = 4 * 64 + 2 * 16;
private static final double CAM_X = 1475.7192986248613, CAM_Y = 70.62, CAM_Z = -935.8161276616005;
private static final String HEADER = """
#version 460 core
layout(std140) uniform Mats { mat4 proj; mat4 view; mat4 viewInv; mat4 mv; vec4 params; vec4 region; };
vec3 _vert_position;
void _vert_init() {
const ivec2 corner[6] = ivec2[](ivec2(0, 0), ivec2(1, 0), ivec2(1, 1), ivec2(0, 0), ivec2(1, 1), ivec2(0, 1));
int g = int(params.w);
int q = gl_VertexID / 6;
int c = gl_VertexID % 6;
vec2 uv = vec2(float(q % g + corner[c].x), float(q / g + corner[c].y)) / params.w;
vec3 packed = floor(vec3(uv.x * 16.0, 1.37 + uv.y * 3.1, 9.0 + uv.y * 7.0) * 2048.0);
_vert_position = packed * (1.0 / 2048.0) + vec3(params.z);
}
vec4 _celeritas_getVertexPosition() { return vec4(_vert_position + region.xyz, 1.0); }
""";
private static final String TERRAIN_VERTEX = HEADER + """
out vec3 vWorld;
void main() {
_vert_init();
vec4 position = viewInv * (mv * _celeritas_getVertexPosition());
vWorld = position.xyz;
gl_Position = proj * (view * position);
}
""";
private static final String WATER_VERTEX = HEADER + """
out vec3 vWorld;
out vec3 vView;
out float vWave;
out vec3 vNormal;
void main() {
_vert_init();
vec4 position = viewInv * (mv * _celeritas_getVertexPosition());
vWorld = position.xyz;
float wave = sin(position.x * 0.7 + params.y) * cos(position.z * 0.3 + params.y) * params.x;
if (params.x > 0.0) position.y += wave;
vWave = wave;
vView = (view * position).xyz;
vNormal = normalize(mat3(view) * vec3(0.0, 1.0, 0.0) + vec3(wave));
gl_Position = proj * (view * position);
}
""";
private static SdlTestRig rig;
private static ShaderManager sm;
private static PipelineStore store;
private static long colorTexture;
private static int colorFormat;
private static long depthTexture;
private static int depthFormat;
private static long terrainPipeline;
private static long waterPipeline;
@BeforeAll
static void setUp() {
rig = RealDeviceExtension.rig();
sm = new ShaderManager(rig.device);
store = new PipelineStore(rig.device);
final RealDeviceExtension.Target color = RealDeviceExtension.colorTarget(9600, SIZE, SIZE);
colorTexture = color.texture();
colorFormat = color.sdlFormat();
PipelineCache.setSwapchainFormats(new int[]{ colorFormat });
final RealDeviceExtension.Target depth = RealDeviceExtension.depthStencilTarget(9601, SIZE, SIZE);
depthTexture = depth.texture();
depthFormat = depth.sdlFormat();
terrainPipeline = createPipeline(TERRAIN_VERTEX, GpuTestPrograms.solidFragment("1.0, 0.0, 0.0"), SDL_GPU_COMPAREOP_LESS, true);
waterPipeline = createPipeline(WATER_VERTEX, GpuTestPrograms.solidFragment("0.0, 1.0, 0.0"), SDL_GPU_COMPAREOP_EQUAL, false);
}
@AfterAll
static void tearDown() {
if (store != null) store.shutdown();
if (sm != null) sm.shutdown();
}
private static long createPipeline(String vertexSource, String fragmentSource, int compareOp, boolean depthWrite) {
final int prog = GpuTestPrograms.link(sm, vertexSource, fragmentSource);
assertEquals(1, sm.getProgram(prog).vertexResources.numUBOs(), "the matrix block must be the only vertex UBO, pushed at slot 0");
return GpuTestPrograms.pipeline(store, sm, prog, colorFormat, depthFormat, cache -> {
cache.depthTestEnabled = true;
cache.depthWriteEnabled = depthWrite;
cache.depthCompareOp = compareOp;
});
}
private static void writeMats(ByteBuffer ubo) {
final Matrix4f proj = new Matrix4f().perspective((float) Math.toRadians(70.0), 1.0f, 0.05f, 512.0f);
final Matrix4f view = new Matrix4f().rotationX(0.35f).rotateY((float) Math.PI - 0.2f);
proj.get(0, ubo);
view.get(64, ubo);
view.invert(new Matrix4f()).get(128, ubo);
view.get(192, ubo);
ubo.putFloat(256, 0.0f).putFloat(260, 0.25f).putFloat(264, -0.37f).putFloat(268, GRID);
ubo.putFloat(272, (float) (1472.0 - CAM_X)).putFloat(276, (float) (64.0 - CAM_Y));
}
private static void drawAndRead(ByteBuffer ubo, ByteBuffer pixels) {
try (MemoryStack stack = MemoryStack.stackPush()) {
final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice());
assertTrue(cb != 0, "no command buffer");
final SDL_GPUColorTargetInfo.Buffer color = SDL_GPUColorTargetInfo.calloc(1, stack);
color.get(0).texture(colorTexture).load_op(SDL_GPU_LOADOP_CLEAR).store_op(SDL_GPU_STOREOP_STORE);
final SDL_GPUDepthStencilTargetInfo ds = SDL_GPUDepthStencilTargetInfo.calloc(stack)
.texture(depthTexture)
.load_op(SDL_GPU_LOADOP_CLEAR).store_op(SDL_GPU_STOREOP_DONT_CARE).clear_depth(1.0f)
.stencil_load_op(SDL_GPU_LOADOP_CLEAR).stencil_store_op(SDL_GPU_STOREOP_DONT_CARE);
SDL_PushGPUVertexUniformData(cb, 0, ubo);
final long pass = SDL_BeginGPURenderPass(cb, color, ds);
assertTrue(pass != 0, "no render pass");
SDL_BindGPUGraphicsPipeline(pass, terrainPipeline);
SDL_DrawGPUPrimitives(pass, GRID * GRID * 6, 1, 0, 0);
SDL_BindGPUGraphicsPipeline(pass, waterPipeline);
SDL_DrawGPUPrimitives(pass, GRID * GRID * 6, 1, 0, 0);
SDL_EndGPURenderPass(pass);
pixels.clear();
rig.resourceManager.downloadFromTexture(cb, colorTexture, 0, 0, SIZE, SIZE, 0, pixels);
}
}
@Test
void secondProgramMatchesFirstProgramDepthOnCoplanarGeometry() throws IOException {
final ByteBuffer ubo = MemoryUtil.memCalloc(UBO_BYTES);
final ByteBuffer pixels = MemoryUtil.memAlloc(SIZE * SIZE * 4);
try {
int mismatched = 0, covered = 0;
Path firstBad = null;
writeMats(ubo);
for (double chunkZ : new double[]{ 0, 16, 64, 256 }) {
ubo.putFloat(280, (float) (-944.0 + chunkZ - CAM_Z));
drawAndRead(ubo, pixels);
int red = 0;
for (int i = 0; i < SIZE * SIZE * 4; i += 4) {
if ((pixels.get(i) & 0xFF) > 128) red++;
else if ((pixels.get(i + 1) & 0xFF) > 128) covered++;
}
if (red > 0 && firstBad == null) firstBad = GpuTestPrograms.dumpPng(pixels, SIZE, SIZE, "coplanar_depth_dz" + (int) chunkZ);
mismatched += red;
covered += red;
}
assertTrue(covered > 4 * SIZE, "the plane must cover the target, covered=" + covered);
assertEquals(0, mismatched, "depth EQUAL failed on " + mismatched + "/" + covered + " pixels drawn by both programs; first failing view: " + firstBad);
} finally {
MemoryUtil.memFree(ubo);
MemoryUtil.memFree(pixels);
}
}
}
@@ -1,8 +1,10 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -10,7 +12,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.sdl.SDL_GPUColorTargetDescription;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
@@ -25,7 +26,6 @@ import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -48,6 +48,11 @@ class FragmentStorageTextureReadGpuTest {
sm = new ShaderManager(rig.device);
}
@AfterAll
static void tearDown() {
if (sm != null) sm.shutdown();
}
private static String fragment(int samplerCount) {
final StringBuilder sb = new StringBuilder();
sb.append("#version 460 core\n");
@@ -69,8 +74,7 @@ class FragmentStorageTextureReadGpuTest {
return (x == y) ? 255 - z * 16 : z * 32 + x * 2 + y;
}
private int createVoxelTexture() {
final int glId = 9001;
private int createVoxelTexture(int glId) {
final long handle = rig.resourceManager.createTexture(glId, GL12.GL_TEXTURE_3D, GL30.GL_R16UI, VOL, VOL, VOL, 1);
assertTrue(handle != 0, "voxel texture creation failed");
final ByteBuffer data = MemoryUtil.memAlloc(VOL * VOL * VOL * 2);
@@ -95,25 +99,15 @@ class FragmentStorageTextureReadGpuTest {
}
private int linkProgram(int samplerCount) {
final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragment(samplerCount));
sm.compileShader(fs);
final int prog = sm.createProgram();
sm.attachShader(prog, vs);
sm.attachShader(prog, fs);
sm.linkProgram(prog);
final int prog = GpuTestPrograms.link(sm, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX, fragment(samplerCount));
final ShaderManager.ProgramObject po = sm.getProgram(prog);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
assertEquals(samplerCount, po.fragmentResources.numSamplers(), "production sampler count");
assertEquals(1, po.fragmentResources.numStorageTextures(), "production storage texture count");
return prog;
}
private void runCase(int samplerCount) throws IOException {
final int voxelGlId = createVoxelTexture();
final int voxelGlId = createVoxelTexture(9000 + samplerCount);
final long voxelHandle = rig.resourceManager.getTextureHandle(voxelGlId);
final int targetGlId = 9100 + samplerCount;
@@ -132,13 +126,6 @@ class FragmentStorageTextureReadGpuTest {
System.out.println("[GpuReadTest] S=" + samplerCount
+ " VS=" + po.vertexResources + " FS=" + po.fragmentResources);
final ShaderManager.ResourceCounts vr = po.vertexResources;
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures());
final ShaderManager.ResourceCounts fr = po.fragmentResources;
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures());
assertTrue(po.sdlVertexShader != 0, "SDL vertex shader creation failed");
assertTrue(po.sdlFragmentShader != 0, "SDL fragment shader creation failed");
final long pipeline;
try (MemoryStack stack = MemoryStack.stackPush()) {
final SDL_GPUColorTargetDescription.Buffer colorDesc = SDL_GPUColorTargetDescription.calloc(1, stack);
@@ -189,13 +176,14 @@ class FragmentStorageTextureReadGpuTest {
assertTrue(SDL_SubmitGPUCommandBuffer(cb), "draw submit failed");
SDL_WaitForGPUIdle(rig.device.getDevice());
}
SDL_ReleaseGPUGraphicsPipeline(rig.device.getDevice(), pipeline);
final ByteBuffer pixels = MemoryUtil.memAlloc(TARGET * TARGET * 4);
try {
final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice());
assertTrue(cb != 0, "no readback command buffer");
rig.resourceManager.downloadFromTexture(cb, targetHandle, 0, 0, TARGET, TARGET, 0, pixels);
final Path png = dumpPng(pixels, samplerCount);
final Path png = GpuTestPrograms.dumpPng(pixels, TARGET, TARGET, "storage_read_s" + samplerCount);
// SDL's Y-flip means the readback may be row-inverted vs gl_FragCoord; either orientation
// is a fixed convention, not this bug - accept whichever matches.
final int direct = countMismatches(pixels, false, null);
@@ -229,22 +217,6 @@ class FragmentStorageTextureReadGpuTest {
return mismatches;
}
private static Path dumpPng(ByteBuffer rgba, int samplerCount) throws IOException {
final Path out = Path.of("build", "test-artifacts");
Files.createDirectories(out);
final java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(TARGET, TARGET, java.awt.image.BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < TARGET; y++) {
for (int x = 0; x < TARGET; x++) {
final int i = (y * TARGET + x) * 4;
img.setRGB(x, y, ((rgba.get(i) & 0xFF) << 16) | ((rgba.get(i + 1) & 0xFF) << 8) | (rgba.get(i + 2) & 0xFF));
}
}
final Path file = out.resolve("storage_read_s" + samplerCount + ".png").toAbsolutePath();
javax.imageio.ImageIO.write(img, "png", file.toFile());
System.out.println("[GpuReadTest] wrote " + file);
return file;
}
@ParameterizedTest(name = "{0} samplers")
@ValueSource(ints = {0, 2})
void fragmentImageLoadReadsCorrectTexels(int samplerCount) throws IOException {
@@ -291,6 +291,55 @@ class MslCrossCompileTest {
assertUniqueBufferSlots(msl);
}
private static final String POSITION_HEAD = """
#version 460 core
layout(std140) uniform Mats { mat4 proj; mat4 view; mat4 viewInv; mat4 mv; vec4 ab; };
in vec3 a_Position;
out float vOut;
""";
static Stream<Arguments> positionVertexShapes() {
return Stream.of(
Arguments.of("chain through a temporary", "proj|view|viewInv|mv", POSITION_HEAD + """
void main() {
vec4 position = viewInv * (mv * vec4(a_Position, 1.0));
vOut = ab.x * ab.y;
gl_Position = proj * (view * position);
}
"""),
Arguments.of("declared invariant", "proj|view", POSITION_HEAD + """
invariant gl_Position;
void main() {
vOut = ab.x * ab.y;
gl_Position = proj * (view * vec4(a_Position, 1.0));
}
"""),
Arguments.of("already precise", "proj|view", POSITION_HEAD + """
precise gl_Position;
void main() {
vOut = ab.x * ab.y;
gl_Position = proj * (view * vec4(a_Position, 1.0));
}
"""),
Arguments.of("helper writes gl_Position", "proj|view", POSITION_HEAD + """
void place(vec4 p) { gl_Position = proj * (view * p); }
void main() {
vOut = ab.x * ab.y;
place(viewInv * (mv * vec4(a_Position, 1.0)));
}
"""));
}
@ParameterizedTest(name = "{0}")
@MethodSource("positionVertexShapes")
void positionMathIsContractionFreeAndOtherMathIsNot(String name, String exactMatrices, String glsl) {
final String transformed = ShaderManager.applyPrewarmTransformsFull(glsl, GL20.GL_VERTEX_SHADER, null, null).source();
final String msl = crossCompile(transformed, Shaderc.shaderc_vertex_shader, GL20.GL_VERTEX_SHADER, false).code();
assertTrue(msl.contains("spvFMulMatrixVector") && msl.contains("[[clang::optnone]]"), "gl_Position math must go through the optnone fma helpers:\n" + msl);
assertFalse(Pattern.compile("\\.(" + exactMatrices + ") \\*").matcher(msl).find(), "a plain multiply by " + exactMatrices + " is left on the gl_Position chain:\n" + msl);
assertTrue(Pattern.compile("\\.ab\\.x \\* \\w+\\.ab\\.y").matcher(msl).find(), "math not feeding gl_Position must stay contractible:\n" + msl);
}
private static void assertUniqueBufferSlots(String msl) {
final Set<Integer> seen = new HashSet<>();
int from = 0;
@@ -0,0 +1,25 @@
The menu blur in this package is based on [Blur](https://github.com/tterrag1098/Blur), used under the following license:
```
MIT License
Copyright (c) 2017 tterrag
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
@@ -0,0 +1,206 @@
package com.gtnewhorizons.angelica.blur;
import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat2v;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMDraws;
import com.gtnewhorizons.angelica.glsm.GLSMFramebuffer;
import com.gtnewhorizons.angelica.glsm.GLSMPrograms;
import com.gtnewhorizons.angelica.glsm.GLSMQueries;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.GLSMVertexInput;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.render.PanoramaRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import org.apache.commons.lang3.ArrayUtils;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import java.nio.ByteBuffer;
/**
* Blurs the world behind open GUIs and fades in a configurable background gradient.
* Based on Blur by tterrag (https://github.com/tterrag1098/Blur) under the MIT license, see LICENSE-Blur.md.
* Reimplemented on top of Angelica's own blur shader instead of a vanilla post-processing shader.
*/
public class MenuBlur {
private static final Minecraft mc = Minecraft.getMinecraft();
private static GlProgram<BlurUniforms> blurProgram;
private static StateSet allState;
private static int emptyVao;
// The blur runs on half resolution copies of the screen, which is much cheaper and looks the same once blurred
private static int horizontalFbo, horizontalTexture, verticalFbo, verticalTexture;
private static int sourceWidth, sourceHeight, halfWidth, halfHeight;
private static boolean blurring;
private static long fadeStartMillis;
/** Called right after the world has been drawn, before the HUD and the open GUI. */
public static void renderBlur() {
final boolean shouldBlur = shouldBlur();
if (shouldBlur && !blurring) {
fadeStartMillis = System.currentTimeMillis();
}
blurring = shouldBlur;
if (!blurring) return;
// The radius grows with the fade, so the blur gets stronger over the first moments
final float radius = (float) Math.floor(AngelicaConfig.menuBlurRadius * getProgress());
if (radius < 1.0F) return;
final Framebuffer mainFramebuffer = mc.getFramebuffer();
if (blurProgram == null) init();
final int previousProgram = GLSMPrograms.getActiveProgram();
final int previousVao = GLSMQueries.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING);
final int previousFilter = mainFramebuffer.framebufferFilter;
final int stateDepth = GLSMAttribStack.pushState(allState);
try {
ensureBlurTargets(mainFramebuffer.framebufferWidth, mainFramebuffer.framebufferHeight);
GLSMBlend.disableBlend();
GLSMDepthStencilAlpha.disableDepthTest();
GLSMDepthStencilAlpha.glDepthMask(false);
GLSMBlend.glColorMask(true, true, true, true);
GLSMRasterizer.disableCull();
GLSMRasterizer.disableScissorTest();
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
blurProgram.bind();
GLSMVertexInput.glBindVertexArray(emptyVao);
final BlurUniforms uniforms = blurProgram.getInterface();
// Each half resolution pixel covers two screen pixels, so half the radius gives the same strength
uniforms.radius.setFloat(radius * 0.5F);
// Horizontal pass, shrinking the screen to half size. Linear filtering makes every
// half size pixel average the four screen pixels it covers instead of picking one.
mainFramebuffer.setFramebufferFilter(GL11.GL_LINEAR);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, horizontalFbo);
GLSMRasterizer.glViewport(0, 0, halfWidth, halfHeight);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, mainFramebuffer.framebufferTexture);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
uniforms.direction.set(1.0F / halfWidth, 0.0F);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
// Vertical pass, still at half size
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, verticalFbo);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, horizontalTexture);
uniforms.direction.set(0.0F, 1.0F / halfHeight);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
// Stretch the result back over the screen. A radius of 0 makes the blur shader a plain copy.
mainFramebuffer.bindFramebuffer(true);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, verticalTexture);
uniforms.radius.setFloat(0.0F);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
} finally {
mainFramebuffer.setFramebufferFilter(previousFilter);
GLSMVertexInput.glBindVertexArray(previousVao);
GLSMPrograms.glUseProgram(previousProgram);
GLSMAttribStack.popStateTo(stateDepth);
mainFramebuffer.bindFramebuffer(true);
}
}
/** Replaces one of the two vanilla GUI background gradient colors while the blur is showing. */
public static int getBackgroundColor(int vanillaColor, String configuredColor) {
if (!blurring) return vanillaColor;
final int color;
try {
color = Integer.parseUnsignedInt(configuredColor, 16);
} catch (NumberFormatException e) {
return vanillaColor;
}
final float progress = getProgress();
final int alpha = (int) ((color >>> 24) * progress);
final int red = (int) ((color >> 16 & 0xFF) * progress);
final int green = (int) ((color >> 8 & 0xFF) * progress);
final int blue = (int) ((color & 0xFF) * progress);
return alpha << 24 | red << 16 | green << 8 | blue;
}
private static boolean shouldBlur() {
return AngelicaConfig.enableMenuBlur
&& mc.theWorld != null
&& mc.currentScreen != null
&& !ArrayUtils.contains(AngelicaConfig.menuBlurExcludedGuis, mc.currentScreen.getClass().getName());
}
private static float getProgress() {
if (AngelicaConfig.menuBlurFadeTime <= 0) return 1.0F;
return Math.min((System.currentTimeMillis() - fadeStartMillis) / (float) AngelicaConfig.menuBlurFadeTime, 1.0F);
}
private static void init() {
blurProgram = PanoramaRenderer.loadProgram("angelica:menu_blur", "angelica:panorama_blur", "angelica:panorama_blur", BlurUniforms::new);
allState = StateSet.forMask(GL11.GL_ALL_ATTRIB_BITS);
emptyVao = GLSMVertexInput.glGenVertexArrays();
}
private static void ensureBlurTargets(int width, int height) {
if (horizontalFbo != 0 && width == sourceWidth && height == sourceHeight) return;
if (horizontalFbo != 0) {
GLSMFramebuffer.glDeleteFramebuffers(horizontalFbo);
GLSMFramebuffer.glDeleteFramebuffers(verticalFbo);
GLSMTextures.glDeleteTextures(horizontalTexture);
GLSMTextures.glDeleteTextures(verticalTexture);
}
sourceWidth = width;
sourceHeight = height;
halfWidth = Math.max((width + 1) / 2, 1);
halfHeight = Math.max((height + 1) / 2, 1);
horizontalTexture = createTexture(halfWidth, halfHeight);
horizontalFbo = createFramebuffer(horizontalTexture);
verticalTexture = createTexture(halfWidth, halfHeight);
verticalFbo = createFramebuffer(verticalTexture);
}
private static int createTexture(int width, int height) {
final int texture = GLSMTextures.glGenTextures();
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, 0);
return texture;
}
private static int createFramebuffer(int colorTexture) {
final int fbo = GLSMFramebuffer.glGenFramebuffers();
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
GLSMFramebuffer.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0);
final int status = GLSMFramebuffer.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER);
if (status != GL30.GL_FRAMEBUFFER_COMPLETE) {
throw new RuntimeException("Menu blur FBO incomplete: 0x" + Integer.toHexString(status));
}
return fbo;
}
private static class BlurUniforms {
final GlUniformFloat2v direction;
final GlUniformFloat radius;
BlurUniforms(ShaderBindingContext ctx) {
direction = ctx.bindUniform("u_Direction", GlUniformFloat2v::new);
radius = ctx.bindUniform("u_Radius", GlUniformFloat::new);
}
}
}
@@ -296,6 +296,32 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableZoom;
@Config.Comment("Blur the world behind open GUIs.")
@Config.DefaultBoolean(false)
public static boolean enableMenuBlur;
@Config.Comment("How strong the menu blur is, in pixels.")
@Config.DefaultInt(12)
@Config.RangeInt(min = 1, max = 100)
public static int menuBlurRadius;
@Config.Comment("How long the menu blur takes to fade in, in milliseconds.")
@Config.DefaultInt(200)
@Config.RangeInt(min = 0, max = 2000)
public static int menuBlurFadeTime;
@Config.Comment("GUI classes that never get the menu blur.")
@Config.DefaultStringList({"net.minecraft.client.gui.GuiChat", "net.coderbot.iris.gui.screen.ShaderPackScreen"})
public static String[] menuBlurExcludedGuis;
@Config.Comment("Top color of the GUI background gradient while the menu blur is showing, as ARGB hex.")
@Config.DefaultString("75000000")
public static String menuBlurGradientTopColor;
@Config.Comment("Bottom color of the GUI background gradient while the menu blur is showing, as ARGB hex.")
@Config.DefaultString("75000000")
public static String menuBlurGradientBottomColor;
@Config.Comment("Optimizes in-world item rendering")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
@@ -676,6 +676,14 @@ public enum Mixins implements IMixins {
"angelica.zoom.MixinMouseFilter"
)),
ANGELICA_MENU_BLUR(new MixinBuilder("Blur the world behind open GUIs")
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.BLUR)
.addClientMixins(
"angelica.blur.MixinEntityRenderer_MenuBlur",
"angelica.blur.MixinGuiScreen_MenuBlur"
)),
ANGELICA_FPS_REDUCER(new MixinBuilder("Reduce frame rate and volume while unfocused, minimized, or idle")
.setPhase(Phase.EARLY)
.addClientMixins(
@@ -9,6 +9,7 @@ public enum TargetedMod implements ITargetMod {
ARCHAICFIX("org.embeddedt.archaicfix.ArchaicCore", "archaicfix"),
BACKHAND("xonin.backhand.coremod.BackhandLoadingPlugin", "backhand"),
BLUR("com.tterrag.blur.BlurPlugin", "blur"),
BOTANIA(null, "Botania"),
CAMPFIRE_BACKPORT(null, "campfirebackport"),
CHISEL(null, "chisel"),
@@ -861,6 +861,29 @@ public class SodiumGameOptionPages {
.build());
}
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlur"))
.setTooltip(I18n.format("options.angelica.menuBlur.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> AngelicaConfig.enableMenuBlur = value, opts -> AngelicaConfig.enableMenuBlur)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlurRadius"))
.setTooltip(I18n.format("options.angelica.menuBlurRadius.tooltip"))
.setControl(option -> new SliderControl(option, 1, 100, 1, ControlValueFormatter.number()))
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> AngelicaConfig.menuBlurRadius = value, opts -> AngelicaConfig.menuBlurRadius)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlurFadeTime"))
.setTooltip(I18n.format("options.angelica.menuBlurFadeTime.tooltip"))
.setControl(option -> new SliderControl(option, 0, 2000, 50, ControlValueFormatter.milliseconds()))
.setBinding((opts, value) -> AngelicaConfig.menuBlurFadeTime = value, opts -> AngelicaConfig.menuBlurFadeTime)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.appearance"), ImmutableList.copyOf(groups));
}
@@ -43,6 +43,10 @@ public interface ControlValueFormatter {
return (v) -> v + "s";
}
static ControlValueFormatter milliseconds() {
return (v) -> v + "ms";
}
static ControlValueFormatter quantity(String name) {
return (v) -> I18n.format(name, v);
}
@@ -402,6 +402,12 @@ sodium.options.use_render_pass_optimization.tooltip=Analyzes sprite transparency
options.angelica.aggressiveChunkLoading=Aggressive Chunk Loading
options.angelica.aggressiveChunkLoading.tooltip=Renders chunks immediately when loaded, even if neighbors aren't ready yet. Improves perceived loading speed at render distance edges. Chunks rebuild automatically when neighbors load. Useful for low render distance servers.
options.angelica.menuBlur=Menu Blur
options.angelica.menuBlur.tooltip=Blurs the world behind open menus like the inventory or the pause menu. Chat is never blurred. Excluded menus and background colors can be changed in the Angelica config.
options.angelica.menuBlurRadius=Menu Blur Strength
options.angelica.menuBlurRadius.tooltip=How strong the menu blur is. Higher values blur more.
options.angelica.menuBlurFadeTime=Menu Blur Fade Time
options.angelica.menuBlurFadeTime.tooltip=How long the menu blur takes to fade in after a menu opens. 0 shows it instantly.
angelica.debug.verbose.on=Verbose F3: shown
angelica.debug.verbose.off=Verbose F3: hidden
angelica.debug.group.rendering=Rendering
@@ -0,0 +1,19 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.blur;
import com.gtnewhorizons.angelica.blur.MenuBlur;
import net.minecraft.client.renderer.EntityRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class)
public class MixinEntityRenderer_MenuBlur {
@Inject(
method = "updateCameraAndRender",
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/EntityRenderer;renderWorld(FJ)V", shift = At.Shift.AFTER))
private void angelica$blurWorldBehindGui(float partialTicks, CallbackInfo ci) {
MenuBlur.renderBlur();
}
}
@@ -0,0 +1,22 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.blur;
import com.gtnewhorizons.angelica.blur.MenuBlur;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import net.minecraft.client.gui.GuiScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin(GuiScreen.class)
public class MixinGuiScreen_MenuBlur {
@ModifyConstant(method = "drawWorldBackground", constant = @Constant(intValue = 0xC0101010))
private int angelica$blurGradientTop(int original) {
return MenuBlur.getBackgroundColor(original, AngelicaConfig.menuBlurGradientTopColor);
}
@ModifyConstant(method = "drawWorldBackground", constant = @Constant(intValue = 0xD0101010))
private int angelica$blurGradientBottom(int original) {
return MenuBlur.getBackgroundColor(original, AngelicaConfig.menuBlurGradientBottomColor);
}
}