diff --git a/src/main/java/com/gtnewhorizons/angelica/api/terrain/TerrainRendering.java b/src/main/java/com/gtnewhorizons/angelica/api/terrain/TerrainRendering.java index 61dfd2b2b..5bd8eb87a 100644 --- a/src/main/java/com/gtnewhorizons/angelica/api/terrain/TerrainRendering.java +++ b/src/main/java/com/gtnewhorizons/angelica/api/terrain/TerrainRendering.java @@ -1,19 +1,26 @@ package com.gtnewhorizons.angelica.api.terrain; import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.api.glstate.GLState; import com.gtnewhorizons.angelica.api.shaders.ShaderPacks; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.BlockMaterialAttribute; import com.gtnewhorizons.angelica.rendering.StateAwareTessellator; import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer; import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils; import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; +import net.coderbot.iris.Iris; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.gl.shader.ProgramCreator; import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPhase; +import net.coderbot.iris.shadows.ShadowRenderingState; +import net.coderbot.iris.uniforms.LocalGridFrame; import net.minecraft.block.Block; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockDynamicLiquid; @@ -21,6 +28,7 @@ import net.minecraft.block.BlockStaticLiquid; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess; +import org.joml.Matrix4f; import java.util.Map; @@ -36,6 +44,7 @@ public final class TerrainRendering { private static int terrainDrawDepth; private static boolean terrainDrawPushed; + private static int localGridId; private TerrainRendering() {} @@ -55,6 +64,8 @@ public final class TerrainRendering { public static void endTerrainDraw() { if (terrainDrawDepth == 0) return; + // While the terrain program is still bound, so it gets the real uniforms back + if (terrainDrawDepth == 1) endLocalGrid(); if (--terrainDrawDepth > 0) return; if (terrainDrawPushed) GbufferPrograms.popOverridePhase(); terrainDrawPushed = false; @@ -64,11 +75,54 @@ public final class TerrainRendering { public static void resetForFrame() { if (terrainDrawDepth == 0) return; AngelicaMod.LOGGER.warn("A terrain draw was never ended, ending it"); + LocalGridFrame.end(); if (terrainDrawPushed) GbufferPrograms.popOverridePhase(); terrainDrawPushed = false; terrainDrawDepth = 0; } + /** + * Call inside {@link #beginTerrainDraw}, in a try-with-resources. Until the grid is closed or the terrain draw + * ends, the pack sees the current modelview's model space as the world. For geometry drawn rotated or off the block + * grid: packs pick out parts of some blocks by where a pixel is inside its world block (cauldron water, end portal + * frame eyes), and off the grid that lands in the wrong spot. + *

+ * Only the uniforms a pack works out world space from change (camera, matrices, upPosition, eyePosition and the + * like), plus the pack's own custom uniforms made from them. View space and shadows come out the same. Model space + * up counts as up. Draws in between must use the modelview it was started with. + *

+ * Does nothing without a pack, in the shadow pass, on the SDL GPU backend, if a grid is already on or if the + * modelview can't be inverted. Packs that go by at_midBlock instead get it right from the vertex data alone, see + * {@link #getMidBlockAttributeLocation}. + * + * @return the grid, {@link LocalGrid#isActive} says whether it's on + */ + public static LocalGrid beginLocalGrid() { + if (!terrainDrawPushed || LocalGridFrame.isActive() || BackendManager.RENDER_BACKEND.isSDLGPU() + || ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + return LocalGrid.OFF; + } + final Matrix4f modelView = GLState.getModelViewMatrix(new Matrix4f()); + if (!LocalGridFrame.begin(modelView)) return LocalGrid.OFF; + refreshBoundUniforms(); + return new LocalGrid(++localGridId, modelView); + } + + private static void endLocalGrid() { + if (!LocalGridFrame.isActive()) return; + LocalGridFrame.end(); + refreshBoundUniforms(); + } + + // The camera and matrix uniforms are only worked out once a frame, so work them out again and push them to the + // terrain program (binding it first if it's still pending) + private static void refreshBoundUniforms() { + GLSMHooks.resolvePendingProgram(); + if (Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) { + drp.refreshUniforms(LocalGridFrame.UNIFORMS); + } + } + /** * True when the pack wants AO in the vertex color's alpha instead of multiplied into the color, so it can apply it * itself. Put the AO from {@link TerrainLighter} in alpha when this is set. @@ -196,6 +250,16 @@ public final class TerrainRendering { return ProgramCreator.AT_TANGENT; } + /** + * Vertex attribute location the pack's programs read at_midBlock from. Four bytes per vertex, not normalized: the + * offset from the vertex to the middle of its block times 64, then the block's light emission (0-15). Bake the + * offset in model space and packs that use it get blocks right even off the grid, no {@link #beginLocalGrid} + * needed. Only bind it while a shaderpack is in use. + */ + public static int getMidBlockAttributeLocation() { + return ProgramCreator.AT_MIDBLOCK; + } + /** * Angelica fills in mc_midTexCoord and at_tangent itself for client array draws out of a VBO, guessing from the * buffer layout, and binds that over whatever the draw set. Draws until {@link #endOwnExtendedAttributes} bring @@ -219,6 +283,39 @@ public final class TerrainRendering { return new SpriteCapture(AnimationsRenderUtils.captureSprites()); } + /** See {@link #beginLocalGrid}. */ + public static final class LocalGrid implements AutoCloseable { + + private static final LocalGrid OFF = new LocalGrid(0, null); + private static boolean warnedModelView; + + private final int id; + private final Matrix4f modelView; + + private LocalGrid(int id, Matrix4f modelView) { + this.id = id; + this.modelView = modelView; + } + + public boolean isActive() { + return id != 0 && id == localGridId && LocalGridFrame.isActive(); + } + + /** Ends it. Does nothing if it never started or the terrain draw already ended it. */ + @Override + public void close() { + if (!isActive()) return; + // The one rule callers can break without noticing. Only catches a modelview left changed, not one changed + // and put back, but that's cheap enough to always check + if (!warnedModelView && !GLState.getModelViewMatrix(new Matrix4f()).equals(modelView, 1e-4f)) { + warnedModelView = true; + AngelicaMod.LOGGER.warn("Modelview changed during a local grid, draws in it have to use the one it " + + "started with", new Throwable()); + } + endLocalGrid(); + } + } + /** See {@link #captureSprites}. */ public static final class SpriteCapture implements AutoCloseable { diff --git a/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java b/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java index 804cc7562..baedf1b47 100644 --- a/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java +++ b/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java @@ -30,6 +30,12 @@ public class SmoothFloat { private float cachedHalfLifeDown; private float cachedDecayDown; + // What the accumulator was at the start of this frame. Custom uniforms can be evaluated again mid-frame (see + // LocalGridFrame), and each of those calls has to smooth from the same point instead of stepping again. + private int frame = -1; + private float frameStartAccumulator; + private boolean frameStartHasInitialValue; + /** * Computes an exponential decay factor based on the given decay constant and time value * @@ -58,6 +64,16 @@ public class SmoothFloat { * Takes one value from the unsmoothed value sequence, and smooths it into our accumulator */ public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) { + final int now = SystemTimeUniforms.COUNTER.getAsInt(); + if (now != frame) { + frame = now; + frameStartAccumulator = accumulator; + frameStartHasInitialValue = hasInitialValue; + } else { + accumulator = frameStartAccumulator; + hasInitialValue = frameStartHasInitialValue; + } + if (halfLifeUp != cachedHalfLifeUp) { cachedHalfLifeUp = halfLifeUp; if (halfLifeUp == 0.0f) { diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 283fa2cc0..e8aeb2e64 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -967,6 +967,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return current; } + /** Evaluates these built-in uniforms again and pushes them to the bound pass, see LocalGridFrame. */ + public void refreshUniforms(String[] names) { + customUniforms.refreshInputs(names); + if (current != null && current.liveProgram != null + && GLSMPrograms.getActiveProgram() == current.liveProgram.getProgramId()) { + current.pushCustomUniforms(); + } + } + public int getActivePassProgramId() { if (current == null) return -1; final Program p = current.boundProgram(); @@ -1497,6 +1506,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } } + void pushCustomUniforms() { + DeferredWorldRenderingPipeline.this.customUniforms.push(liveProgram == program ? this : liveProgram); + } + private void bindSelected() { final Program selected = select(activeInstancing, GLSMRasterizer.clipEmulationActive()); liveProgram = selected; diff --git a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java b/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java index 829c6f690..6f70ce5da 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java @@ -29,6 +29,7 @@ public class CameraUniforms { public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) { final CameraPositionTracker tracker = new CameraPositionTracker(notifier); + LocalGridFrame.trackCamera(tracker); uniforms .uniform1f(ONCE, "near", () -> 0.05) diff --git a/src/main/java/net/coderbot/iris/uniforms/LocalGridFrame.java b/src/main/java/net/coderbot/iris/uniforms/LocalGridFrame.java new file mode 100644 index 000000000..965e2e25b --- /dev/null +++ b/src/main/java/net/coderbot/iris/uniforms/LocalGridFrame.java @@ -0,0 +1,260 @@ +package net.coderbot.iris.uniforms; + +import org.joml.Matrix3d; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector3d; +import org.joml.Vector3dc; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.joml.Vector3ic; +import org.joml.Vector4f; +import org.joml.Vector4fc; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.DoubleSupplier; +import java.util.function.DoubleUnaryOperator; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; + +/** + * Lets a draw's own model space stand in for the world's block grid, for geometry drawn rotated or off the grid + * (structures, previews). + *

+ * Packs pick out parts of some blocks by where a pixel is inside its world block, {@code fract(playerPos + + * cameraPosition)}, e.g. the water in a cauldron or the eye of an end portal frame. Off the grid that cuts through the + * block in the wrong place. While this is active the uniforms describe a world where the draw's model coordinates are + * world coordinates, moved by whole blocks to stay near the real position. View space, clip space and the shadow map + * come out exactly the same, so only what a pack works out in world space changes. + *

+ * Every uniform that changes is in the remap tables below, keyed by name. The custom uniform input holder wraps those + * suppliers when it's built (see the wrap methods), so the uniform classes themselves don't know about any of this. A + * new world space uniform only needs a line here. The uniforms are worked out once a frame, so starting or ending this + * works them out again and pushes them to the bound program, see {@link #UNIFORMS}. + */ +public final class LocalGridFrame { + + private static final Map> VEC3D = new HashMap<>(); + private static final Map> VEC3F = new HashMap<>(); + private static final Map> VEC3I = new HashMap<>(); + private static final Map> VEC4F = new HashMap<>(); + private static final Map> MATRIX = new HashMap<>(); + private static final Map DOUBLE = new HashMap<>(); + + /** Every uniform that changes under the frame. */ + public static final String[] UNIFORMS; + + private static boolean active; + private static CameraUniforms.CameraPositionTracker tracker; + + // Model to player space is T = V^-1 * M, linear part L and translation t. Everything below comes from that + private static final Matrix4f postfix = new Matrix4f(); + private static final Matrix4f postfixInverse = new Matrix4f(); + private static final Matrix3d linearInverse = new Matrix3d(); + private static final Vector3d eye = new Vector3d(); + private static final Vector3d modelCamera = new Vector3d(); + private static final Vector3d modelOrigin = new Vector3d(); + private static final Vector4f up = new Vector4f(); + + // What the remaps hand back. Like the suppliers they wrap (CameraUniforms and MatrixUniforms keep scratch objects + // too), a value is only good until the next remap runs. The cached uniforms in the input holder all copy it + // straight away, anything new that takes a wrapped supplier has to do the same + private static final Matrix4f scratch = new Matrix4f(); + private static final Vector3d current = new Vector3d(); + private static final Vector3d previous = new Vector3d(); + private static final Vector3d point = new Vector3d(); + private static final Vector3d offset = new Vector3d(); + private static final Vector3d direction = new Vector3d(); + private static final Vector3f offset3f = new Vector3f(); + private static final Vector4f offset4f = new Vector4f(); + + static { + // World positions. The shifted ones keep Iris's shift, the unshifted ones read the real camera directly + VEC3D.put("cameraPosition", LocalGridFrame::camera); + DOUBLE.put("eyeAltitude", y -> Math.rint(y + modelOrigin.y) + modelCamera.y); + VEC3D.put("previousCameraPosition", real -> tracker == null ? real + : previousCamera(tracker.getCurrentCameraPosition(), real)); + VEC3I.put("cameraPositionInt", real -> CameraUniforms.getCameraPositionInt(unshiftedCamera())); + VEC3F.put("cameraPositionFract", real -> CameraUniforms.getCameraPositionFract(unshiftedCamera())); + VEC3I.put("previousCameraPositionInt", real -> tracker == null ? real + : CameraUniforms.getCameraPositionInt(unshiftedPreviousCamera())); + VEC3F.put("previousCameraPositionFract", real -> tracker == null ? real + : CameraUniforms.getCameraPositionFract(unshiftedPreviousCamera())); + VEC3D.put("eyePosition", real -> worldPosition(CameraUniforms.getUnshiftedCameraPosition(), real)); + + // Offsets from the unshifted camera + VEC3D.put("relativeEyePosition", LocalGridFrame::offset); + VEC3D.put("relativeVehiclePosition", LocalGridFrame::offset); + // -256 on every axis means nothing is selected + VEC3F.put("currentSelectedBlockPos", real -> real.x() == -256.0f && real.y() == -256.0f && real.z() == -256.0f + ? real : offset3f.set(offset(point.set(real.x(), real.y(), real.z())))); + // w is 0 when there's no bolt + VEC4F.put("lightningBoltPosition", real -> { + if (real.w() == 0.0f) return real; + final Vector3d moved = offset(point.set(real.x(), real.y(), real.z())); + return offset4f.set((float) moved.x, (float) moved.y, (float) moved.z, real.w()); + }); + + // Directions in the world + VEC3D.put("playerLookVector", LocalGridFrame::direction); + VEC3D.put("playerBodyVector", LocalGridFrame::direction); + VEC3D.put("vehicleLookVector", LocalGridFrame::direction); + + // View space, so only up changes + VEC4F.put("upPosition", real -> up); + + // Matrices that take world space positions relative to the camera + MATRIX.put("gbufferModelView", LocalGridFrame::modelView); + MATRIX.put("gbufferPreviousModelView", LocalGridFrame::modelView); + MATRIX.put("shadowModelView", LocalGridFrame::modelView); + MATRIX.put("gbufferModelViewInverse", LocalGridFrame::modelViewInverse); + MATRIX.put("shadowModelViewInverse", LocalGridFrame::modelViewInverse); + + UNIFORMS = Stream.of(VEC3D, VEC3F, VEC3I, VEC4F, MATRIX, DOUBLE).flatMap(m -> m.keySet().stream()) + .toArray(String[]::new); + } + + private LocalGridFrame() {} + + public static boolean isActive() { + return active; + } + + /** The pipeline's camera tracker, for the uniforms that need the camera rather than their own value. */ + static void trackCamera(CameraUniforms.CameraPositionTracker cameraTracker) { + tracker = cameraTracker; + } + + /** + * @param drawModelView the modelview the geometry is drawn with + * @return false when it can't be done (a modelview that can't be inverted) + */ + public static boolean begin(Matrix4fc drawModelView) { + final Matrix4f view = new Matrix4f(MatrixUniforms.getGbufferModelView()); + final Matrix4f viewInverse = new Matrix4f(view).invert(); + final Matrix4f model = new Matrix4f(viewInverse).mul(drawModelView); + if (!Float.isFinite(model.determinant()) || Math.abs(model.determinant3x3()) < 1e-8f) return false; + + // The camera's eye in player space, and in model space + eye.set(viewInverse.m30(), viewInverse.m31(), viewInverse.m32()); + final Matrix3d linear = new Matrix3d(model.m00(), model.m01(), model.m02(), model.m10(), model.m11(), + model.m12(), model.m20(), model.m21(), model.m22()); + linearInverse.set(linear).invert(); + modelOrigin.set(model.m30(), model.m31(), model.m32()); + modelCamera.set(eye).sub(modelOrigin); + linearInverse.transform(modelCamera); + + // gbufferModelView' = V * translate(eye) * L, so V' * (p - camera) lands where M * p does + postfix.identity().translate((float) eye.x, (float) eye.y, (float) eye.z) + .mul(new Matrix4f().set3x3(model)); + postfix.invert(postfixInverse); + + // Model space up in view space, 100 long like the real upPosition + final Vector3f modelUp = model.transformDirection(new Vector3f(0, 1, 0)).normalize(100); + view.transformDirection(modelUp); + up.set(modelUp, 0); + + active = true; + return true; + } + + public static void end() { + active = false; + } + + // The wrap methods are for the custom uniform input holder, each hands back the supplier with the remap applied + // while the frame is active, or the same supplier if that uniform doesn't change + public static Supplier wrap3d(String name, Supplier real) { + return wrap(VEC3D.get(name), real); + } + + public static Supplier wrap3f(String name, Supplier real) { + return wrap(VEC3F.get(name), real); + } + + public static Supplier wrap3i(String name, Supplier real) { + return wrap(VEC3I.get(name), real); + } + + public static Supplier wrap4f(String name, Supplier real) { + return wrap(VEC4F.get(name), real); + } + + public static Supplier wrapMatrix(String name, Supplier real) { + return wrap(MATRIX.get(name), real); + } + + public static DoubleSupplier wrapDouble(String name, DoubleSupplier real) { + final DoubleUnaryOperator remap = DOUBLE.get(name); + if (remap == null) return real; + return () -> active ? remap.applyAsDouble(real.getAsDouble()) : real.getAsDouble(); + } + + private static Supplier wrap(UnaryOperator remap, Supplier real) { + if (remap == null) return real; + return () -> active ? remap.apply(real.get()) : real.get(); + } + + /** Where the model origin really is, rounded to whole blocks, so the frame's world stays near the real one. */ + private static Vector3d shift(Vector3dc realCamera, Vector3d dest) { + return dest.set( + Math.rint(realCamera.x() + modelOrigin.x), + Math.rint(realCamera.y() + modelOrigin.y), + Math.rint(realCamera.z() + modelOrigin.z)); + } + + /** cameraPosition (or its unshifted twin) for a real one. */ + private static Vector3d camera(Vector3d realCamera) { + return shift(realCamera, current).add(modelCamera); + } + + private static Vector3d unshiftedCamera() { + return camera(CameraUniforms.getUnshiftedCameraPosition()); + } + + private static Vector3d unshiftedPreviousCamera() { + final Vector3d realPrevious = tracker.getPreviousCameraPositionUnshifted(); + return previousCamera(CameraUniforms.getUnshiftedCameraPosition(), realPrevious); + } + + /** previousCameraPosition, from the camera's last step turned into model space. */ + private static Vector3d previousCamera(Vector3d realCamera, Vector3d realPrevious) { + previous.set(realCamera).sub(realPrevious); + linearInverse.transform(previous); + return previous.negate().add(camera(realCamera)); + } + + /** A real world position (eyePosition) moved into the frame's world, against the unshifted camera. */ + private static Vector3d worldPosition(Vector3dc realCamera, Vector3dc realPosition) { + point.set(realPosition).sub(realCamera).sub(modelOrigin); + linearInverse.transform(point); + return shift(realCamera, current).add(point); + } + + /** + * An offset from the unshifted camera (relativeEyePosition and co), as the same offset in the frame's world. Works + * out to {@link #worldPosition} minus the unshifted cameraPosition. + */ + private static Vector3d offset(Vector3d realOffset) { + return linearInverse.transform(offset.set(realOffset).sub(eye)); + } + + /** A world space direction turned into model space, same length. */ + private static Vector3d direction(Vector3d real) { + final double length = real.length(); + if (length == 0) return real; + return linearInverse.transform(direction.set(real)).normalize(length); + } + + /** gbufferModelView, gbufferPreviousModelView or shadowModelView for a real one. */ + private static Matrix4fc modelView(Matrix4fc real) { + return scratch.set(real).mul(postfix); + } + + /** Their inverses, (R * P)^-1 = P^-1 * R^-1 for the real inverse. */ + private static Matrix4fc modelViewInverse(Matrix4fc realInverse) { + return scratch.set(postfixInverse).mul(realInverse); + } +} diff --git a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java index a5a8b9616..4071c0584 100644 --- a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java @@ -22,7 +22,7 @@ public final class MatrixUniforms { } private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f(); - private static Matrix4fc getGbufferModelView() { + static Matrix4fc getGbufferModelView() { final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix(); final Entity view = Minecraft.getMinecraft().renderViewEntity; if (view == null) { diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java index b374d5460..01cb94c12 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java +++ b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java @@ -8,6 +8,7 @@ import net.coderbot.iris.gl.uniform.FloatSupplier; import net.coderbot.iris.gl.uniform.UniformHolder; import com.gtnewhorizons.angelica.glsm.shader.UniformType; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.coderbot.iris.uniforms.LocalGridFrame; import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform; import net.coderbot.iris.uniforms.custom.cached.CachedUniform; import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform; @@ -94,7 +95,8 @@ public class CustomUniformFixedInputUniformsHolder { @Override public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) { - return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) value.getAsDouble())); + final DoubleSupplier wrapped = LocalGridFrame.wrapDouble(name, value); + return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) wrapped.getAsDouble())); } @Override @@ -119,11 +121,13 @@ public class CustomUniformFixedInputUniformsHolder { @Override public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier value) { + value = LocalGridFrame.wrap3f(name, value); return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value)); } @Override public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier value) { + value = LocalGridFrame.wrap3i(name, value); return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value)); } @@ -134,9 +138,10 @@ public class CustomUniformFixedInputUniformsHolder { @Override public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier value) { + final Supplier wrapped = LocalGridFrame.wrap4f(name, value); Vector3f held = new Vector3f(); return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> { - final Vector4fc vec = value.get(); + final Vector4fc vec = wrapped.get(); held.set(vec.x(), vec.y(), vec.z()); return held; })); @@ -144,9 +149,10 @@ public class CustomUniformFixedInputUniformsHolder { @Override public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier value) { + final Supplier wrapped = LocalGridFrame.wrap3d(name, value); Vector3f held = new Vector3f(); return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> { - Vector3d vec = value.get(); + Vector3d vec = wrapped.get(); held.set(vec.x(), vec.y(), vec.z()); return held; })); @@ -154,9 +160,10 @@ public class CustomUniformFixedInputUniformsHolder { @Override public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier value) { + final Supplier wrapped = LocalGridFrame.wrap4f(name, value); Vector4f held = new Vector4f(); return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> { - final Vector4fc vec = value.get(); + final Vector4fc vec = wrapped.get(); held.set(vec.x(), vec.y(), vec.z(), vec.w()); return held; })); @@ -175,6 +182,7 @@ public class CustomUniformFixedInputUniformsHolder { @Override public UniformHolder uniformMatrix( UniformUpdateFrequency updateFrequency, String name, Supplier value) { + value = LocalGridFrame.wrapMatrix(name, value); return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value)); } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java index ca649bd33..2e538bf36 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java @@ -48,6 +48,9 @@ public class CustomUniforms implements FunctionContext { private final Object2LongOpenHashMap lastPushedGen = new Object2LongOpenHashMap<>(); private long generation; + private String[] refreshNames; + private CachedUniform[] refreshOrder; + private static final long PLOT_CUSTOM_PUSHED = Tracy.ENABLED ? Tracy.plotHandle("iris.customPushed") : 0; private static final long PLOT_CUSTOM_SKIPPED = Tracy.ENABLED ? Tracy.plotHandle("iris.customSkipped") : 0; private int pushedThisFrame; @@ -254,6 +257,41 @@ public class CustomUniforms implements FunctionContext { } } + /** + * Evaluates these built-in uniforms again mid-frame, along with every custom uniform made from them, so the next + * push picks them up (see LocalGridFrame). + */ + public void refreshInputs(String[] names) { + if (names != refreshNames) { + refreshNames = names; + refreshOrder = readersInOrder(names); + } + for (CachedUniform uniform : refreshOrder) { + uniform.update(); + } + generation++; + } + + // The named inputs that are still used and every custom uniform that reads them, directly or not, in the order + // they're evaluated. uniformOrder is already sorted so each uniform comes after what it reads. + private CachedUniform[] readersInOrder(String[] names) { + final Set affected = new ObjectOpenHashSet<>(); + for (String name : names) { + final CachedUniform uniform = this.inputHolder.getUniform(name); + if (uniform != null) affected.add(uniform); + } + final List ordered = new ObjectArrayList<>(); + for (CachedUniform uniform : this.uniformOrder) { + if (!affected.contains(uniform)) { + final List dependencies = this.dependsOn.get(uniform); + if (dependencies == null || dependencies.stream().noneMatch(affected::contains)) continue; + affected.add(uniform); + } + ordered.add(uniform); + } + return ordered.toArray(new CachedUniform[0]); + } + public void push(Object pass) { final PassUniforms pu = this.locationMap.get(pass); if (pu == null) return;