From f2c07dea28ff8e364c4eeac672238d00738f2f52 Mon Sep 17 00:00:00 2001 From: Eclipse-Sol Date: Tue, 22 Sep 2026 19:27:05 -0400 Subject: [PATCH] Weather instancing (#2127) * Initial commit for weather-instancing * attempt to make the builder less ugly --- .../angelica/config/SystemProperties.java | 16 + .../angelica/glsm/ffp/FFPUniformBlock.java | 6 + .../glsm/ffp/InstancedGlslHelpers.java | 61 ++ .../angelica/glsm/ffp/Instancing.java | 3 +- .../angelica/glsm/ffp/Uniforms.java | 16 + .../angelica/glsm/ffp/VertexKey.java | 11 +- .../glsm/ffp/VertexShaderGenerator.java | 11 +- .../glsm/ffp/WeatherInstancedAttribs.java | 34 ++ .../angelica/glsm/ffp/WeatherParams.java | 42 ++ .../angelica/glsm/ffp/WeatherQuadMesh.java | 69 +++ scripts/flyby-compare.py | 3 +- .../compat/dragonapi/DragonAPICompat.java | 8 + .../angelica/config/AngelicaConfig.java | 4 + .../angelica/debug/flyby/FlybyRunner.java | 22 +- .../gtnewhorizons/angelica/mixins/Mixins.java | 15 + .../interfaces/EntityRendererAccessor.java | 3 + .../angelica/render/WeatherColumns.java | 213 +++++++ .../angelica/render/WeatherRenderer.java | 528 ++++++++++++++++++ .../celeritas/CeleritasWorldRenderer.java | 2 + .../DeferredWorldRenderingPipeline.java | 6 + .../transform/AttributeTransformer.java | 7 +- .../transform/CoreTransformHelper.java | 14 + .../iris/uniforms/CommonUniforms.java | 1 + .../iris/uniforms/IrisInternalUniforms.java | 14 + .../PerFrameUniformBlockHarvester.java | 3 +- .../early/angelica/MixinEntityRenderer.java | 3 + .../MixinEntityRenderer_Weather.java | 22 + .../dragonapi/MixinSpecialDayTracker.java | 19 + 28 files changed, 1145 insertions(+), 11 deletions(-) create mode 100644 glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherInstancedAttribs.java create mode 100644 glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherParams.java create mode 100644 glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherQuadMesh.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/compat/dragonapi/DragonAPICompat.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/render/WeatherColumns.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/render/WeatherRenderer.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/rendering/MixinEntityRenderer_Weather.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/dragonapi/MixinSpecialDayTracker.java diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java index e669cfd0a..adc016175 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java @@ -62,6 +62,7 @@ public final class SystemProperties { public static final String FLYBY_COMMANDS = System.getProperty("angelica.flyby.commands", ""); public static final String FLYBY_ORIGIN = System.getProperty("angelica.flyby.origin", ""); public static final FlybyPacing FLYBY_PACING = parseEnum("angelica.flyby.pacing", FlybyPacing.UNCAPPED, FlybyPacing.UNCAPPED, FlybyPacing.class); + public static final FlybyWeather FLYBY_WEATHER = parseEnum("angelica.flyby.weather", FlybyWeather.CLEAR, FlybyWeather.CLEAR, FlybyWeather.class); public static final boolean FLYBY_JFR = Boolean.getBoolean("angelica.flyby.jfr"); // Debug @@ -77,6 +78,7 @@ public final class SystemProperties { public static final boolean FFP_TRACE = Boolean.getBoolean("angelica.debug.ffpTrace"); public static final boolean LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.debug.displayLists.compilation"); public static final boolean FORCE_ORPHAN_STREAMING = Boolean.getBoolean("angelica.debug.forceOrphanStreaming"); + public static final boolean WEATHER_REBUILD_ALWAYS = Boolean.getBoolean("angelica.debug.weatherRebuildAlways"); public static final String SHADER_DUMP_ROOT = "angelica_dumps"; // Set by us, read by celeritas @@ -125,6 +127,20 @@ public final class SystemProperties { CONFIGURED } + public enum FlybyWeather { + CLEAR, + RAIN, + THUNDER; + + public boolean isRaining() { + return this != CLEAR; + } + + public boolean isThundering() { + return this == THUNDER; + } + } + private static > E parseEnum(String key, E whenAbsent, E whenInvalid, Class type) { final String raw = System.getProperty(key); if (raw == null || raw.isEmpty()) return whenAbsent; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java index 9aa8410b0..e7204fbab 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java @@ -107,6 +107,12 @@ public final class FFPUniformBlock { public static final int FOG_PARAMS = vec4("u_FogParams"); public static final int FOG_COLOR = vec4("u_FogColor"); + // Rain and snow, for Instancing.WEATHER. 0 = (translate.xyz, 1/radius), + // 1 = (cameraFrac.xy, partialTicks, age), 2 = (rainScroll, snowScroll, rainStrength, unused). + public static final int WEATHER_PARAMS_0 = vec4("u_WeatherParams0"); + public static final int WEATHER_PARAMS_1 = vec4("u_WeatherParams1"); + public static final int WEATHER_PARAMS_2 = vec4("u_WeatherParams2"); + public static final int SIZE; public static final String GLSL_DECL; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java index 5e6ecf04c..273952ada 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java @@ -34,6 +34,62 @@ public final class InstancedGlslHelpers { + "0.0, 1.0)"; } + // wHalfWidth is vanilla's rainXCoords table. + private static final String WEATHER_PROLOGUE = """ + vec2 {p}wColumn = {span}.xy; + float {p}wBottom = {span}.z; + float {p}wTop = {span}.w; + vec2 {p}wLightmap = {params}.xy; + float {p}wHash = {params}.z; + bool {p}wSnow = {params}.w > 0.5; + vec3 {p}wTranslate = {p}WeatherParams0.xyz; + float {p}wInvRadius = {p}WeatherParams0.w; + vec2 {p}wCameraFrac = {p}WeatherParams1.xy; + float {p}wPartialTicks = {p}WeatherParams1.z; + float {p}wAge = {p}WeatherParams1.w; + float {p}wRainScroll = {p}WeatherParams2.x; + float {p}wSnowScroll = {p}WeatherParams2.y; + float {p}wStrength = {p}WeatherParams2.z; + + vec2 {p}wHalfWidth = vec2(-{p}wColumn.y, {p}wColumn.x) * (0.5 / sqrt(dot({p}wColumn, {p}wColumn))); + vec2 {p}wCornerXZ = {p}wColumn + vec2(0.5) + ({corner}.x * 2.0 - 1.0) * {p}wHalfWidth; + float {p}wCornerY = mix({p}wBottom, {p}wTop, {corner}.y); + {vertex} = vec4(vec3({p}wCornerXZ.x, {p}wCornerY, {p}wCornerXZ.y) + {p}wTranslate, 1.0); + + float {p}wDistance = length({p}wColumn + vec2(0.5) - {p}wCameraFrac) * {p}wInvRadius; + float {p}wFade = 1.0 - {p}wDistance * {p}wDistance; + float {p}wScroll; + vec2 {p}wDrift; + float {p}wAlpha; + if ({p}wSnow) { + {p}wScroll = ({p}wSnowScroll + {p}wPartialTicks) / 512.0; + {p}wDrift = vec2({jitter}.x + {p}wAge * 0.01 * {jitter}.y, {jitter}.z + {p}wAge * {jitter}.w * 0.001); + {p}wAlpha = {p}wFade * 0.3 + 0.5; + } else { + {p}wScroll = (mod({p}wRainScroll + {p}wHash, 32.0) + {p}wPartialTicks) / 32.0 * (3.0 + {jitter}.x); + {p}wDrift = vec2(0.0); + {p}wAlpha = {p}wFade * 0.5 + 0.5; + } + + {tex0} = vec4({corner}.x + {p}wDrift.x, {p}wCornerY * 0.25 + {p}wScroll + {p}wDrift.y, 0.0, 1.0); + {tex1} = vec4({p}wLightmap, 0.0, 1.0); + {color} = vec4(1.0, 1.0, 1.0, {p}wAlpha * {p}wStrength);"""; + + public static String weatherPrologue(String uniformPrefix, String attribPrefix, String corner, + String vertex, String color, String tex0, String tex1, String sep) { + return WEATHER_PROLOGUE + .replace("{p}", uniformPrefix) + .replace("{span}", attribPrefix + "InstColumnSpan") + .replace("{jitter}", attribPrefix + "InstJitter") + .replace("{params}", attribPrefix + "InstWeatherParams") + .replace("{corner}", corner) + .replace("{vertex}", vertex) + .replace("{color}", color) + .replace("{tex0}", tex0) + .replace("{tex1}", tex1) + .replace("\n", sep); + } + public static String cubePrelude(String prefix, String mid, String delta, String normal, String tex, String sep) { return "float " + prefix + "cubeMirror = " + tex + ".z < 0.0 ? 1.0 : 0.0;" + sep + "vec2 " + prefix + "cubeMidU = " + mid + ".xy - " + prefix + "cubeMirror * " + normal + ".x;" + sep @@ -65,6 +121,11 @@ public final class InstancedGlslHelpers { decls.add(decl(ParticleInstancedAttribs.LOC_COLOR, "vec4", prefix + "InstColor")); decls.add(decl(ParticleInstancedAttribs.LOC_LIGHTMAP, "vec2", prefix + "InstLightmap")); } + case WEATHER -> { + decls.add(decl(WeatherInstancedAttribs.LOC_COLUMN_SPAN, "vec4", prefix + "InstColumnSpan")); + decls.add(decl(WeatherInstancedAttribs.LOC_JITTER, "vec4", prefix + "InstJitter")); + decls.add(decl(WeatherInstancedAttribs.LOC_PARAMS, "vec4", prefix + "InstWeatherParams")); + } } return decls.toArray(String[]::new); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java index 58b0e4431..e0b1bce16 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java @@ -4,7 +4,8 @@ public enum Instancing { NONE(""), TEMPLATE("_instanced"), CUBE("_cubeinstanced"), - PARTICLE("_particleinstanced"); + PARTICLE("_particleinstanced"), + WEATHER("_weatherinstanced"); public static final Instancing[] VALUES = values(); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java index c0b528fa2..968129a26 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java @@ -49,6 +49,7 @@ public class Uniforms { private float lightmapX = Float.NaN, lightmapY = Float.NaN, lineWidth = Float.NaN; private int viewportX = Integer.MIN_VALUE, viewportY = Integer.MIN_VALUE, viewportWidth = -1, viewportHeight = -1; private int lineStipple = -1; + private int weatherGen = -1; int blockWrites; int blockSkips; @@ -192,6 +193,12 @@ public class Uniforms { stagedMisc++; dirty = true; } + if (WeatherParams.generation != weatherGen) { + stageWeatherParams(); + weatherGen = WeatherParams.generation; + stagedMisc++; + dirty = true; + } final int stippleFactor = Math.max(line.getStippleFactor(), 1); final int stipplePacked = (line.getStipplePattern() & 0xFFFF) | (stippleFactor << 16); if (stipplePacked != lineStipple) { @@ -379,6 +386,15 @@ public class Uniforms { putVec3(offset + 32, m.m20(), m.m21(), m.m22()); } + private void stageWeatherParams() { + putVec4(FFPUniformBlock.WEATHER_PARAMS_0, WeatherParams.translateX, WeatherParams.translateY, + WeatherParams.translateZ, WeatherParams.invRadius); + putVec4(FFPUniformBlock.WEATHER_PARAMS_1, WeatherParams.cameraFracX, WeatherParams.cameraFracZ, + WeatherParams.partialTicks, WeatherParams.age); + putVec4(FFPUniformBlock.WEATHER_PARAMS_2, WeatherParams.rainScroll, WeatherParams.snowScroll, + WeatherParams.rainStrength, 0.0f); + } + private void putVec4(int offset, Vector4f v) { putVec4(offset, v.x, v.y, v.z, v.w); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java index 460d47d97..76ac72d28 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -51,6 +51,13 @@ public final class VertexKey { private static final int BIT_UNIT23_UV_FROM_UNIT0 = BIT_UNIT_TEXMAT_BASE + MAX_UNITS; private static final int BIT_LINE_STIPPLE = BIT_UNIT23_UV_FROM_UNIT0 + 1; private static final int BIT_INSTANCING = BIT_LINE_STIPPLE + 1; + private static final long INSTANCING_MASK = 0x7L; + + static { + if (Instancing.VALUES.length > INSTANCING_MASK + 1) { + throw new IllegalStateException("Instancing has outgrown the VertexKey field; widen INSTANCING_MASK"); + } + } public static final int TG_NONE = 0; public static final int TG_OBJ_LINEAR = 1; @@ -98,7 +105,7 @@ public final class VertexKey { public boolean clipPlanesEnabled() { return bit(BIT_CLIP_PLANES); } public boolean wideLineEmulation() { return bit(BIT_WIDE_LINE); } public boolean lineStipple() { return bit(BIT_LINE_STIPPLE); } - public Instancing instancing() { return Instancing.VALUES[(int) ((packed >> BIT_INSTANCING) & 0x3)]; } + public Instancing instancing() { return Instancing.VALUES[(int) ((packed >> BIT_INSTANCING) & INSTANCING_MASK)]; } public boolean cmReplacesAmbient() { final int m = colorMaterialMode(); return m == CM_AMBIENT || m == CM_AMBIENT_AND_DIFFUSE; } public boolean cmReplacesDiffuse() { final int m = colorMaterialMode(); return m == CM_DIFFUSE || m == CM_AMBIENT_AND_DIFFUSE; } @@ -245,7 +252,7 @@ public final class VertexKey { } static long withInstancing(long packed, Instancing kind) { - return (packed & ~(0x3L << BIT_INSTANCING)) | ((long) kind.ordinal() << BIT_INSTANCING); + return (packed & ~(INSTANCING_MASK << BIT_INSTANCING)) | ((long) kind.ordinal() << BIT_INSTANCING); } public static VertexKey fromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap, int fragUnitMask) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java index 9f8133eeb..bd3ce9604 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java @@ -21,6 +21,10 @@ public final class VertexShaderGenerator { emitOutputs(sb, key); sb.append("void main() {\n"); + if (key.instancing() == Instancing.WEATHER) { + sb.append(" ").append(InstancedGlslHelpers.weatherPrologue("u_", "a_", "a_TexCoord0", + "vec4 weatherVertex", "vec4 weatherColor", "vec4 weatherTex0", "vec4 weatherTex1", "\n ")).append('\n'); + } emitPositionTransform(sb, key); if (key.lightingEnabled()) { emitNormalTransform(sb, key); @@ -58,7 +62,7 @@ public final class VertexShaderGenerator { final Instancing kind = key.instancing(); sb.append("// Vertex attributes\n"); sb.append("layout(location = ").append(VertexFormatElement.Usage.POSITION.getAttributeLocation()).append(") in vec3 a_Position;\n"); - if (kind == Instancing.PARTICLE) { + if (kind == Instancing.PARTICLE || kind == Instancing.WEATHER) { sb.append("layout(location = ").append(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation()).append(") in vec2 a_TexCoord0;\n"); } else { if (key.hasVertexColor()) { @@ -88,6 +92,7 @@ public final class VertexShaderGenerator { return switch (key.instancing()) { case CUBE -> "cubeUv"; case PARTICLE -> PARTICLE_UV; + case WEATHER -> "weatherTex0"; case NONE, TEMPLATE -> key.hasVertexTexCoord() ? "vec4(a_TexCoord0, 0.0, 1.0)" : "u_CurrentTexCoord0"; }; } @@ -134,6 +139,8 @@ public final class VertexShaderGenerator { sb.append(" // Position transform\n"); if (key.instancing() == Instancing.PARTICLE) { sb.append(" vec4 pos4 = ").append(InstancedGlslHelpers.particlePos("a_InstCenterHalf", "a_Position")).append(";\n"); + } else if (key.instancing() == Instancing.WEATHER) { + sb.append(" vec4 pos4 = weatherVertex;\n"); } else { sb.append(" vec4 pos4 = vec4(a_Position, 1.0);\n"); } @@ -282,6 +289,7 @@ public final class VertexShaderGenerator { final String src = key.hasVertexColor() ? "a_Color" : "u_CurrentColor"; switch (key.instancing()) { case PARTICLE -> sb.append(" v_Color = a_InstColor;\n"); + case WEATHER -> sb.append(" v_Color = weatherColor;\n"); case TEMPLATE, CUBE -> sb.append(" v_Color = ").append(src).append(" * a_InstColor;\n"); case NONE -> sb.append(" v_Color = ").append(src).append(";\n"); } @@ -312,6 +320,7 @@ public final class VertexShaderGenerator { final String lightmap = switch (key.instancing()) { case PARTICLE, TEMPLATE -> "a_InstLightmap"; case CUBE -> "a_InstLightmapScale.xy"; + case WEATHER -> "weatherTex1.xy"; case NONE -> key.hasVertexLightmap() ? "a_TexCoord1" : "u_CurrentLightmapCoord"; }; sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(").append(lightmap).append(", 0.0, 1.0);\n"); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherInstancedAttribs.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherInstancedAttribs.java new file mode 100644 index 000000000..bf89b8ea5 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherInstancedAttribs.java @@ -0,0 +1,34 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; + + +/** + * One rain or snow column per instance. + */ +public final class WeatherInstancedAttribs { + + public static final int LOC_COLUMN_SPAN = ParticleInstancedAttribs.LOC_CENTER_HALF; + public static final int LOC_JITTER = ParticleInstancedAttribs.LOC_UV; + public static final int LOC_PARAMS = InstancedAttribs.LOC_COLOR; + + public static final int OFFSET_COLUMN_SPAN = 0; + public static final int OFFSET_JITTER = 16; + public static final int OFFSET_PARAMS = 32; + public static final int STRIDE = 48; + + public static void pointInstanceAttribs(long base) { + GLStateManager.glVertexAttribPointer(LOC_COLUMN_SPAN, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_COLUMN_SPAN); + GLStateManager.glVertexAttribPointer(LOC_JITTER, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_JITTER); + GLStateManager.glVertexAttribPointer(LOC_PARAMS, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_PARAMS); + } + + static void enableInstanceArrays() { + InstancedAttribs.enableInstanced(LOC_COLUMN_SPAN); + InstancedAttribs.enableInstanced(LOC_JITTER); + InstancedAttribs.enableInstanced(LOC_PARAMS); + } + + private WeatherInstancedAttribs() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherParams.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherParams.java new file mode 100644 index 000000000..eef810b8b --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherParams.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +/** + * The per-frame half of the rain and snow instancing, set once per weather draw. + */ +public final class WeatherParams { + + public static float translateX; + public static float translateY; + public static float translateZ; + public static float invRadius; + + public static float cameraFracX; + public static float cameraFracZ; + public static float partialTicks; + public static float age; + + public static float rainScroll; + public static float snowScroll; + public static float rainStrength; + + public static int generation; + + private WeatherParams() {} + + public static void set(float translateX, float translateY, float translateZ, float invRadius, + float cameraFracX, float cameraFracZ, float partialTicks, float age, + float rainScroll, float snowScroll, float rainStrength) { + WeatherParams.translateX = translateX; + WeatherParams.translateY = translateY; + WeatherParams.translateZ = translateZ; + WeatherParams.invRadius = invRadius; + WeatherParams.cameraFracX = cameraFracX; + WeatherParams.cameraFracZ = cameraFracZ; + WeatherParams.partialTicks = partialTicks; + WeatherParams.age = age; + WeatherParams.rainScroll = rainScroll; + WeatherParams.snowScroll = snowScroll; + WeatherParams.rainStrength = rainStrength; + generation++; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherQuadMesh.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherQuadMesh.java new file mode 100644 index 000000000..1da961984 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/WeatherQuadMesh.java @@ -0,0 +1,69 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * The four corners every rain and snow column is expanded from. x picks the end of the billboard, y picks + * the bottom or top edge. + */ +public final class WeatherQuadMesh { + + public static final int VERTEX_FLAGS = VertexFlags.TEXTURE_BIT; + public static final int VERTEX_COUNT = 4; + + private static final float[] CORNERS = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; + + private static int vao; + private static int vbo; + + private WeatherQuadMesh() {} + + public static int vao() { + if (vao != 0) return vao; + + final ByteBuffer data = ByteBuffer.allocateDirect(CORNERS.length * Float.BYTES).order(ByteOrder.nativeOrder()); + for (float corner : CORNERS) data.putFloat(corner); + data.flip(); + + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW); + + final int corner = VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(); + GLStateManager.glEnableVertexAttribArray(corner); + GLStateManager.glVertexAttribPointer(corner, 2, GL11.GL_FLOAT, false, 2 * Float.BYTES, 0L); + WeatherInstancedAttribs.enableInstanceArrays(); + + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + return vao; + } + + public static void bindInstanceBuffer(int bufferId) { + GLStateManager.glBindVertexArray(vao()); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, bufferId); + WeatherInstancedAttribs.pointInstanceAttribs(0L); + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + public static void delete() { + if (vbo != 0) { + GLStateManager.glDeleteBuffers(vbo); + vbo = 0; + } + if (vao != 0) { + GLStateManager.glDeleteVertexArrays(vao); + vao = 0; + } + } +} diff --git a/scripts/flyby-compare.py b/scripts/flyby-compare.py index bb576c9de..3c27f7142 100755 --- a/scripts/flyby-compare.py +++ b/scripts/flyby-compare.py @@ -14,8 +14,9 @@ PLOTS = [ "items.bail.ineligible", "items.bail.material", "items.bail.isbrh", "items.bail.blockState", "items.bail.notAllowed", "items.bail.template", "items.bail.queue", "particles.direct", "particles.captured", "particles.spilled", "particles.undecodable", "particles.draws", "sdl.renderPasses", "sdl.submits", "sdl.gpuWaitUs", "sdl.acquireWaitUs", + "weather.strength", "weather.quads", "weather.drawCalls", "weather.micros", ] -ZONES = ["entityModelParts", "tesrBatch", "tesrInstanced", "entityLayerLoop", "tesrOpaque", "particlePass"] +ZONES = ["entityModelParts", "tesrBatch", "tesrInstanced", "entityLayerLoop", "tesrOpaque", "particlePass", "cl:weather"] CLOCK = "gl.drawCalls" diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/dragonapi/DragonAPICompat.java b/src/main/java/com/gtnewhorizons/angelica/compat/dragonapi/DragonAPICompat.java new file mode 100644 index 000000000..1b50d8e89 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/dragonapi/DragonAPICompat.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.compat.dragonapi; + +public final class DragonAPICompat { + + private DragonAPICompat() {} + + public static boolean forcingSeasonalSnow; +} diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 0399ed0d2..1a981e642 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -63,6 +63,10 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean enableVBOClouds; + @Config.Comment("Replace rain/snow rendering with a cached, instanced version.") + @Config.DefaultBoolean(true) + public static boolean enableInstancedWeather; + @Config.Comment("Uses cached attributes for VBO rendering, resulting in less CPU overhead. Disable if you notice any graphical issues.") @Config.DefaultBoolean(true) @Config.RequiresMcRestart diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java index 35bacac0c..8ad0d0d14 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java @@ -22,6 +22,7 @@ import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.world.MinecraftException; +import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; @@ -215,6 +216,8 @@ public final class FlybyRunner { final EntityClientPlayerMP player = mc.thePlayer; if (player == null || mc.theWorld == null) return; + pinClientWeather(mc.theWorld); + switch (this.state) { case WAITING -> { if (!this.armed) { @@ -569,6 +572,13 @@ public final class FlybyRunner { server.getConfigurationManager().sendChatMsg(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Flyby: world saving is off until you leave this world")); } + + private static void pinClientWeather(World world) { + final SystemProperties.FlybyWeather weather = SystemProperties.FLYBY_WEATHER; + world.rainingStrength = world.prevRainingStrength = weather.isRaining() ? 1.0f : 0.0f; + world.thunderingStrength = world.prevThunderingStrength = weather.isThundering() ? 1.0f : 0.0f; + } + private void applyFreeze(MinecraftServer server) { for (WorldServer world : server.worldServers) { if (world == null) continue; @@ -577,13 +587,17 @@ public final class FlybyRunner { world.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); LOGGER.warn("Flyby: doDaylightCycle was on, disabled it"); } - if (world.getWorldInfo().isRaining() || world.getWorldInfo().isThundering()) { - LOGGER.warn("Flyby: weather was active, clearing it"); - world.getWorldInfo().setRaining(false); - world.getWorldInfo().setThundering(false); + final SystemProperties.FlybyWeather weather = SystemProperties.FLYBY_WEATHER; + if (world.getWorldInfo().isRaining() != weather.isRaining() + || world.getWorldInfo().isThundering() != weather.isThundering()) { + LOGGER.warn("Flyby: forcing weather to {}", weather); + world.getWorldInfo().setRaining(weather.isRaining()); + world.getWorldInfo().setThundering(weather.isThundering()); } world.getWorldInfo().setRainTime(Integer.MAX_VALUE); world.getWorldInfo().setThunderTime(Integer.MAX_VALUE); + world.rainingStrength = world.prevRainingStrength = weather.isRaining() ? 1.0f : 0.0f; + world.thunderingStrength = world.prevThunderingStrength = weather.isThundering() ? 1.0f : 0.0f; if (world.getWorldTime() % 24000L != SystemProperties.FLYBY_TIME_OF_DAY) { LOGGER.info("Flyby: freezing time at {}", SystemProperties.FLYBY_TIME_OF_DAY); diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 3006f52b9..eb10d6613 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -71,6 +71,13 @@ public enum Mixins implements IMixins { ) ), + ANGELICA_WEATHER(new MixinBuilder() + .setPhase(Phase.EARLY) + .addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_MIST) + .addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_ORIGINAL) + .addClientMixins("angelica.rendering.MixinEntityRenderer_Weather") + ), + STARMINER_RENDERER_LIVING_ENTITY_OPTIMIZATION(new MixinBuilder() .setPhase(Phase.LATE) .addRequiredMod(TargetedMod.STARMINER) @@ -505,6 +512,14 @@ public enum Mixins implements IMixins { ) ), + DRAGONAPI_SEASONAL_SNOW(new MixinBuilder("Let DragonAPI's Xmas forced-snow event override weather rendering") + .setPhase(Phase.EARLY) + .addRequiredMod(TargetedMod.DRAGON_API) + .addClientMixins( + "dragonapi.MixinSpecialDayTracker" + ) + ), + IRIS_RENDERING_NOBACKHAND(new MixinBuilder("Iris Hand Shaders") .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.enableIris) diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/EntityRendererAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/EntityRendererAccessor.java index ab44d5c18..bda51395b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/EntityRendererAccessor.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/EntityRendererAccessor.java @@ -10,4 +10,7 @@ public interface EntityRendererAccessor { * Get the lightmap texture for shader binding. */ DynamicTexture getLightmapTexture(); + + /** Drives the rain and snow texture scroll. */ + int getRendererUpdateCount(); } diff --git a/src/main/java/com/gtnewhorizons/angelica/render/WeatherColumns.java b/src/main/java/com/gtnewhorizons/angelica/render/WeatherColumns.java new file mode 100644 index 000000000..8d0dbe3bf --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/render/WeatherColumns.java @@ -0,0 +1,213 @@ +package com.gtnewhorizons.angelica.render; + +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.world.biome.BiomeGenBase; + +import java.lang.ref.WeakReference; +import java.util.Arrays; +import java.util.Random; + +/** + * Per-column rain and snow data, sampled once and reused instead of recomputed for every column of every frame. + */ +public final class WeatherColumns { + + private static final float TEMPERATURE_PER_BLOCK = 0.05F / 30.0F; + private static final int TEMPERATURE_REFERENCE_Y = 65; + + private static final int REFRESH_TICKS = 20; + + private final Random random = new Random(); + + private int size; + private int[] keyX = new int[0]; + private int[] keyZ = new int[0]; + private boolean[] present = new boolean[0]; + private boolean[] precipitates = new boolean[0]; + private boolean[] strikesLightning = new boolean[0]; + private int[] height = new int[0]; + private int[] hash = new int[0]; + private float[] temperatureAtReference = new float[0]; + private float[] temperatureBelow65 = new float[0]; + private int[] light = new int[0]; + private int[] lightY = new int[0]; + private float[] jitter = new float[0]; + + private int refreshCursor; + private int revision; + private int lastTick = Integer.MIN_VALUE; + private int originX = Integer.MIN_VALUE; + private int originZ = Integer.MIN_VALUE; + private WeakReference lastWorld = new WeakReference<>(null); + + public int revision() { + return revision; + } + + public void update(WorldClient world, int cameraBlockX, int cameraBlockZ, int radius, int tick) { + final int wanted = radius * 2 + 1; + final boolean resized = wanted != size; + if (resized) resize(wanted); + + final boolean worldChanged = lastWorld.get() != world; + if (worldChanged) { + lastWorld = new WeakReference<>(world); + Arrays.fill(present, false); + originX = Integer.MIN_VALUE; + originZ = Integer.MIN_VALUE; + revision++; + } + + final int slots = size * size; + if (tick != lastTick) { + lastTick = tick; + final int slice = Math.max(1, slots / REFRESH_TICKS); + for (int i = 0; i < slice; i++) { + if (++refreshCursor >= slots) refreshCursor = 0; + if (present[refreshCursor]) sample(world, keyX[refreshCursor], keyZ[refreshCursor], refreshCursor); + } + } + + if (!resized && cameraBlockX == originX && cameraBlockZ == originZ) return; + originX = cameraBlockX; + originZ = cameraBlockZ; + + for (int dz = -radius; dz <= radius; dz++) { + for (int dx = -radius; dx <= radius; dx++) { + final int x = cameraBlockX + dx; + final int z = cameraBlockZ + dz; + final int slot = slotOf(x, z); + if (present[slot] && keyX[slot] == x && keyZ[slot] == z) continue; + sample(world, x, z, slot); + } + } + } + + public boolean precipitates(int x, int z) { + return precipitates[slotOf(x, z)]; + } + + public int slotAt(int x, int z) { + return slotOf(x, z); + } + + public boolean precipitatesAtSlot(int slot) { + return precipitates[slot]; + } + + public int heightAtSlot(int slot) { + return height[slot]; + } + + public int hashAtSlot(int slot) { + return hash[slot]; + } + + public float jitterAtSlot(int slot, int index) { + return jitter[slot * 4 + index]; + } + + public float temperatureAtSlot(int slot, int y) { + if (y <= 64) return temperatureBelow65[slot]; + return temperatureAtReference[slot] - (y - TEMPERATURE_REFERENCE_Y) * TEMPERATURE_PER_BLOCK; + } + + public int lightAtSlot(WorldClient world, int slot, int x, int z, int y) { + if (lightY[slot] != y) { + lightY[slot] = y; + light[slot] = world.getLightBrightnessForSkyBlocks(x, y, z, 0); + } + return light[slot]; + } + + public boolean covers(int x, int z) { + if (size == 0) return false; + final int slot = slotOf(x, z); + return present[slot] && keyX[slot] == x && keyZ[slot] == z; + } + + public boolean strikesLightning(int x, int z) { + return strikesLightning[slotOf(x, z)]; + } + + public int heightAt(int x, int z) { + return height[slotOf(x, z)]; + } + + public int hashAt(int x, int z) { + return hash[slotOf(x, z)]; + } + + public float temperatureAt(int x, int z, int y) { + final int slot = slotOf(x, z); + if (y <= 64) return temperatureBelow65[slot]; + return temperatureAtReference[slot] - (y - TEMPERATURE_REFERENCE_Y) * TEMPERATURE_PER_BLOCK; + } + + public int lightAt(WorldClient world, int x, int z, int y) { + final int slot = slotOf(x, z); + if (lightY[slot] != y) { + lightY[slot] = y; + light[slot] = world.getLightBrightnessForSkyBlocks(x, y, z, 0); + } + return light[slot]; + } + + public float jitterAt(int x, int z, int index) { + return jitter[slotOf(x, z) * 4 + index]; + } + + private int slotOf(int x, int z) { + return Math.floorMod(x, size) * size + Math.floorMod(z, size); + } + + private void resize(int wanted) { + size = wanted; + final int slots = wanted * wanted; + keyX = new int[slots]; + keyZ = new int[slots]; + present = new boolean[slots]; + precipitates = new boolean[slots]; + strikesLightning = new boolean[slots]; + height = new int[slots]; + hash = new int[slots]; + temperatureAtReference = new float[slots]; + temperatureBelow65 = new float[slots]; + light = new int[slots]; + lightY = new int[slots]; + jitter = new float[slots * 4]; + refreshCursor = 0; + } + + private void sample(WorldClient world, int x, int z, int slot) { + final boolean sameColumn = present[slot] && keyX[slot] == x && keyZ[slot] == z; + final boolean wasPrecipitating = precipitates[slot]; + final int wasHeight = height[slot]; + + keyX[slot] = x; + keyZ[slot] = z; + present[slot] = true; + lightY[slot] = Integer.MIN_VALUE; + + final BiomeGenBase biome = world.getBiomeGenForCoords(x, z); + strikesLightning[slot] = biome.canSpawnLightningBolt(); + precipitates[slot] = strikesLightning[slot] || biome.getEnableSnow(); + if (!sameColumn || precipitates[slot] != wasPrecipitating) revision++; + if (!precipitates[slot]) return; + + height[slot] = world.getPrecipitationHeight(x, z); + if (height[slot] != wasHeight) revision++; + temperatureAtReference[slot] = biome.getFloatTemperature(x, TEMPERATURE_REFERENCE_Y, z); + temperatureBelow65[slot] = biome.getFloatTemperature(x, 64, z); + + // Vanilla overflows these in int before widening + hash[slot] = x * x * 3121 + x * 45238971 + z * z * 418711 + z * 13761; + random.setSeed((long) x * x * 3121 + x * 45238971L ^ (long) z * z * 418711 + z * 13761L); + + final int base = slot * 4; + jitter[base] = random.nextFloat(); + jitter[base + 1] = (float) random.nextGaussian(); + jitter[base + 2] = random.nextFloat(); + jitter[base + 3] = (float) random.nextGaussian(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/render/WeatherRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/WeatherRenderer.java new file mode 100644 index 000000000..218ac199d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/render/WeatherRenderer.java @@ -0,0 +1,528 @@ +package com.gtnewhorizons.angelica.render; + +import com.gtnewhorizons.angelica.compat.dragonapi.DragonAPICompat; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.glsm.ffp.WeatherInstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.WeatherParams; +import com.gtnewhorizons.angelica.glsm.ffp.WeatherQuadMesh; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; +import jss.notfine.core.SettingsManager; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.particle.EntityRainFX; +import net.minecraft.client.particle.EntitySmokeFX; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraft.world.biome.WorldChunkManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Random; + +/** + * Replaces EntityRenderer.renderRainSnow. + * + *

The whole grid is one instanced draw per precipitation type. Everything that varies per frame + * (billboard axis, distance falloff, texture scroll, snow drift) happens in the vertex shader, and the + * instance buffer is only rebuilt when the camera changes block or {@link WeatherColumns} actually + * resamples something. Per-column data comes from that cache rather than being recomputed every frame. + */ +public final class WeatherRenderer { + + private static final ResourceLocation RAIN_TEXTURE = new ResourceLocation("textures/environment/rain.png"); + private static final ResourceLocation SNOW_TEXTURE = new ResourceLocation("textures/environment/snow.png"); + + private static final int REBUILD_TICKS = 20; + + private static final long P_STRENGTH = Tracy.plotHandle("weather.strength"); + private static final long P_QUADS = Tracy.plotHandle("weather.quads"); + private static final long P_DRAW_CALLS = Tracy.plotHandle("weather.drawCalls"); + private static final long P_MICROS = Tracy.plotHandle("weather.micros"); + private static final long P_REBUILDS = Tracy.plotHandle("weather.rebuilds"); + private static final long P_PARTICLE_MICROS = Tracy.plotHandle("weather.particleMicros"); + private static final long P_PARTICLES_SPAWNED = Tracy.plotHandle("weather.particlesSpawned"); + + private static final WeatherColumns columns = new WeatherColumns(); + + private static float[] axisX; + private static float[] axisZ; + + private static int instanceBuffer; + private static ByteBuffer instanceData; + private static int instanceCapacity; + private static int instanceCount; + private static int rainInstances; + + private static int builtRevision = Integer.MIN_VALUE; + private static int builtX = Integer.MIN_VALUE; + private static int builtY = Integer.MIN_VALUE; + private static int builtZ = Integer.MIN_VALUE; + private static int builtRadius = -1; + private static int builtUpdateCount = Integer.MIN_VALUE; + private static int builtCameraY = Integer.MIN_VALUE; + private static boolean rebuiltThisFrame; + + private static final int PARTICLE_RADIUS = 10; + private static final Random particleRandom = new Random(); + private static int rainSoundCounter; + + private WeatherRenderer() {} + + /** Replaces EntityRenderer.addRainParticles */ + public static boolean spawnRainParticles() { + if (!AngelicaConfig.enableInstancedWeather) return false; + if (SettingsManager.downfallDistance < PARTICLE_RADIUS) return false; + + final long startNanos = System.nanoTime(); + final Minecraft mc = Minecraft.getMinecraft(); + final WorldClient world = mc.theWorld; + if (world.provider.getWeatherRenderer() != null) return false; + float strength = world.getRainStrength(1.0F); + if (!mc.gameSettings.fancyGraphics) strength /= 2.0F; + if (strength == 0.0F) { + Tracy.plot(P_PARTICLE_MICROS, 0.0); + Tracy.plotInt(P_PARTICLES_SPAWNED, 0); + return true; + } + + int attempts = (int) (100.0F * strength * strength); + if (mc.gameSettings.particleSetting == 1) attempts >>= 1; + else if (mc.gameSettings.particleSetting == 2) attempts = 0; + + final int updateCount = ((EntityRendererAccessor) mc.entityRenderer).getRendererUpdateCount(); + particleRandom.setSeed(updateCount * 312987231L); + + final EntityLivingBase view = mc.renderViewEntity; + final int originX = MathHelper.floor_double(view.posX); + final int originY = MathHelper.floor_double(view.posY); + final int originZ = MathHelper.floor_double(view.posZ); + + double soundX = 0.0D, soundY = 0.0D, soundZ = 0.0D; + int landed = 0; + int spawned = 0; + + for (int attempt = 0; attempt < attempts; attempt++) { + final int x = originX + particleRandom.nextInt(PARTICLE_RADIUS) - particleRandom.nextInt(PARTICLE_RADIUS); + final int z = originZ + particleRandom.nextInt(PARTICLE_RADIUS) - particleRandom.nextInt(PARTICLE_RADIUS); + + final int height; + final boolean eligible; + if (columns.covers(x, z)) { + height = columns.heightAt(x, z); + eligible = columns.strikesLightning(x, z) + && height <= originY + PARTICLE_RADIUS && height >= originY - PARTICLE_RADIUS + && columns.temperatureAt(x, z, height) >= 0.15F; + } else { + height = world.getPrecipitationHeight(x, z); + final BiomeGenBase biome = world.getBiomeGenForCoords(x, z); + eligible = height <= originY + PARTICLE_RADIUS && height >= originY - PARTICLE_RADIUS + && biome.canSpawnLightningBolt() && biome.getFloatTemperature(x, height, z) >= 0.15F; + } + if (!eligible) continue; + + final float offsetX = particleRandom.nextFloat(); + final float offsetZ = particleRandom.nextFloat(); + + final Block block = world.getBlock(x, height - 1, z); + final Material material = block.getMaterial(); + if (material == Material.air) continue; + final double dropY = (height + 0.1F) - block.getBlockBoundsMinY(); + + if (material == Material.lava) { + mc.effectRenderer.addEffect(new EntitySmokeFX(world, x + offsetX, dropY, z + offsetZ, 0.0D, 0.0D, 0.0D)); + } else { + landed++; + if (particleRandom.nextInt(landed) == 0) { + soundX = x + offsetX; + soundY = dropY; + soundZ = z + offsetZ; + } + mc.effectRenderer.addEffect(new EntityRainFX(world, x + offsetX, dropY, z + offsetZ)); + } + spawned++; + } + Tracy.plotInt(P_PARTICLES_SPAWNED, spawned); + Tracy.plot(P_PARTICLE_MICROS, (System.nanoTime() - startNanos) / 1000.0); + + if (landed > 0 && particleRandom.nextInt(3) < rainSoundCounter++) { + rainSoundCounter = 0; + final int playerHeight = columns.covers(originX, originZ) && columns.precipitates(originX, originZ) + ? columns.heightAt(originX, originZ) + : world.getPrecipitationHeight(originX, originZ); + if (soundY > view.posY + 1.0D && playerHeight > originY) { + world.playSound(soundX, soundY, soundZ, "ambient.weather.rain", 0.1F, 0.5F, false); + } else { + world.playSound(soundX, soundY, soundZ, "ambient.weather.rain", 0.2F, 1.0F, false); + } + } + return true; + } + + public static boolean render(float partialTicks) { + final Minecraft mc = Minecraft.getMinecraft(); + final WorldClient world = mc.theWorld; + final long startNanos = System.nanoTime(); + if (!AngelicaConfig.enableInstancedWeather) return false; + if (world.provider.getWeatherRenderer() != null) { + Tracy.plot(P_STRENGTH, 0.0); + report(0, 0, startNanos); + return false; + } + if (DragonAPICompat.forcingSeasonalSnow) { + report(0, 0, startNanos); + return false; + } + final float rainStrength = world.getRainStrength(partialTicks); + Tracy.plot(P_STRENGTH, rainStrength); + + final int radius = SettingsManager.downfallDistance; + if (rainStrength <= 0.0F || radius <= 0) { + report(0, 0, startNanos); + return true; + } + buildAxisTable(); + + final EntityLivingBase view = mc.renderViewEntity; + final int entityBlockX = MathHelper.floor_double(view.posX); + final int entityBlockY = MathHelper.floor_double(view.posY); + final int entityBlockZ = MathHelper.floor_double(view.posZ); + + final double cameraX = view.lastTickPosX + (view.posX - view.lastTickPosX) * partialTicks; + final double cameraY = view.lastTickPosY + (view.posY - view.lastTickPosY) * partialTicks; + final double cameraZ = view.lastTickPosZ + (view.posZ - view.lastTickPosZ) * partialTicks; + final int cameraBlockY = MathHelper.floor_double(cameraY); + + final int updateCount = ((EntityRendererAccessor) mc.entityRenderer).getRendererUpdateCount(); + columns.update(world, entityBlockX, entityBlockZ, radius, updateCount); + + final DeferredWorldRenderingPipeline deferred = deferredPipeline(); + + if (deferred != null && !deferred.supportsInstancing(Instancing.WEATHER)) { + renderTessellator(mc, world, view, partialTicks, rainStrength, radius, updateCount, + entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos); + return true; + } + + renderInstanced(mc, world, view, deferred, partialTicks, rainStrength, radius, updateCount, + entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos); + return true; + } + + private static DeferredWorldRenderingPipeline deferredPipeline() { + if (!AngelicaConfig.enableIris || !Iris.enabled) return null; + return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline pipeline + ? pipeline : null; + } + + private static void renderInstanced(Minecraft mc, WorldClient world, EntityLivingBase view, + DeferredWorldRenderingPipeline deferred, float partialTicks, float rainStrength, int radius, + int updateCount, int entityBlockX, int entityBlockY, int entityBlockZ, double cameraX, + double cameraY, double cameraZ, int cameraBlockY, long startNanos) { + + final boolean rebuild = SystemProperties.WEATHER_REBUILD_ALWAYS + || updateCount - builtUpdateCount >= REBUILD_TICKS + || columns.revision() != builtRevision + || entityBlockX != builtX || entityBlockY != builtY || entityBlockZ != builtZ + || cameraBlockY != builtCameraY + || radius != builtRadius; + if (rebuild) { + rebuildInstances(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY); + builtCameraY = cameraBlockY; + builtRevision = columns.revision(); + builtX = entityBlockX; + builtY = entityBlockY; + builtZ = entityBlockZ; + builtRadius = radius; + builtUpdateCount = updateCount; + } + rebuiltThisFrame = rebuild; + + if (instanceCount == 0) { + report(0, 0, startNanos); + return; + } + + if (deferred != null) { + deferred.rebindCurrentPass(); + if (!deferred.hasInstancedVariant(Instancing.WEATHER)) { + renderTessellator(mc, world, view, partialTicks, rainStrength, radius, updateCount, + entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos); + return; + } + } + + WeatherParams.set((float) (entityBlockX - cameraX), (float) -cameraY, (float) (entityBlockZ - cameraZ), + 1.0F / radius, + (float) (view.posX - entityBlockX), (float) (view.posZ - entityBlockZ), partialTicks, + updateCount + partialTicks, + updateCount & 31, updateCount & 511, rainStrength); + + mc.entityRenderer.enableLightmap(partialTicks); + GLStateManager.disableCull(); + GLStateManager.glNormal3f(0.0F, 1.0F, 0.0F); + GLStateManager.enableBlend(); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + int drawCalls = 0; + drawCalls += drawRange(mc, deferred, RAIN_TEXTURE, 0, rainInstances); + drawCalls += drawRange(mc, deferred, SNOW_TEXTURE, rainInstances, instanceCount - rainInstances); + + GLStateManager.enableCull(); + GLStateManager.disableBlend(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); + mc.entityRenderer.disableLightmap(partialTicks); + + report(instanceCount, drawCalls, startNanos); + } + + private static int drawRange(Minecraft mc, DeferredWorldRenderingPipeline deferred, + ResourceLocation texture, int first, int count) { + if (count <= 0) return 0; + mc.getTextureManager().bindTexture(texture); + + if (deferred != null) { + deferred.rebindCurrentPass(); + if (!deferred.hasInstancedVariant(Instancing.WEATHER)) return 0; + deferred.bindInstancedVariant(Instancing.WEATHER); + } + + GLStateManager.glBindVertexArray(WeatherQuadMesh.vao()); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer); + WeatherInstancedAttribs.pointInstanceAttribs((long) first * WeatherInstancedAttribs.STRIDE); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + VAOManager.setCurrentVertexFlags(WeatherQuadMesh.VERTEX_FLAGS); + if (deferred == null) GLStateManager.ffpInstancing = Instancing.WEATHER; + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLE_FAN, 0, WeatherQuadMesh.VERTEX_COUNT, count); + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + + if (deferred != null) deferred.rebindCurrentPass(); + return 1; + } + + private static void rebuildInstances(WorldClient world, int radius, int entityBlockX, int entityBlockY, + int entityBlockZ, int cameraBlockY) { + final int slots = (radius * 2 + 1) * (radius * 2 + 1); + final int stride = WeatherInstancedAttribs.STRIDE; + if (instanceCapacity < slots) { + instanceCapacity = slots; + instanceData = ByteBuffer.allocateDirect(slots * stride).order(ByteOrder.nativeOrder()); + if (instanceBuffer == 0) instanceBuffer = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, (long) slots * stride, GL15.GL_DYNAMIC_DRAW); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + WeatherQuadMesh.bindInstanceBuffer(instanceBuffer); + } + + int count = writeColumns(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY, true, 0); + rainInstances = count; + count = writeColumns(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY, false, count); + instanceCount = count; + if (count == 0) return; + + instanceData.position(0); + instanceData.limit(count * stride); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer); + GLStateManager.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0L, instanceData); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + instanceData.clear(); + } + + private static int writeColumns(WorldClient world, int radius, int entityBlockX, int entityBlockY, + int entityBlockZ, int cameraBlockY, boolean wantRain, int count) { + final int stride = WeatherInstancedAttribs.STRIDE; + final WorldChunkManager chunkManager = world.getWorldChunkManager(); + for (int z = entityBlockZ - radius; z <= entityBlockZ + radius; z++) { + for (int x = entityBlockX - radius; x <= entityBlockX + radius; x++) { + final int slot = columns.slotAt(x, z); + if (!columns.precipitatesAtSlot(slot)) continue; + + final int precipitationHeight = columns.heightAtSlot(slot); + final int bottom = Math.max(entityBlockY - radius, precipitationHeight); + final int top = Math.max(entityBlockY + radius, precipitationHeight); + if (bottom == top) continue; + + final float temperature = columns.temperatureAtSlot(slot, bottom); + final boolean rain = chunkManager.getTemperatureAtHeight(temperature, precipitationHeight) >= 0.15F; + if (rain != wantRain) continue; + + final int lightY = Math.max(precipitationHeight, cameraBlockY); + int brightness = columns.lightAtSlot(world, slot, x, z, lightY); + if (!rain) brightness = (brightness * 3 + 15728880) / 4; + + final int base = count * stride; + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN, x - entityBlockX); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 4, z - entityBlockZ); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 8, bottom); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 12, top); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER, columns.jitterAtSlot(slot, 0)); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 4, columns.jitterAtSlot(slot, 1)); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 8, columns.jitterAtSlot(slot, 2)); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 12, columns.jitterAtSlot(slot, 3)); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS, brightness & 0xFFFF); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 4, brightness >> 16 & 0xFFFF); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 8, columns.hashAtSlot(slot) & 31); + instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 12, rain ? 0.0F : 1.0F); + count++; + } + } + return count; + } + + private static void renderTessellator(Minecraft mc, WorldClient world, EntityLivingBase view, + float partialTicks, float rainStrength, int radius, int updateCount, int entityBlockX, + int entityBlockY, int entityBlockZ, double cameraX, double cameraY, double cameraZ, + int cameraBlockY, long startNanos) { + + mc.entityRenderer.enableLightmap(partialTicks); + + final float age = updateCount + partialTicks; + GLStateManager.disableCull(); + GLStateManager.glNormal3f(0.0F, 1.0F, 0.0F); + GLStateManager.enableBlend(); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + final Tessellator tessellator = Tessellator.instance; + int bound = -1; + int quads = 0; + int drawCalls = 0; + + for (int z = entityBlockZ - radius; z <= entityBlockZ + radius; z++) { + for (int x = entityBlockX - radius; x <= entityBlockX + radius; x++) { + if (!columns.precipitates(x, z)) continue; + + final int precipitationHeight = columns.heightAt(x, z); + final int bottom = Math.max(entityBlockY - radius, precipitationHeight); + final int top = Math.max(entityBlockY + radius, precipitationHeight); + if (bottom == top) continue; + + final int lightY = Math.max(precipitationHeight, cameraBlockY); + final float temperature = columns.temperatureAt(x, z, bottom); + final boolean rain = world.getWorldChunkManager() + .getTemperatureAtHeight(temperature, precipitationHeight) >= 0.15F; + + final int axis = (z - entityBlockZ + 16) * 32 + x - entityBlockX + 16; + final float halfX = axisX[axis] * 0.5F; + final float halfZ = axisZ[axis] * 0.5F; + + final double offsetX = (x + 0.5F) - view.posX; + final double offsetZ = (z + 0.5F) - view.posZ; + final float distance = MathHelper.sqrt_double(offsetX * offsetX + offsetZ * offsetZ) / radius; + + if (rain) { + if (bound != 0) { + if (bound >= 0) { + tessellator.draw(); + drawCalls++; + } + bound = 0; + mc.getTextureManager().bindTexture(RAIN_TEXTURE); + tessellator.startDrawingQuads(); + } + final float scroll = ((updateCount + columns.hashAt(x, z) & 31) + partialTicks) / 32.0F + * (3.0F + columns.jitterAt(x, z, 0)); + tessellator.setBrightness(columns.lightAt(world, x, z, lightY)); + tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F, + ((1.0F - distance * distance) * 0.5F + 0.5F) * rainStrength); + emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, 0.0F, 0.0F, + cameraX, cameraY, cameraZ); + } else { + if (bound != 1) { + if (bound == 0) { + tessellator.draw(); + drawCalls++; + } + bound = 1; + mc.getTextureManager().bindTexture(SNOW_TEXTURE); + tessellator.startDrawingQuads(); + } + final float scroll = ((updateCount & 511) + partialTicks) / 512.0F; + final float driftU = columns.jitterAt(x, z, 0) + age * 0.01F * columns.jitterAt(x, z, 1); + final float driftV = columns.jitterAt(x, z, 2) + age * columns.jitterAt(x, z, 3) * 0.001F; + tessellator.setBrightness((columns.lightAt(world, x, z, lightY) * 3 + 15728880) / 4); + tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F, + ((1.0F - distance * distance) * 0.3F + 0.5F) * rainStrength); + emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, driftU, driftV, + cameraX, cameraY, cameraZ); + } + quads++; + } + } + + if (bound >= 0) { + tessellator.draw(); + drawCalls++; + } + + GLStateManager.enableCull(); + GLStateManager.disableBlend(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); + mc.entityRenderer.disableLightmap(partialTicks); + + report(quads, drawCalls, startNanos); + } + + private static void emit(Tessellator tessellator, int x, int z, int bottom, int top, float halfX, + float halfZ, float scroll, float driftU, float driftV, double cameraX, double cameraY, double cameraZ) { + tessellator.setTranslation(-cameraX, -cameraY, -cameraZ); + tessellator.addVertexWithUV(x - halfX + 0.5D, bottom, z - halfZ + 0.5D, driftU, bottom / 4.0F + scroll + driftV); + tessellator.addVertexWithUV(x + halfX + 0.5D, bottom, z + halfZ + 0.5D, 1.0F + driftU, bottom / 4.0F + scroll + driftV); + tessellator.addVertexWithUV(x + halfX + 0.5D, top, z + halfZ + 0.5D, 1.0F + driftU, top / 4.0F + scroll + driftV); + tessellator.addVertexWithUV(x - halfX + 0.5D, top, z - halfZ + 0.5D, driftU, top / 4.0F + scroll + driftV); + tessellator.setTranslation(0.0D, 0.0D, 0.0D); + } + + private static void report(int quads, int drawCalls, long startNanos) { + Tracy.plotInt(P_QUADS, quads); + Tracy.plotInt(P_DRAW_CALLS, drawCalls); + Tracy.plotInt(P_REBUILDS, rebuiltThisFrame ? 1 : 0); + Tracy.plot(P_MICROS, (System.nanoTime() - startNanos) / 1000.0); + rebuiltThisFrame = false; + } + + private static void buildAxisTable() { + if (axisX != null) return; + axisX = new float[1024]; + axisZ = new float[1024]; + for (int z = 0; z < 32; z++) { + for (int x = 0; x < 32; x++) { + final float dx = x - 16; + final float dz = z - 16; + final float length = MathHelper.sqrt_float(dx * dx + dz * dz); + axisX[z << 5 | x] = -dz / length; + axisZ[z << 5 | x] = dx / length; + } + } + } + + public static void clear() { + WeatherQuadMesh.delete(); + if (instanceBuffer != 0) { + GLStateManager.glDeleteBuffers(instanceBuffer); + instanceBuffer = 0; + } + instanceData = null; + instanceCapacity = 0; + instanceCount = 0; + rainInstances = 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java index 0e9c20ea8..3fd8e0aa0 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java @@ -53,6 +53,7 @@ import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.render.WeatherRenderer; import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller; import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; @@ -168,6 +169,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer ProgramId.values(); case TEMPLATE, CUBE -> INSTANCED_PROGRAM_IDS; case PARTICLE -> PARTICLE_PROGRAM_IDS; + case WEATHER -> WEATHER_PROGRAM_IDS; }; } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java index 3de74606f..42fbce45a 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -38,6 +38,7 @@ class AttributeTransformer { final boolean instancedVertex = vertex && parameters.instancing != Instancing.NONE; final boolean cubeVertex = vertex && parameters.instancing == Instancing.CUBE; final boolean particleVertex = vertex && parameters.instancing == Instancing.PARTICLE; + final boolean weatherVertex = vertex && parameters.instancing == Instancing.WEATHER; final boolean matrixVertex = vertex && parameters.instancing.hasInstanceHead(); final boolean wantsMvInverse = matrixVertex && transformer.containsCall("gl_ModelViewMatrixInverse"); CoreTransformHelper.injectMatrixUniforms(transformer, vertex ? parameters.instancing : Instancing.NONE); @@ -47,7 +48,7 @@ class AttributeTransformer { aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix"); if (parameters.type == ShaderType.VERTEX) { - if (!particleVertex) { + if (!particleVertex && !weatherVertex) { transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); transformer.injectVariable("layout(location = 1) in vec4 iris_Color;"); if (cubeVertex) { @@ -109,6 +110,10 @@ class AttributeTransformer { init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.particleUv("iris_InstUv", "iris_ParticleCorner")).append(';'); init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0);"); assignMidTexCoord(transformer, init, "vec4((iris_InstUv.x + iris_InstUv.z) * 0.5, (iris_InstUv.y + iris_InstUv.w) * 0.5, 0.0, 1.0)"); + } else if (weatherVertex) { + init.append(InstancedGlslHelpers.weatherPrologue("iris_", "iris_", "iris_WeatherCorner", + "iris_Vertex", "iris_Color", "iris_MultiTexCoord0", "iris_MultiTexCoord1", " ")); + assignMidTexCoord(transformer, init, "vec4(0.5, 0.5, 0.0, 1.0)"); } else { init.append("iris_ModelViewMatrix = ").append(InstancedGlslHelpers.mat4FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';'); init.append(" iris_NormalMatrix = ").append(InstancedGlslHelpers.mat3FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';'); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java index 30c1500ad..7834c7936 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java @@ -35,6 +35,20 @@ class CoreTransformHelper { transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); } + case WEATHER -> { + transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation() + ") in vec2 iris_WeatherCorner;"); + injectAttributeDecls(transformer, instancing); + transformer.injectVariable("uniform vec4 iris_WeatherParams0;"); + transformer.injectVariable("uniform vec4 iris_WeatherParams1;"); + transformer.injectVariable("uniform vec4 iris_WeatherParams2;"); + transformer.injectVariable("vec4 iris_Vertex;"); + transformer.injectVariable("vec4 iris_Color;"); + transformer.injectVariable("vec4 iris_MultiTexCoord0;"); + transformer.injectVariable("vec4 iris_MultiTexCoord1;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + } case TEMPLATE, CUBE -> { injectAttributeDecls(transformer, instancing); transformer.injectVariable("mat4 iris_ModelViewMatrix;"); diff --git a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java index 8dac4d297..adda75ef4 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java @@ -75,6 +75,7 @@ public final class CommonUniforms { IdMapUniforms.addEntityIdMapUniforms(uniforms); FogUniforms.addFogUniforms(uniforms, fogMode); IrisInternalUniforms.addFogUniforms(uniforms, fogMode); + IrisInternalUniforms.addWeatherUniforms(uniforms); uniforms.uniform2i("atlasSize", () -> { final int glId = GLStateManager.getBoundTextureForServerState(0); diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java index eafe9c7d5..c8a33a08d 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java @@ -1,6 +1,7 @@ package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.WeatherParams; import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.gl.uniform.DynamicUniformHolder; @@ -38,6 +39,19 @@ public class IrisInternalUniforms { return func & 0x7; } + private static final Vector4f WEATHER_0 = new Vector4f(); + private static final Vector4f WEATHER_1 = new Vector4f(); + private static final Vector4f WEATHER_2 = new Vector4f(); + + public static void addWeatherUniforms(DynamicUniformHolder uniforms) { + uniforms.uniform4f(PER_FRAME, "iris_WeatherParams0", () -> WEATHER_0.set( + WeatherParams.translateX, WeatherParams.translateY, WeatherParams.translateZ, WeatherParams.invRadius)); + uniforms.uniform4f(PER_FRAME, "iris_WeatherParams1", () -> WEATHER_1.set( + WeatherParams.cameraFracX, WeatherParams.cameraFracZ, WeatherParams.partialTicks, WeatherParams.age)); + uniforms.uniform4f(PER_FRAME, "iris_WeatherParams2", () -> WEATHER_2.set( + WeatherParams.rainScroll, WeatherParams.snowScroll, WeatherParams.rainStrength, 0.0f)); + } + public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode) { uniforms.uniform4f(PER_FRAME, "iris_FogColor", () -> { final Vector3d color = GLStateManager.getFogState().getFogColor(); diff --git a/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java b/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java index 342bdc204..32b2d05a5 100644 --- a/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java +++ b/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java @@ -47,7 +47,8 @@ public final class PerFrameUniformBlockHarvester { private static final Set LIVE_STATE_UNIFORMS = Set.of( "gbufferModelView", "gbufferModelViewInverse", "gbufferPreviousModelView", "gbufferProjection", "gbufferProjectionInverse", "gbufferPreviousProjection", - "fogColor", "iris_FogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity"); + "fogColor", "iris_FogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity", + "iris_WeatherParams0", "iris_WeatherParams1", "iris_WeatherParams2"); /** * @param primary manifest whose entry order defines the block layout diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinEntityRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinEntityRenderer.java index 507deb9fb..402feb4bc 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinEntityRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinEntityRenderer.java @@ -30,6 +30,9 @@ public abstract class MixinEntityRenderer implements EntityRendererAccessor { @Accessor("lightmapTexture") public abstract DynamicTexture getLightmapTexture(); + @Accessor("rendererUpdateCount") + public abstract int getRendererUpdateCount(); + @Inject(method = "renderWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ActiveRenderInfo;updateRenderInfo(Lnet/minecraft/entity/player/EntityPlayer;Z)V", shift = At.Shift.AFTER)) private void angelica$captureCameraMatrix(float partialTicks, long finishTimeNano, CallbackInfo ci) { final Minecraft mc = Minecraft.getMinecraft(); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/rendering/MixinEntityRenderer_Weather.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/rendering/MixinEntityRenderer_Weather.java new file mode 100644 index 000000000..a4ab55e05 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/rendering/MixinEntityRenderer_Weather.java @@ -0,0 +1,22 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.rendering; + +import com.gtnewhorizons.angelica.render.WeatherRenderer; +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_Weather { + + @Inject(method = "renderRainSnow(F)V", at = @At("HEAD"), cancellable = true) + private void angelica$weather(float partialTicks, CallbackInfo ci) { + if (WeatherRenderer.render(partialTicks)) ci.cancel(); + } + + @Inject(method = "addRainParticles", at = @At("HEAD"), cancellable = true) + private void angelica$rainParticles(CallbackInfo ci) { + if (WeatherRenderer.spawnRainParticles()) ci.cancel(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/dragonapi/MixinSpecialDayTracker.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/dragonapi/MixinSpecialDayTracker.java new file mode 100644 index 000000000..ec0b14b9f --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/dragonapi/MixinSpecialDayTracker.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.dragonapi; + +import com.gtnewhorizons.angelica.compat.dragonapi.DragonAPICompat; +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.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Pseudo +@Mixin(targets = "Reika/DragonAPI/Auxiliary/Trackers/SpecialDayTracker", remap = false) +public class MixinSpecialDayTracker { + + // Can't break easter eggs now can we :trolley: + @Inject(method = "loadXmasTextures", at = @At("RETURN")) + private void angelica$captureXmasFlag(CallbackInfoReturnable cir) { + DragonAPICompat.forcingSeasonalSnow = cir.getReturnValue(); + } +}