Support for custom uniforms (#902)

* wip backport of custom uniforms

* Functioning custom uniforms maybe?

* Workon separating dynamic/non-dynamic uniforms and making variables available to custom uniforms (currently the JVM dies horribly)

* wip

* It no longer crashes horrifically

* star imports
This commit is contained in:
Darren Eberly authored and GitHub committed 2025-03-18 10:04:31 -07:00
1 parent 6fa973dbc8
commit bed724ba59
89 files changed
+4622 -266

No files matched your search

@@ -57,12 +57,15 @@ public final class ComputeProgram extends GlResource {
return cachedWorkGroups;
}
public void dispatch(float width, float height) {
GL20.glUseProgram(getGlId());
uniforms.update();
samplers.update();
images.update();
public void use() {
GL20.glUseProgram(getGlId());
uniforms.update();
samplers.update();
images.update();
}
public void dispatch(float width, float height) {
if (!Iris.getPipelineManager().getPipeline().map(WorldRenderingPipeline::allowConcurrentCompute).orElse(false)) {
RenderSystem.memoryBarrier(40);
}
@@ -10,6 +10,8 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.function.Supplier;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder;
@@ -20,6 +22,7 @@ import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import org.joml.Vector3i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderImageLoadStore;
import org.lwjgl.opengl.GL11;
@@ -172,8 +175,7 @@ public class ProgramUniforms {
return OptionalInt.empty();
}
// TODO: Temporary hack until custom uniforms are merged.
if ((!locations.containsKey(id) && !uniformNames.containsKey(name)) || name.equals("framemod8")) {
if ((!locations.containsKey(id) && !uniformNames.containsKey(name))) {
locations.put(id, name);
uniformNames.put(name, type);
} else {
@@ -240,12 +242,6 @@ public class ProgramUniforms {
continue;
}
// TODO: This is an absolutely horrific hack, but is needed until custom uniforms work.
if ("framemod8".equals(name) && expected == UniformType.FLOAT && provided == UniformType.INT) {
SystemTimeUniforms.addFloatFrameMod8Uniform(this);
provided = UniformType.FLOAT;
}
if (provided != null && provided != expected) {
String expectedName;
@@ -283,7 +279,7 @@ public class ProgramUniforms {
return this;
}
@Override
@Override
public UniformHolder externallyManagedUniform(String name, UniformType type) {
externalUniformNames.put(name, type);
@@ -2,6 +2,7 @@ package net.coderbot.iris.gl.uniform;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import org.joml.Vector2i;
import org.joml.Vector3i;
import org.joml.Vector4f;
import org.joml.Vector4i;
@@ -42,12 +43,23 @@ public interface DynamicLocationalUniformHolder extends LocationalUniformHolder,
return this;
}
default DynamicUniformHolder uniform3i(String name, Supplier<Vector3i> value, ValueUpdateNotifier notifier) {
location(name, UniformType.VEC3I).ifPresent(id -> addDynamicUniform(new Vector3IntegerJomlUniform(id, value, notifier), notifier));
return this;
}
default DynamicUniformHolder uniform4f(String name, Supplier<Vector4f> value, ValueUpdateNotifier notifier) {
location(name, UniformType.VEC4).ifPresent(id -> addDynamicUniform(new Vector4Uniform(id, value, notifier), notifier));
return this;
}
default DynamicUniformHolder uniform4fArray(String name, Supplier<float[]> value, ValueUpdateNotifier notifier) {
location(name, UniformType.VEC4).ifPresent(id -> addDynamicUniform(new Vector4ArrayUniform(id, value, notifier), notifier));
return this;
}
default DynamicUniformHolder uniform4i(String name, Supplier<Vector4i> value, ValueUpdateNotifier notifier) {
location(name, UniformType.VEC4I).ifPresent(id -> addDynamicUniform(new Vector4IntegerJomlUniform(id, value, notifier), notifier));
@@ -2,6 +2,7 @@ package net.coderbot.iris.gl.uniform;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import org.joml.Vector2i;
import org.joml.Vector3i;
import org.joml.Vector4f;
import org.joml.Vector4i;
@@ -15,6 +16,8 @@ public interface DynamicUniformHolder extends UniformHolder {
DynamicUniformHolder uniform1f(String name, DoubleSupplier value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform1i(String name, IntSupplier value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform2i(String name, Supplier<Vector2i> value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform3i(String name, Supplier<Vector3i> value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform4f(String name, Supplier<Vector4f> value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform4fArray(String name, Supplier<float[]> value, ValueUpdateNotifier notifier);
DynamicUniformHolder uniform4i(String name, Supplier<Vector4i> value, ValueUpdateNotifier notifier);
}
@@ -6,6 +6,7 @@ import org.joml.Vector2f;
import org.joml.Vector2i;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import java.util.OptionalInt;
@@ -75,6 +76,13 @@ public interface LocationalUniformHolder extends UniformHolder {
return this;
}
@Override
default LocationalUniformHolder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3i> value) {
location(name, UniformType.VEC3I).ifPresent(id -> addUniform(updateFrequency, new Vector3IntegerJomlUniform(id, value)));
return this;
}
@Override
default LocationalUniformHolder uniformVanilla3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vec3> value) {
location(name, UniformType.VEC3).ifPresent(id -> addUniform(updateFrequency, new VanillaVector3Uniform(id, value)));
@@ -103,6 +111,13 @@ public interface LocationalUniformHolder extends UniformHolder {
return this;
}
@Override
default LocationalUniformHolder uniform4fArray(UniformUpdateFrequency updateFrequency, String name, Supplier<float[]> value) {
location(name, UniformType.VEC4).ifPresent(id -> addUniform(updateFrequency, new Vector4ArrayUniform(id, value)));
return this;
}
@Override
default LocationalUniformHolder uniformMatrix(UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4f> value) {
location(name, UniformType.MAT4).ifPresent(id -> addUniform(updateFrequency, new MatrixUniform(id, value)));
@@ -6,6 +6,7 @@ import org.joml.Vector2f;
import org.joml.Vector2i;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import java.util.function.BooleanSupplier;
@@ -30,6 +31,8 @@ public interface UniformHolder {
UniformHolder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3f> value);
UniformHolder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3i> value);
UniformHolder uniformVanilla3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vec3> value);
UniformHolder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4f> value);
@@ -38,6 +41,8 @@ public interface UniformHolder {
UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4f> value);
UniformHolder uniform4fArray(UniformUpdateFrequency updateFrequency, String name, Supplier<float[]> value);
UniformHolder uniformMatrix(UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4f> value);
UniformHolder uniformMatrixFromArray(UniformUpdateFrequency updateFrequency, String name, Supplier<float[]> value);
@@ -7,6 +7,7 @@ public enum UniformType {
VEC2,
VEC2I,
VEC3,
VEC3I,
VEC4,
VEC4I
}
@@ -3,5 +3,6 @@ package net.coderbot.iris.gl.uniform;
public enum UniformUpdateFrequency {
ONCE,
PER_TICK,
PER_FRAME
PER_FRAME,
CUSTOM
}
@@ -0,0 +1,41 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import org.joml.Vector3i;
import java.util.function.Supplier;
public class Vector3IntegerJomlUniform extends Uniform {
private Vector3i cachedValue;
private final Supplier<Vector3i> value;
Vector3IntegerJomlUniform(int location, Supplier<Vector3i> value) {
this(location, value, null);
}
Vector3IntegerJomlUniform(int location, Supplier<Vector3i> value, ValueUpdateNotifier notifier) {
super(location, notifier);
this.cachedValue = null;
this.value = value;
}
@Override
public void update() {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
}
}
private void updateValue() {
Vector3i newValue = value.get();
if (cachedValue == null || !newValue.equals(cachedValue)) {
cachedValue = newValue;
RenderSystem.uniform3i(this.location, newValue.x, newValue.y, newValue.z);
}
}
}
@@ -0,0 +1,41 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import java.util.Arrays;
import java.util.function.Supplier;
public class Vector4ArrayUniform extends Uniform {
private final Supplier<float[]> value;
private float[] cachedValue;
Vector4ArrayUniform(int location, Supplier<float[]> value) {
this(location, value, null);
}
Vector4ArrayUniform(int location, Supplier<float[]> value, ValueUpdateNotifier notifier) {
super(location, notifier);
this.cachedValue = new float[4];
this.value = value;
}
@Override
public void update() {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
}
}
private void updateValue() {
float[] newValue = value.get();
if (!Arrays.equals(newValue, cachedValue)) {
cachedValue = newValue;
RenderSystem.uniform4f(location, cachedValue[0], cachedValue[1], cachedValue[2], cachedValue[3]);
}
}
}
@@ -0,0 +1,25 @@
package net.coderbot.iris.parsing;
public enum BiomeCategories {
NONE,
TAIGA,
EXTREME_HILLS,
JUNGLE,
MESA,
PLAINS,
SAVANNA,
ICY,
THE_END,
BEACH,
FOREST,
OCEAN,
DESERT,
RIVER,
SWAMP,
MUSHROOM,
NETHER,
// TODO: This is in Optifine, but undocumented...
MOUNTAIN,
UNDERGROUND
}
@@ -0,0 +1,81 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import kroppeb.stareval.function.TypedFunction;
import java.util.Collection;
public class BooleanVectorizedFunction implements TypedFunction {
final TypedFunction inner;
final int size;
final Parameter[] parameters;
private final ElementAccessExpression[] vectorAccessors;
private int index;
public BooleanVectorizedFunction(TypedFunction inner, int size) {
this.inner = inner;
this.size = size;
Parameter[] innerTypes = inner.getParameters();
this.parameters = new Parameter[innerTypes.length];
this.vectorAccessors = new ElementAccessExpression[innerTypes.length];
for (int i = 0; i < innerTypes.length; i++) {
this.parameters[i] = new Parameter(VectorType.of((Type.Primitive) innerTypes[i].type(), size));
this.vectorAccessors[i] = new ElementAccessExpression(innerTypes[i].type());
}
}
@Override
public Type getReturnType() {
return Type.Boolean;
}
@Override
public Parameter[] getParameters() {
return this.parameters;
}
@Override
public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
for (int p = 0; p < params.length; p++) {
final Expression param = params[p];
param.evaluateTo(context, functionReturn);
this.vectorAccessors[p].vector = functionReturn.objectReturn;
}
for (int i = 0; i < this.size; i++) {
this.index = i;
this.inner.evaluateTo(this.vectorAccessors, context, functionReturn);
if (!functionReturn.booleanReturn)
return; // if false -> return false
}
// if all true (and thus the last one was true) -> return true
}
class ElementAccessExpression implements Expression {
final Type parameterType;
Object vector;
ElementAccessExpression(Type parameterType) {
this.parameterType = parameterType;
}
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
parameterType.getValueFromArray(vector, index, functionReturn);
}
@Override
public void listVariables(Collection<? super VariableExpression> variables) {
throw new IllegalStateException();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,53 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.parser.BinaryOp;
import kroppeb.stareval.parser.ParserOptions;
import kroppeb.stareval.parser.UnaryOp;
public class IrisOptions {
public static final ParserOptions options;
static final BinaryOp Multiply = new BinaryOp("multiply", 0);
static final BinaryOp Divide = new BinaryOp("divide", 0);
static final BinaryOp Remainder = new BinaryOp("remainder", 0);
static final BinaryOp Add = new BinaryOp("add", 1);
static final BinaryOp Subtract = new BinaryOp("subtract", 1);
static final BinaryOp Equals = new BinaryOp("equals", 2);
static final BinaryOp NotEquals = new BinaryOp("notEquals", 2);
static final BinaryOp LessThan = new BinaryOp("lessThan", 2);
static final BinaryOp MoreThan = new BinaryOp("moreThan", 2);
static final BinaryOp LessThanOrEquals = new BinaryOp("lessThanOrEquals", 2);
static final BinaryOp MoreThanOrEquals = new BinaryOp("moreThanOrEquals", 2);
static final BinaryOp And = new BinaryOp("and", 3);
static final BinaryOp Or = new BinaryOp("or", 3);
static final UnaryOp Not = new UnaryOp("not");
static final UnaryOp Negate = new UnaryOp("negate");
static {
final ParserOptions.Builder builder = new ParserOptions.Builder();
builder.addBinaryOp("*", Multiply);
builder.addBinaryOp("/", Divide);
builder.addBinaryOp("%", Remainder);
builder.addBinaryOp("+", Add);
builder.addBinaryOp("-", Subtract);
builder.addBinaryOp("==", Equals);
builder.addBinaryOp("!=", NotEquals);
builder.addBinaryOp("<", LessThan);
builder.addBinaryOp(">", MoreThan);
builder.addBinaryOp("<=", LessThanOrEquals);
builder.addBinaryOp(">=", MoreThanOrEquals);
builder.addBinaryOp("≠", NotEquals);
builder.addBinaryOp("≤", LessThanOrEquals);
builder.addBinaryOp("≥", MoreThanOrEquals);
builder.addBinaryOp("&&", And);
builder.addBinaryOp("||", Or);
builder.addUnaryOp("!", Not);
builder.addUnaryOp("-", Negate);
options = builder.build();
}
}
@@ -0,0 +1,24 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.function.Type;
import org.joml.Matrix2f;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import java.util.function.Supplier;
public class MatrixType<T> extends Type.ObjectType {
public static final MatrixType<Matrix4f> MAT4 = new MatrixType<>("mat4", Matrix4f::new);
public static MatrixType<Matrix2f> MAT2 = new MatrixType<>("mat2", Matrix2f::new);
public static MatrixType<Matrix3f> MAT3 = new MatrixType<>("mat3", Matrix3f::new);
final String name;
public MatrixType(String name, Supplier<T> supplier) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
@@ -0,0 +1,121 @@
package net.coderbot.iris.parsing;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
/**
* An implementation of basic exponential smoothing that converts a sequence of unsmoothed values into a sequence of
* smoothed values.
*
* @see <a href="https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_(simple)_exponential_smoothing_(Holt_linear)">
* Wikipedia: Basic (simple) exponential smoothing (Holt linear)</a>
*/
public class SmoothFloat {
/**
* Natural logarithm of 2, ie. {@code ln(2)}
*/
private static final double LN_OF_2 = Math.log(2.0);
/**
* An accumulator for smoothed values.
*/
private float accumulator;
/**
* Tracks whether an initial value has already been generated, because otherwise there will be nothing to smooth
* with.
*/
private boolean hasInitialValue;
private float cachedHalfLifeUp;
private float cachedDecayUp;
private float cachedHalfLifeDown;
private float cachedDecayDown;
/**
* Computes an exponential decay factor based on the given decay constant and time value
*
* @param k the decay constant, derived from the half life
* @param t the time that has passed since the decay started
*/
private static float exponentialDecayFactor(float k, float t) {
// https://en.wikipedia.org/wiki/Exponential_decay
// e^(-kt)
return (float) Math.exp(-k * t);
}
/**
* Computes a linearly interpolated value between v0 and v1
*
* @param v0 the starting value (t = 0)
* @param v1 the ending value (t = 1)
* @param t the time/progress value - should be in the range of 0.0 to 1.0
*/
private static float lerp(float v0, float v1, float t) {
// https://en.wikipedia.org/wiki/Linear_interpolation
return (1 - t) * v0 + t * v1;
}
/**
* Takes one value from the unsmoothed value sequence, and smooths it into our accumulator
*/
public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) {
if (halfLifeUp != cachedHalfLifeUp) {
cachedHalfLifeUp = halfLifeUp;
if (halfLifeUp == 0.0f) {
cachedDecayUp = 0;
} else {
cachedDecayUp = computeDecay(halfLifeUp * 0.1F);
}
}
if (halfLifeDown != cachedHalfLifeDown) {
cachedHalfLifeDown = halfLifeDown;
if (halfLifeDown == 0.0f) {
cachedDecayDown = 0;
} else {
cachedDecayDown = computeDecay(halfLifeDown * 0.1F);
}
}
if (!hasInitialValue) {
// There is no smoothing on the first value.
// This is not an optimal approach to choosing the initial value:
// https://en.wikipedia.org/wiki/Exponential_smoothing#Choosing_the_initial_smoothed_value
//
// However, it works well enough for now.
accumulator = value;
hasInitialValue = true;
return accumulator;
}
// Implements the basic variant of exponential smoothing
// https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_(simple)_exponential_smoothing_(Holt_linear)
// 𝚫t
float lastFrameTime = SystemTimeUniforms.TIMER.getLastFrameTime();
float decay = value > this.accumulator ? cachedDecayUp : cachedDecayDown;
if (decay == 0.0f) {
accumulator = value;
return accumulator;
}
// Compute the smoothing factor based on our
// α = 1 - e^(-𝚫t/τ) = 1 - e^(-k𝚫t)
float smoothingFactor = 1.0f - exponentialDecayFactor(decay, lastFrameTime);
// sₜ = αxₜ + (1 - α)sₜ₋₁
accumulator = lerp(accumulator, value, smoothingFactor);
return accumulator;
}
private float computeDecay(float halfLife) {
// Compute the decay constant from the half life
// https://en.wikipedia.org/wiki/Exponential_decay#Measuring_rates_of_decay
// https://en.wikipedia.org/wiki/Exponential_smoothing#Time_constant
// k = 1 / τ
return (float) (1.0f / (halfLife / LN_OF_2));
}
}
@@ -0,0 +1,32 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.Util;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.function.AbstractTypedFunction;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import java.util.Arrays;
public class VectorConstructor extends AbstractTypedFunction {
public VectorConstructor(Type inner, int size) {
super(
new VectorType.ArrayVector(inner, size),
Util.make(new Type[size], params -> Arrays.fill(params, inner))
);
}
@Override
public VectorType.ArrayVector getReturnType() {
return (VectorType.ArrayVector) super.getReturnType();
}
@Override
public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn
functionReturn) {
VectorType.ArrayVector vectorType = this.getReturnType();
vectorType.map(params, context, functionReturn, (i, p, ctx, fr) -> p[i].evaluateTo(ctx, fr));
}
}
@@ -0,0 +1,125 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import org.joml.Vector2f;
import org.joml.Vector2i;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import org.joml.Vector4i;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
abstract public class VectorType extends Type.ObjectType {
public static final JOMLVector<Vector2f> VEC2 = new JOMLVector<>("vec2", Vector2f::new);
public static final JOMLVector<Vector3f> VEC3 = new JOMLVector<>("vec3", Vector3f::new);
public static final JOMLVector<Vector4f> VEC4 = new JOMLVector<>("vec4", Vector4f::new);
public static final JOMLVector<Vector2i> I_VEC2 = new JOMLVector<>("ivec2", Vector2i::new);
public static final JOMLVector<Vector3i> I_VEC3 = new JOMLVector<>("ivec3", Vector3i::new);
public static final JOMLVector<Vector4i> I_VEC4 = new JOMLVector<>("ivec4", Vector4i::new);
public static final VectorType B_VEC2 = new ArrayVector(Type.Boolean, 2);
public static final VectorType B_VEC3 = new ArrayVector(Type.Boolean, 3);
public static final VectorType B_VEC4 = new ArrayVector(Type.Boolean, 4);
public static final ArrayVector[] AllArrayVectorTypes = Stream.of(Type.Int, Type.Boolean)
.flatMap(type ->
IntStream
.rangeClosed(2, 4)
.mapToObj(i -> new ArrayVector(type, i))
).toArray(ArrayVector[]::new);
public static final VectorType[] AllVectorTypes = Arrays.stream(Type.AllPrimitives)
.flatMap(type ->
IntStream
.rangeClosed(2, 4)
.mapToObj(i -> VectorType.of(type, i))
).toArray(VectorType[]::new);
public static VectorType of(Type.Primitive primitive, int size) {
if (primitive.equals(Type.Float)) {
return switch (size) {
case 2 -> VEC2;
case 3 -> VEC3;
case 4 -> VEC4;
default -> throw new IllegalArgumentException("not a valid vector");
};
} else {
return new ArrayVector(primitive, size);
}
}
public static class ArrayVector extends VectorType {
private final Type inner;
private final int size;
public ArrayVector(Type inner, int size) {
this.inner = inner;
this.size = size;
}
public Object createObject() {
return this.inner.createArray(this.size);
}
public void setValue(Object vector, int index, FunctionReturn functionReturn) {
this.inner.setValueFromReturn(vector, index, functionReturn);
}
public void getValue(Object vector, int index, FunctionReturn functionReturn) {
this.inner.getValueFromArray(vector, index, functionReturn);
}
public <T1, T2> void map(T1 item1, T2 item2, FunctionReturn functionReturn, IntObjectObjectObjectConsumer<T1, T2, FunctionReturn> mapper) {
Object array = this.createObject();
for (int i = 0; i < this.size; i++) {
mapper.accept(i, item1, item2, functionReturn);
this.setValue(array, i, functionReturn);
}
functionReturn.objectReturn = array;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ArrayVector that)) return false;
return size == that.size && inner.equals(that.inner);
}
@Override
public int hashCode() {
return Objects.hash(inner, size);
}
@Override
public String toString() {
String base = this.inner.equals(Type.Float) ? "" : this.inner.toString().substring(0, 1);
return "__" + base + "vec" + this.size;
}
public interface IntObjectObjectObjectConsumer<TB, TC, TD> {
void accept(int a, TB b, TC c, TD d);
}
}
public static class JOMLVector<T> extends VectorType {
private final String name;
private final Supplier<T> supplier;
public JOMLVector(String name, Supplier<T> supplier) {
this.name = name;
this.supplier = supplier;
}
@Override
public String toString() {
return this.name;
}
public T create() {
return this.supplier.get();
}
}
}
@@ -0,0 +1,83 @@
package net.coderbot.iris.parsing;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import kroppeb.stareval.function.TypedFunction;
import java.util.Collection;
public class VectorizedFunction implements TypedFunction {
final TypedFunction inner;
final int size;
final VectorType.ArrayVector returnType;
final Parameter[] parameters;
private final ElementAccessExpression[] vectorAccessors;
private int index;
private final VectorType.ArrayVector.IntObjectObjectObjectConsumer<VectorizedFunction, FunctionContext, FunctionReturn> mapper =
(i, self, ctx, fr) -> {
self.index = i;
self.inner.evaluateTo(self.vectorAccessors, ctx, fr);
};
public VectorizedFunction(TypedFunction inner, int size) {
this.inner = inner;
this.size = size;
this.returnType = new VectorType.ArrayVector(inner.getReturnType(), size);
Parameter[] innerTypes = inner.getParameters();
this.parameters = new Parameter[innerTypes.length];
this.vectorAccessors = new ElementAccessExpression[innerTypes.length];
for (int i = 0; i < innerTypes.length; i++) {
this.parameters[i] = new Parameter(new VectorType.ArrayVector(innerTypes[i].type(), size));
this.vectorAccessors[i] = new ElementAccessExpression(innerTypes[i].type());
}
}
@Override
public Type getReturnType() {
return this.returnType;
}
@Override
public Parameter[] getParameters() {
return this.parameters;
}
@Override
public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
for (int p = 0; p < params.length; p++) {
final Expression param = params[p];
param.evaluateTo(context, functionReturn);
this.vectorAccessors[p].vector = functionReturn.objectReturn;
}
returnType.map(this, context, functionReturn, this.mapper);
}
class ElementAccessExpression implements Expression {
final Type parameterType;
Object vector;
ElementAccessExpression(Type parameterType) {
this.parameterType = parameterType;
}
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
parameterType.getValueFromArray(vector, index, functionReturn);
}
@Override
public void listVariables(Collection<? super VariableExpression> variables) {
throw new IllegalStateException();
}
}
}
@@ -57,6 +57,7 @@ import net.coderbot.iris.texture.pbr.PBRTextureManager;
import net.coderbot.iris.texture.pbr.PBRType;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
@@ -109,6 +110,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Nullable
private final ShadowRenderer shadowRenderer;
private final CustomUniforms customUniforms;
private final int shadowMapResolution;
private final CompositeRenderer deferredRenderer;
private final CompositeRenderer compositeRenderer;
@@ -195,6 +198,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
forcedShadowRenderDistanceChunks = OptionalInt.empty();
}
this.customUniforms = programs.getPack().customUniforms.build(
holder -> CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), this.updateNotifier)
);
// TODO: BlockStateIdMap
BlockRenderingSettings.INSTANCE.setBlockMatches(BlockMaterialMapping.createBlockStateIdMap(programs.getPack().getIdMap().getBlockProperties()));
BlockRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programs.getPack().getIdMap().getBlockRenderTypeMap()));
@@ -235,25 +242,25 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.prepareRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getPrepare(), programs.getPrepareCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE),
programs.getPackDirectives().getExplicitFlips("prepare_pre"));
programs.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms);
flippedAfterPrepare = flipper.snapshot();
this.deferredRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getDeferred(), programs.getDeferredCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED),
programs.getPackDirectives().getExplicitFlips("deferred_pre"));
programs.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms);
flippedAfterTranslucent = flipper.snapshot();
this.compositeRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getComposite(), programs.getCompositeCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL),
programs.getPackDirectives().getExplicitFlips("composite_pre"));
programs.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms);
this.finalPassRenderer = new FinalPassRenderer(programs, renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, flipper.snapshot(),
centerDepthSampler, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL),
this.compositeRenderer.getFlippedAtLeastOnceFinal());
this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms);
// [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)]
ProgramId[] ids = new ProgramId[] {
@@ -285,7 +292,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
Map<Pair<ProgramId, InputAvailability>, Pass> cachedPasses = new HashMap<>();
this.shadowComputes = createShadowComputes(programs.getShadowCompute(), programs);
this.shadowComputes = createShadowComputes(programs.getShadowCompute());
this.table = new ProgramTable<>((condition, availability) -> {
int idx;
@@ -355,6 +362,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shadowRenderer = null;
}
this.customUniforms.optimise();
this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, programs.getPackDirectives().getRenderTargetDirectives());
this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, programs.getPackDirectives().getRenderTargetDirectives());
@@ -418,7 +427,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
};
this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers,
shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages,
shadowRenderer == null ? null : createShadowTerrainImages);
shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms);
}
private RenderTargets getRenderTargets() {
@@ -598,13 +607,13 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
return createPassInner(builder, source.getParent().getPack().getIdMap(), source.getDirectives(), source.getParent().getPackDirectives(), availability, shadow, id);
return createPassInner(builder, source.getDirectives(), availability, shadow, id);
}
private Pass createPassInner(ProgramBuilder builder, IdMap map, ProgramDirectives programDirectives,
PackDirectives packDirectives, InputAvailability availability, boolean shadow, ProgramId id) {
private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) {
CommonUniforms.addCommonUniforms(builder, map, packDirectives, updateNotifier);
CommonUniforms.addDynamicUniforms(builder);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -674,8 +683,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
});
return new Pass(builder.build(), framebufferBeforeTranslucents, framebufferAfterTranslucents, alphaTestOverride,
programDirectives.getBlendModeOverride().orElse(id.getBlendModeOverride()), bufferOverrides, shadow);
Pass pass = new Pass(builder.build(), framebufferBeforeTranslucents, framebufferAfterTranslucents, alphaTestOverride,
programDirectives.getBlendModeOverride().orElse(id.getBlendModeOverride()), bufferOverrides, shadow);
this.customUniforms.mapholderToPass(builder, pass);
return pass;
}
private boolean isPostChain;
@@ -751,6 +764,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
program.use();
}
DeferredWorldRenderingPipeline.this.customUniforms.push(this);
if (alphaTestOverride != null) {
alphaTestOverride.apply();
} else {
@@ -875,6 +890,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
for (ComputeProgram computeProgram : shadowComputes) {
if (computeProgram != null) {
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(shadowMapResolution, shadowMapResolution);
}
}
@@ -937,7 +954,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true);
}
private ComputeProgram[] createShadowComputes(ComputeSource[] compute, ProgramSet programSet) {
private ComputeProgram[] createShadowComputes(ComputeSource[] compute) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
for (int i = 0; i < programs.length; i++) {
ComputeSource source = compute[i];
@@ -953,7 +970,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
throw new RuntimeException("Shader compilation failed!", e);
}
CommonUniforms.addCommonUniforms(builder, programSet.getPack().getIdMap(), programSet.getPackDirectives(), updateNotifier);
CommonUniforms.addDynamicUniforms(builder);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -980,6 +998,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups());
}
}
@@ -1099,6 +1119,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
updateNotifier.onNewFrame();
this.customUniforms.update();
// Get ready for world rendering
prepareRenderTargets();
@@ -1,5 +1,6 @@
package net.coderbot.iris.pipeline;
import lombok.Getter;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
@@ -9,6 +10,7 @@ import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import java.util.Map;
import java.util.Objects;
@@ -28,6 +30,9 @@ public class SodiumTerrainPipeline {
//GlFramebuffer framebuffer;
ProgramSet programSet;
@Getter
private final CustomUniforms customUniforms;
private final WorldRenderingPipeline parent;
private final IntFunction<ProgramSamplers> createTerrainSamplers;
@@ -40,7 +45,7 @@ public class SodiumTerrainPipeline {
ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers,
IntFunction<ProgramSamplers> createShadowSamplers,
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages) {
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms) {
this.parent = Objects.requireNonNull(parent);
Optional<ProgramSource> terrainSource = first(programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic());
@@ -49,6 +54,8 @@ public class SodiumTerrainPipeline {
this.programSet = programSet;
this.customUniforms = customUniforms;
terrainSource.ifPresent(sources -> {
Map<PatchShaderType, String> result = TransformPatcher.patchSodiumTerrain(
sources.getVertexSource().orElse(null),
@@ -130,13 +137,14 @@ public class SodiumTerrainPipeline {
return shadowFragment;
}
public ProgramUniforms initUniforms(int programId) {
public ProgramUniforms.Builder initUniforms(int programId) {
ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<sodium shaders>", programId);
CommonUniforms.addCommonUniforms(uniforms, programSet.getPack().getIdMap(), programSet.getPackDirectives(), parent.getFrameUpdateNotifier());
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
CommonUniforms.addDynamicUniforms(uniforms);
customUniforms.assignTo(uniforms);
return uniforms.buildUniforms();
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
return uniforms;
}
public boolean hasShadowPass() {
@@ -28,6 +28,7 @@ import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.shader.Framebuffer;
@@ -48,6 +49,7 @@ public class CompositeRenderer {
private final IntSupplier noiseTexture;
private final FrameUpdateNotifier updateNotifier;
private final CenterDepthSampler centerDepthSampler;
private final CustomUniforms customUniforms;
private final Object2ObjectMap<String, IntSupplier> customTextureIds;
@Getter
private final ImmutableSet<Integer> flippedAtLeastOnceFinal;
@@ -56,12 +58,13 @@ public class CompositeRenderer {
IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier,
CenterDepthSampler centerDepthSampler, BufferFlipper bufferFlipper,
Supplier<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips) {
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips, CustomUniforms customUniforms) {
this.noiseTexture = noiseTexture;
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.renderTargets = renderTargets;
this.customTextureIds = customTextureIds;
this.customUniforms = customUniforms;
final ImmutableList.Builder<Pass> passes = ImmutableList.builder();
final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>();
@@ -207,6 +210,8 @@ public class CompositeRenderer {
if (computeProgram != null) {
ranCompute = true;
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight);
}
}
@@ -236,6 +241,8 @@ public class CompositeRenderer {
renderPass.framebuffer.bind();
renderPass.program.use();
this.customUniforms.push(renderPass.program);
FullScreenQuadRenderer.INSTANCE.renderQuad();
}
@@ -307,9 +314,11 @@ public class CompositeRenderer {
throw new RuntimeException("Shader compilation failed!", e);
}
CommonUniforms.addDynamicUniforms(builder);
this.customUniforms.assignTo(builder);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addCommonUniforms(builder, source.getParent().getPack().getIdMap(), source.getParent().getPackDirectives(), updateNotifier);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
@@ -324,8 +333,12 @@ public class CompositeRenderer {
// TODO: Don't duplicate this with FinalPassRenderer
centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth"));
return builder.build();
}
Program build = builder.build();
this.customUniforms.mapholderToPass(builder, build);
return build;
}
private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
@@ -347,7 +360,10 @@ public class CompositeRenderer {
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addCommonUniforms(builder, source.getParent().getPack().getIdMap(), source.getParent().getPackDirectives(), updateNotifier);
CommonUniforms.addDynamicUniforms(builder);
this.customUniforms.assignTo(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
@@ -364,6 +380,8 @@ public class CompositeRenderer {
programs[i] = builder.buildCompute();
customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups());
}
}
@@ -28,6 +28,7 @@ import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.shader.Framebuffer;
@@ -56,6 +57,7 @@ public class FinalPassRenderer {
private final FrameUpdateNotifier updateNotifier;
private final CenterDepthSampler centerDepthSampler;
private final Object2ObjectMap<String, IntSupplier> customTextureIds;
private final CustomUniforms customUniforms;
// TODO: The length of this argument list is getting a bit ridiculous
public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, IntSupplier noiseTexture,
@@ -63,13 +65,14 @@ public class FinalPassRenderer {
CenterDepthSampler centerDepthSampler,
Supplier<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds,
ImmutableSet<Integer> flippedAtLeastOnce) {
ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms) {
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.customTextureIds = customTextureIds;
this.noiseTexture = noiseTexture;
this.renderTargets = renderTargets;
this.customUniforms = customUniforms;
this.finalPass = pack.getCompositeFinal().map(source -> {
Pass pass = new Pass();
ProgramDirectives directives = source.getDirectives();
@@ -181,6 +184,8 @@ public class FinalPassRenderer {
for (ComputeProgram computeProgram : finalPass.computes) {
if (computeProgram != null) {
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(baseWidth, baseHeight);
}
}
@@ -196,6 +201,9 @@ public class FinalPassRenderer {
}
finalPass.program.use();
this.customUniforms.push(finalPass.program);
FullScreenQuadRenderer.INSTANCE.renderQuad();
FullScreenQuadRenderer.end();
@@ -327,9 +335,11 @@ public class FinalPassRenderer {
throw new RuntimeException("Shader compilation failed!", e);
}
this.customUniforms.assignTo(builder);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addCommonUniforms(builder, source.getParent().getPack().getIdMap(), source.getParent().getPackDirectives(), updateNotifier);
CommonUniforms.addDynamicUniforms(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
@@ -343,7 +353,11 @@ public class FinalPassRenderer {
// TODO: Don't duplicate this with CompositeRenderer
centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth"));
return builder.build();
Program build = builder.build();
this.customUniforms.mapholderToPass(builder, build);
return build;
}
private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
@@ -364,9 +378,11 @@ public class FinalPassRenderer {
throw new RuntimeException("Shader compilation failed!", e);
}
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addCommonUniforms(builder, source.getParent().getPack().getIdMap(), source.getParent().getPackDirectives(), updateNotifier);
customUniforms.assignTo(builder);
CommonUniforms.addDynamicUniforms(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
@@ -383,6 +399,8 @@ public class FinalPassRenderer {
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups());
}
}
@@ -23,6 +23,7 @@ import net.coderbot.iris.shaderpack.preprocessor.JcppProcessor;
import net.coderbot.iris.shaderpack.texture.CustomTextureData;
import net.coderbot.iris.shaderpack.texture.TextureFilteringData;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.irisshaders.iris.api.v0.IrisApi;
import org.jetbrains.annotations.Nullable;
@@ -47,6 +48,8 @@ import java.util.stream.Collectors;
public class ShaderPack {
private static final Gson GSON = new Gson();
public final CustomUniforms.Builder customUniforms;
private final ProgramSet base;
@Nullable
private final ProgramSet overworld;
@@ -243,6 +246,8 @@ public class ShaderPack {
customTextureDataMap.put(textureStage, innerCustomTextureDataMap);
});
this.customUniforms = shaderProperties.getCustomUniforms();
}
private String getCurrentProfileName() {
@@ -21,6 +21,7 @@ import net.coderbot.iris.gl.texture.TextureScaleOverride;
import net.coderbot.iris.shaderpack.option.ShaderPackOptions;
import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import java.io.IOException;
import java.io.StringReader;
@@ -42,6 +43,7 @@ import java.util.function.Consumer;
* values in here & the values parsed from shader source code.
*/
public class ShaderProperties {
@Getter private final CustomUniforms.Builder customUniforms = new CustomUniforms.Builder();
@Getter private CloudSetting cloudSetting = CloudSetting.DEFAULT;
@Getter private OptionalBoolean oldHandLight = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean dynamicHandLight = OptionalBoolean.DEFAULT;
@@ -309,6 +311,26 @@ public class ShaderProperties {
handleWhitespacedListDirective(key, value, "iris.features.required", options -> requiredFeatureFlags = options);
handleWhitespacedListDirective(key, value, "iris.features.optional", options -> optionalFeatureFlags = options);
handlePassDirective("variable.", key, value, pass -> {
String[] parts = pass.split("\\.");
if (parts.length != 2) {
Iris.logger.warn("Custom variables should take the form of `variable.<type>.<name> = <expression>. Ignoring " + key);
return;
}
customUniforms.addVariable(parts[0], parts[1], value, false);
});
handlePassDirective("uniform.", key, value, pass -> {
String[] parts = pass.split("\\.");
if (parts.length != 2) {
Iris.logger.warn("Custom uniforms sould take the form of `uniform.<type>.<name> = <expression>. Ignoring " + key);
return;
}
customUniforms.addVariable(parts[0], parts[1], value, true);
});
// TODO: Buffer size directives
// TODO: Conditional program enabling directives
});
@@ -12,6 +12,8 @@ import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderFogCompon
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.SodiumTerrainPipeline;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.util.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
@@ -30,15 +32,20 @@ public class IrisChunkProgram extends ChunkProgram {
@Nullable
private final ProgramImages irisProgramImages;
public IrisChunkProgram(RenderDevice owner, ResourceLocation name, int handle,
@Nullable ProgramUniforms irisProgramUniforms, @Nullable ProgramSamplers irisProgramSamplers,
@Nullable ProgramImages irisProgramImages) {
private CustomUniforms customUniforms;
public IrisChunkProgram(RenderDevice owner, ResourceLocation name, int handle, boolean isShadowPass, SodiumTerrainPipeline pipeline, CustomUniforms customUniforms) {
super(owner, name, handle, ChunkShaderFogComponent.None::new);
this.uModelViewMatrix = this.getUniformLocation("iris_ModelViewMatrix");
this.uNormalMatrix = this.getUniformLocation("iris_NormalMatrix");
this.irisProgramUniforms = irisProgramUniforms;
this.irisProgramSamplers = irisProgramSamplers;
this.irisProgramImages = irisProgramImages;
this.customUniforms = customUniforms;
ProgramUniforms.Builder builder = pipeline.initUniforms(handle);
customUniforms.mapholderToPass(builder, this);
this.irisProgramUniforms = builder.buildUniforms();
this.irisProgramSamplers
= isShadowPass? pipeline.initShadowSamplers(handle) : pipeline.initTerrainSamplers(handle);
this.irisProgramImages = isShadowPass ? pipeline.initShadowImages(handle) : pipeline.initTerrainImages(handle);
}
@Override
@@ -64,6 +71,8 @@ public class IrisChunkProgram extends ChunkProgram {
uniformMatrix(uModelViewMatrix, modelViewMatrix);
uniformMatrix(uNormalMatrix, normalMatrix);
customUniforms.push(this);
}
@Override
@@ -142,21 +142,7 @@ public class IrisChunkProgramOverrides {
.bindAttribute("mc_Entity", IrisChunkShaderBindingPoints.BLOCK_ID)
.bindAttribute("at_midBlock", IrisChunkShaderBindingPoints.MID_BLOCK)
.bindAttribute("iris_ModelOffset", ChunkShaderBindingPoints.MODEL_OFFSET)
.build((program, name) -> {
ProgramUniforms uniforms = pipeline.initUniforms(name);
ProgramSamplers samplers;
ProgramImages images;
if (pass == IrisTerrainPass.SHADOW) {
samplers = pipeline.initShadowSamplers(name);
images = pipeline.initShadowImages(name);
} else {
samplers = pipeline.initTerrainSamplers(name);
images = pipeline.initTerrainImages(name);
}
return new IrisChunkProgram(device, program, name, uniforms, samplers, images);
});
.build((program, name) -> new IrisChunkProgram(device, program, name, pass == IrisTerrainPass.SHADOW, pipeline, pipeline.getCustomUniforms()));
} finally {
vertShader.delete();
if (geomShader != null) {
@@ -44,17 +44,22 @@ public final class CommonUniforms {
// no construction allowed
}
public static void addNonDynamicUniforms(UniformHolder uniforms, IdMap idMap, PackDirectives directives, FrameUpdateNotifier updateNotifier) {
CameraUniforms.addCameraUniforms(uniforms, updateNotifier);
ViewportUniforms.addViewportUniforms(uniforms);
WorldTimeUniforms.addWorldTimeUniforms(uniforms);
SystemTimeUniforms.addSystemTimeUniforms(uniforms);
new CelestialUniforms(directives.getSunPathRotation()).addCelestialUniforms(uniforms);
IrisExclusiveUniforms.addIrisExclusiveUniforms(uniforms);
IdMapUniforms.addIdMapUniforms(updateNotifier, uniforms, idMap, directives.isOldHandLight());
MatrixUniforms.addMatrixUniforms(uniforms, directives);
HardcodedCustomUniforms.addHardcodedCustomUniforms(uniforms, updateNotifier);
CommonUniforms.generalCommonUniforms(uniforms, updateNotifier, directives);
}
// Needs to use a LocationalUniformHolder as we need it for the common uniforms
public static void addCommonUniforms(DynamicUniformHolder uniforms, IdMap idMap, PackDirectives directives, FrameUpdateNotifier updateNotifier) {
CameraUniforms.addCameraUniforms(uniforms, updateNotifier);
ViewportUniforms.addViewportUniforms(uniforms);
WorldTimeUniforms.addWorldTimeUniforms(uniforms);
SystemTimeUniforms.addSystemTimeUniforms(uniforms);
new CelestialUniforms(directives.getSunPathRotation()).addCelestialUniforms(uniforms);
IdMapUniforms.addIdMapUniforms(updateNotifier, uniforms, idMap, directives.isOldHandLight());
IrisExclusiveUniforms.addIrisExclusiveUniforms(uniforms);
MatrixUniforms.addMatrixUniforms(uniforms, directives);
HardcodedCustomUniforms.addHardcodedCustomUniforms(uniforms, updateNotifier);
public static void addDynamicUniforms(DynamicUniformHolder uniforms) {
IdMapUniforms.addEntityIdMapUniforms(uniforms);
FogUniforms.addFogUniforms(uniforms);
// TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform,
@@ -91,7 +96,6 @@ public final class CommonUniforms {
uniforms.uniform4f("entityColor", CapturedRenderingState.INSTANCE::getCurrentEntityColor, CapturedRenderingState.INSTANCE.getEntityColorNotifier());
CommonUniforms.generalCommonUniforms(uniforms, updateNotifier, directives);
}
public static void generalCommonUniforms(UniformHolder uniforms, FrameUpdateNotifier updateNotifier, PackDirectives directives) {
@@ -3,6 +3,7 @@ package net.coderbot.iris.uniforms;
import it.unimi.dsi.fastutil.objects.Object2IntFunction;
import com.gtnewhorizons.angelica.compat.mojang.InteractionHand;
import net.coderbot.iris.gl.uniform.DynamicUniformHolder;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.shaderpack.IdMap;
import net.coderbot.iris.shaderpack.materialmap.NamespacedId;
@@ -21,7 +22,7 @@ public final class IdMapUniforms {
private IdMapUniforms() {
}
public static void addIdMapUniforms(FrameUpdateNotifier notifier, DynamicUniformHolder uniforms, IdMap idMap, boolean isOldHandLight) {
public static void addIdMapUniforms(FrameUpdateNotifier notifier, UniformHolder uniforms, IdMap idMap, boolean isOldHandLight) {
HeldItemSupplier mainHandSupplier = new HeldItemSupplier(InteractionHand.MAIN_HAND, idMap.getItemIdMap(), isOldHandLight);
HeldItemSupplier offHandSupplier = new HeldItemSupplier(InteractionHand.OFF_HAND, idMap.getItemIdMap(), false);
notifier.addListener(mainHandSupplier::update);
@@ -35,14 +36,16 @@ public final class IdMapUniforms {
// TODO: Figure out API.
//.uniformVanilla3f(PER_FRAME, "heldBlockLightColor", mainHandSupplier::getLightColor)
//.uniformVanilla3f(PER_FRAME, "heldBlockLightColor2", offHandSupplier::getLightColor);
uniforms.uniform1i("entityId", CapturedRenderingState.INSTANCE::getCurrentRenderedEntity,
CapturedRenderingState.INSTANCE.getEntityIdNotifier());
uniforms.uniform1i("blockEntityId", CapturedRenderingState.INSTANCE::getCurrentRenderedBlockEntity,
CapturedRenderingState.INSTANCE.getBlockEntityIdNotifier());
}
public static void addEntityIdMapUniforms(DynamicUniformHolder uniforms) {
uniforms.uniform1i("entityId", CapturedRenderingState.INSTANCE::getCurrentRenderedEntity,
CapturedRenderingState.INSTANCE.getEntityIdNotifier());
uniforms.uniform1i("blockEntityId", CapturedRenderingState.INSTANCE::getCurrentRenderedBlockEntity,
CapturedRenderingState.INSTANCE.getBlockEntityIdNotifier());
}
/**
* Provides the currently held item, and it's light value, in the given hand as a uniform. Uses the item.properties ID map to map the item
* to an integer, and the old hand light value to map offhand to main hand.
@@ -27,8 +27,6 @@ public final class SystemTimeUniforms {
public static void addSystemTimeUniforms(UniformHolder uniforms) {
uniforms
.uniform1i(UniformUpdateFrequency.PER_FRAME, "frameCounter", COUNTER)
// TODO: Don't hardcode framemod8 here for Sildur's Vibrant Shaders
.uniform1i(UniformUpdateFrequency.PER_FRAME, "framemod8", () -> COUNTER.getAsInt() % 8)
.uniform1f(UniformUpdateFrequency.PER_FRAME, "frameTime", TIMER::getLastFrameTime)
.uniform1f(UniformUpdateFrequency.PER_FRAME, "frameTimeCounter", TIMER::getFrameTimeCounter);
}
@@ -0,0 +1,200 @@
package net.coderbot.iris.uniforms.custom;
import com.google.common.collect.ImmutableMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.uniform.FloatSupplier;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.gl.uniform.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.CachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float3VectorCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float4MatrixCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float4VectorCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.FloatCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Int2VectorCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Int3VectorCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.IntCachedUniform;
import net.minecraft.util.Vec3;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector2f;
import org.joml.Vector2i;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import java.util.Collection;
import java.util.Map;
import java.util.function.BooleanSupplier;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class CustomUniformFixedInputUniformsHolder {
final private ImmutableMap<String, CachedUniform> inputVariables;
public CustomUniformFixedInputUniformsHolder(
ImmutableMap<String, CachedUniform> inputVariables) {
this.inputVariables = inputVariables;
}
public Type getType(String name) {
CachedUniform uniform = this.inputVariables.get(name);
if (uniform == null)
return null;
return uniform.getType();
}
public boolean containsKey(String name) {
return this.inputVariables.containsKey(name);
}
public CachedUniform getUniform(String name) {
return this.inputVariables.get(name);
}
public void updateAll() {
for (CachedUniform value : this.inputVariables.values()) {
value.update();
}
}
public Collection<CachedUniform> getAll() {
return this.inputVariables.values();
}
public static class Builder implements UniformHolder {
final private Map<String, CachedUniform> inputVariables = new Object2ObjectOpenHashMap<>();
private Builder put(String name, CachedUniform uniform) {
if (inputVariables.containsKey(name)) {
Iris.logger.warn("Duplicated fixed uniform supplied as inputs to the Custom uniform holder: " + name);
return this;
}
inputVariables.put(name, uniform);
return this;
}
@Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, FloatSupplier value) {
return this.put(name, new FloatCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, IntSupplier value) {
return this.put(name, new FloatCachedUniform(name, updateFrequency, value::getAsInt));
}
@Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) {
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) value.getAsDouble()));
}
@Override
public Builder uniform1i(UniformUpdateFrequency updateFrequency, String name, IntSupplier value) {
return this.put(name, new IntCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform1b(UniformUpdateFrequency updateFrequency, String name, BooleanSupplier value) {
return this.put(name, new BooleanCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform2f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector2f> value) {
return this.put(name, new Float2VectorCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform2i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector2i> value) {
return this.put(name, new Int2VectorCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3f> value) {
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3i> value) {
return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value));
}
@Override
public UniformHolder uniformVanilla3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vec3> value) {
throw new RuntimeException("Exception from Custom Uniform UniformHolder implementation. This should never be reached, please send help");
}
@Override
public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4f> value) {
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
Vector4f vec = value.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
}
@Override
public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3d> value) {
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
Vector3d vec = value.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
}
@Override
public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4f> value) {
Vector4f held = new Vector4f();
return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> {
Vector4f vec = value.get();
held.set(vec.x(), vec.y(), vec.z(), vec.w());
return held;
}));
}
@Override
public UniformHolder uniform4fArray(UniformUpdateFrequency updateFrequency, String name, Supplier<float[]> value) {
Vector4f held = new Vector4f();
return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> {
float[] vec = value.get();
held.set(vec);
return held;
}));
}
@Override
public UniformHolder uniformMatrix(
UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4f> value) {
return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value));
}
@Override
public UniformHolder uniformMatrixFromArray(
UniformUpdateFrequency updateFrequency, String name, Supplier<float[]> value) {
Matrix4f held = new Matrix4f();
return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, () -> {
held.set(value.get());
return held;
}));
}
@Override
public UniformHolder externallyManagedUniform(String name, UniformType type) {
// TODO: what is this function for?
return this;
}
public CustomUniformFixedInputUniformsHolder build() {
return new CustomUniformFixedInputUniformsHolder(ImmutableMap.copyOf(this.inputVariables));
}
}
}
@@ -0,0 +1,353 @@
package net.coderbot.iris.uniforms.custom;
import com.github.bsideup.jabel.Desugar;
import com.google.common.collect.ImmutableMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import kroppeb.stareval.element.ExpressionElement;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import kroppeb.stareval.parser.Parser;
import kroppeb.stareval.resolver.ExpressionResolver;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.uniform.LocationalUniformHolder;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.parsing.IrisFunctions;
import net.coderbot.iris.parsing.IrisOptions;
import net.coderbot.iris.parsing.VectorType;
import net.coderbot.iris.uniforms.custom.cached.CachedUniform;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class CustomUniforms implements FunctionContext {
private final Map<String, CachedUniform> variables = new Object2ObjectLinkedOpenHashMap<>();
private final Map<String, Expression> variablesExpressions = new Object2ObjectLinkedOpenHashMap<>();
private final CustomUniformFixedInputUniformsHolder inputHolder;
private final List<CachedUniform> uniformOrder;
private final Map<Object, Object2IntMap<CachedUniform>> locationMap = new Object2ObjectOpenHashMap<>();
private final Map<CachedUniform, List<CachedUniform>> dependsOn;
private CustomUniforms(CustomUniformFixedInputUniformsHolder inputHolder, Map<String, Builder.Variable> variables) {
this.inputHolder = inputHolder;
ExpressionResolver resolver = new ExpressionResolver(
IrisFunctions.functions,
(name) -> {
Type type = this.inputHolder.getType(name);
if (type != null)
return type;
Builder.Variable variable = variables.get(name);
if (variable != null)
return variable.type;
return null;
},
true);
for (Builder.Variable variable : variables.values()) {
try {
Expression expression = resolver.resolveExpression(variable.type, variable.expression);
CachedUniform cachedUniform = CachedUniform
.forExpression(variable.name, variable.type, expression, this);
this.addVariable(expression, cachedUniform);
if (variable.uniform) {
List<CachedUniform> uniforms = new ArrayList<>();
uniforms.add(cachedUniform);
}
//Iris.logger.info("Was able to resolve uniform " + variable.name + " = " + variable.expression);
} catch (Exception e) {
Iris.logger
.warn("Failed to resolve uniform " + variable.name + ", reason: " + e
.getMessage() + " ( = " + variable.expression + ")", e);
}
}
{
// toposort
this.dependsOn = new Object2ObjectOpenHashMap<>();
Map<CachedUniform, List<CachedUniform>> requiredBy = new Object2ObjectOpenHashMap<>();
Object2IntMap<CachedUniform> dependsOnCount = new Object2IntOpenHashMap<>();
for (CachedUniform input : this.inputHolder.getAll()) {
requiredBy.put(input, new ObjectArrayList<>());
}
for (CachedUniform input : this.variables.values()) {
requiredBy.put(input, new ObjectArrayList<>());
}
FunctionReturn functionReturn = new FunctionReturn();
Set<VariableExpression> requires = new ObjectOpenHashSet<>();
Set<CachedUniform> brokenUniforms = new ObjectOpenHashSet<>();
for (Map.Entry<String, Expression> entry : this.variablesExpressions.entrySet()) {
requires.clear();
entry.getValue().listVariables(requires);
if (requires.isEmpty()) {
continue;
}
CachedUniform uniform = this.variables.get(entry.getKey());
List<CachedUniform> dependencies = new ArrayList<>();
for (VariableExpression v : requires) {
Expression evaluated = v.partialEval(this, functionReturn);
if (evaluated instanceof CachedUniform) {
dependencies.add((CachedUniform) evaluated);
} else {
// we are depending on a broken uniform
brokenUniforms.add(uniform);
}
}
if (dependencies.isEmpty()) {
// can be empty if we rely on broken uniforms
continue;
}
dependsOn.put(uniform, dependencies);
dependsOnCount.put(uniform, dependencies.size());
for (CachedUniform dependency : dependencies) {
requiredBy.get(dependency).add(uniform);
}
}
// actual toposort:
List<CachedUniform> ordered = new ObjectArrayList<>();
List<CachedUniform> free = new ObjectArrayList<>();
// init
for (CachedUniform entry : requiredBy.keySet()) {
if (!dependsOnCount.containsKey(entry)) {
free.add(entry);
}
}
while (!free.isEmpty()) {
CachedUniform pop = free.remove(free.size() - 1);
if (!brokenUniforms.contains(pop)) {
// only add those that aren't broken
ordered.add(pop);
} else {
// mark all those that rely on use as broken too
brokenUniforms.addAll(requiredBy.get(pop));
}
for (CachedUniform dependent : requiredBy.get(pop)) {
int count = dependsOnCount.mergeInt(dependent, -1, Integer::sum);
assert count >= 0;
if (count == 0) {
free.add(dependent);
dependsOnCount.removeInt(dependent);
}
}
}
if (!brokenUniforms.isEmpty()) {
Iris.logger.warn(
"The following uniforms won't work, either because they are broken, or reference a broken uniform: \n" +
brokenUniforms.stream().map(CachedUniform::getName).collect(Collectors.joining(", ")));
}
if (!dependsOnCount.isEmpty()) {
throw new IllegalStateException("Circular reference detected between: " +
dependsOnCount.object2IntEntrySet()
.stream()
.map(entry -> entry.getKey().getName() + " (" + entry.getIntValue() + ")")
.collect(Collectors.joining(", "))
);
}
this.uniformOrder = ordered;
}
}
private void addVariable(Expression expression, CachedUniform uniform) throws Exception {
String name = uniform.getName();
if (this.variables.containsKey(name))
throw new Exception("Duplicated variable: " + name);
if (this.inputHolder.containsKey(name))
throw new Exception("Variable shadows build in uniform: " + name);
this.variables.put(name, uniform);
this.variablesExpressions.put(name, expression);
}
public void assignTo(LocationalUniformHolder targetHolder) {
Object2IntMap<CachedUniform> locations = new Object2IntOpenHashMap<>();
for (CachedUniform uniform : this.uniformOrder) {
try {
OptionalInt location = targetHolder.location(uniform.getName(), Type.convert(uniform.getType()));
if (location.isPresent()) {
locations.put(uniform, location.getAsInt());
}
} catch (Exception e) {
throw new RuntimeException(uniform.getName(), e);
}
}
this.locationMap.put(targetHolder, locations);
}
public void mapholderToPass(LocationalUniformHolder holder, Object pass) {
locationMap.put(pass, locationMap.remove(holder));
}
public void update() {
for (CachedUniform value : this.uniformOrder) {
value.update();
}
}
public void push(Object pass) {
Object2IntMap<CachedUniform> uniforms = this.locationMap.get(pass);
if (uniforms != null) {
uniforms.forEach(CachedUniform::pushIfChanged);
}
}
/**
* This function will do the following:
* <ul>
* <li>
* Remove unused uniforms
* </li>
* <li>
* TODO: Create separate push lists for each renderpass
* </li>
* <li>
* TODO: Sort the others in the correct execution line <p/>
* note: that if a `EVERY_FRAME` depends on a `EVERY_TICK`, it has to correctly now that it's
* dependency hasn't updated <br/>
* suggestion: set a boolean in the `EVERY_TICK` execution line saying this is a tick
* and have it set to false in the `EVERY_FRAME`. Depending on the value, `frameDependencies` or
* `allDependencies` lists are used
* </li>
* </ul>
*/
public void optimise() {
Object2IntMap<CachedUniform> dependedByCount = new Object2IntOpenHashMap<>();
// Count the times a uniform is depended on
for (List<CachedUniform> dependencies : this.dependsOn.values()) {
for (CachedUniform dependency : dependencies) {
dependedByCount.mergeInt(dependency, 1, Integer::sum);
}
}
// Count the times a pass depends on a uniform
// ensures they wont ever be removed
for (Object2IntMap<CachedUniform> map : this.locationMap.values()) {
for (CachedUniform cachedUniform : map.keySet()) {
dependedByCount.mergeInt(cachedUniform, 1, Integer::sum);
}
}
Set<CachedUniform> unused = new ObjectOpenHashSet<>();
for (int i = this.uniformOrder.size() - 1; i >= 0; i--) {
CachedUniform uniform = this.uniformOrder.get(i);
if (!dependedByCount.containsKey(uniform)) {
// not used
unused.add(uniform);
// remove dependencies
List<CachedUniform> dependencies = this.dependsOn.get(uniform);
if (dependencies != null) {
for (CachedUniform dependency : dependencies) {
// reduce count by 1
dependedByCount.computeIntIfPresent(dependency, (key, value) -> value - 1);
}
}
}
}
this.uniformOrder.removeAll(unused);
}
@Override
public boolean hasVariable(String name) {
return this.inputHolder.containsKey(name) || this.variables.containsKey(name);
}
@Override
public Expression getVariable(String name) {
// TODO: Make the simplify just return these ones
final CachedUniform inputUniform = this.inputHolder.getUniform(name);
if (inputUniform != null)
return inputUniform;
final CachedUniform customUniform = this.variables.get(name);
if (customUniform != null)
return customUniform;
throw new RuntimeException("Unknown variable: " + name);
}
public static class Builder {
final private static Map<String, Type> types = new ImmutableMap.Builder<String, Type>()
.put("bool", Type.Boolean)
.put("float", Type.Float)
.put("int", Type.Int)
.put("vec2", VectorType.VEC2)
.put("vec3", VectorType.VEC3)
.put("vec4", VectorType.VEC4)
.build();
final Map<String, Variable> variables = new Object2ObjectLinkedOpenHashMap<>();
public void addVariable(String type, String name, String expression, boolean isUniform) {
if (variables.containsKey(name)) {
Iris.logger.warn("Ignoring duplicated custom uniform name: " + name);
return;
}
Type parsedType = types.get(type);
if (parsedType == null) {
Iris.logger.warn("Ignoring invalid uniform type: " + type + " of " + name);
return;
}
try {
ExpressionElement ast = Parser.parse(expression, IrisOptions.options);
variables.put(name, new Variable(parsedType, name, ast, isUniform));
} catch (Exception e) {
Iris.logger.warn("Failed to parse custom variable/uniform " + name + " with expression " + expression, e);
}
}
public CustomUniforms build(
CustomUniformFixedInputUniformsHolder inputHolder
) {
return new CustomUniforms(inputHolder, this.variables);
}
@SafeVarargs
public final CustomUniforms build(
Consumer<UniformHolder>... uniforms
) {
CustomUniformFixedInputUniformsHolder.Builder inputs = new CustomUniformFixedInputUniformsHolder.Builder();
for (Consumer<UniformHolder> uniform : uniforms) {
uniform.accept(inputs);
}
return this.build(inputs.build());
}
@Desugar
private record Variable(Type type, String name, ExpressionElement expression, boolean uniform) {
}
}
}
@@ -0,0 +1,41 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import org.lwjgl.opengl.GL20;
import java.util.function.BooleanSupplier;
public class BooleanCachedUniform extends CachedUniform {
final private BooleanSupplier supplier;
private boolean cached;
public BooleanCachedUniform(String name, UniformUpdateFrequency updateFrequency, BooleanSupplier supplier) {
super(name, updateFrequency);
this.supplier = supplier;
}
@Override
protected boolean doUpdate() {
boolean prev = this.cached;
this.cached = this.supplier.getAsBoolean();
return prev != cached;
}
@Override
public void push(int location) {
GL20.glUniform1i(location, this.cached ? 1 : 0);
}
@Override
public void writeTo(FunctionReturn functionReturn) {
functionReturn.booleanReturn = this.cached;
}
@Override
public Type getType() {
return Type.Boolean;
}
}
@@ -0,0 +1,99 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector2f;
import org.joml.Vector3f;
import org.joml.Vector4f;
public abstract class CachedUniform implements VariableExpression {
private final String name;
private final UniformUpdateFrequency updateFrequency;
private boolean changed = true;
public CachedUniform(String name, UniformUpdateFrequency updateFrequency) {
this.name = name;
this.updateFrequency = updateFrequency;
}
static public CachedUniform forExpression(String name, Type type, Expression expression, FunctionContext context) {
final FunctionReturn held = new FunctionReturn();
final UniformUpdateFrequency frequency = UniformUpdateFrequency.CUSTOM;
if (type.equals(Type.Boolean)) {
return new BooleanCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return held.booleanReturn;
});
} else if (type.equals(Type.Int)) {
return new IntCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return held.intReturn;
});
} else if (type.equals(Type.Float)) {
return new FloatCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return held.floatReturn;
});
} else if (type.equals(VectorType.VEC2)) {
return new Float2VectorCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return (Vector2f) held.objectReturn;
});
} else if (type.equals(VectorType.VEC3)) {
return new Float3VectorCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return (Vector3f) held.objectReturn;
});
} else if (type.equals(VectorType.VEC4)) {
return new Float4VectorCachedUniform(name, frequency, () -> {
expression.evaluateTo(context, held);
return (Vector4f) held.objectReturn;
});
} else {
throw new IllegalArgumentException("Custom uniforms of type: " + type + " are currently not supported");
}
}
public void markUnchanged() {
this.changed = false;
}
public void update() {
doUpdate();
// TODO: Works around a logic error / architectural flaw - there's no way to
// know when a uniform has been uploaded to all programs, so we can never
// safely change this to false with the current design.
this.changed = true;
}
protected abstract boolean doUpdate();
public abstract void push(int location);
public void pushIfChanged(int location) {
if (this.changed)
push(location);
}
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
this.writeTo(functionReturn);
}
public abstract void writeTo(FunctionReturn functionReturn);
public abstract Type getType();
public String getName() {
return name;
}
public UniformUpdateFrequency getUpdateFrequency() {
return updateFrequency;
}
}
@@ -0,0 +1,30 @@
package net.coderbot.iris.uniforms.custom.cached;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector2f;
import org.lwjgl.opengl.GL20;
import java.util.function.Supplier;
public class Float2VectorCachedUniform extends VectorCachedUniform<Vector2f> {
public Float2VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Vector2f> supplier) {
super(name, updateFrequency, new Vector2f(), supplier);
}
@Override
protected void setFrom(Vector2f other) {
this.cached.set(other);
}
@Override
public void push(int location) {
GL20.glUniform2f(location, this.cached.x, this.cached.y);
}
@Override
public VectorType getType() {
return VectorType.VEC2;
}
}
@@ -0,0 +1,30 @@
package net.coderbot.iris.uniforms.custom.cached;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL20;
import java.util.function.Supplier;
public class Float3VectorCachedUniform extends VectorCachedUniform<Vector3f> {
public Float3VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Vector3f> supplier) {
super(name, updateFrequency, new Vector3f(), supplier);
}
@Override
protected void setFrom(Vector3f other) {
this.cached.set(other);
}
@Override
public void push(int location) {
GL20.glUniform3f(location, this.cached.x, this.cached.y, this.cached.z);
}
@Override
public VectorType getType() {
return VectorType.VEC3;
}
}
@@ -0,0 +1,36 @@
package net.coderbot.iris.uniforms.custom.cached;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.MatrixType;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL20;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.function.Supplier;
public class Float4MatrixCachedUniform extends VectorCachedUniform<Matrix4f> {
final private FloatBuffer buffer = ByteBuffer.allocateDirect(16 << 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
public Float4MatrixCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Matrix4f> supplier) {
super(name, updateFrequency, new Matrix4f(), supplier);
}
@Override
protected void setFrom(Matrix4f other) {
((Matrix4f) this.cached).set(other);
}
@Override
public void push(int location) {
// `gets` the values from the matrix and put's them into a buffer
this.cached.get(buffer);
GL20.glUniformMatrix4(location, false, buffer);
}
@Override
public MatrixType<Matrix4f> getType() {
return MatrixType.MAT4;
}
}
@@ -0,0 +1,30 @@
package net.coderbot.iris.uniforms.custom.cached;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL20;
import java.util.function.Supplier;
public class Float4VectorCachedUniform extends VectorCachedUniform<Vector4f> {
public Float4VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Vector4f> supplier) {
super(name, updateFrequency, new Vector4f(), supplier);
}
@Override
protected void setFrom(Vector4f other) {
this.cached.set(other);
}
@Override
public void push(int location) {
GL20.glUniform4f(location, this.cached.x, this.cached.y, this.cached.z, this.cached.w);
}
@Override
public VectorType getType() {
return VectorType.VEC4;
}
}
@@ -0,0 +1,40 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.gl.uniform.FloatSupplier;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import org.lwjgl.opengl.GL20;
public class FloatCachedUniform extends CachedUniform {
final private FloatSupplier supplier;
private float cached;
public FloatCachedUniform(String name, UniformUpdateFrequency updateFrequency, FloatSupplier supplier) {
super(name, updateFrequency);
this.supplier = supplier;
}
@Override
protected boolean doUpdate() {
float prev = this.cached;
this.cached = this.supplier.getAsFloat();
return prev != cached;
}
@Override
public void push(int location) {
GL20.glUniform1f(location, this.cached);
}
@Override
public void writeTo(FunctionReturn functionReturn) {
functionReturn.floatReturn = this.cached;
}
@Override
public Type getType() {
return Type.Float;
}
}
@@ -0,0 +1,36 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.function.FunctionReturn;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector2i;
import org.lwjgl.opengl.GL20;
import java.util.function.Supplier;
public class Int2VectorCachedUniform extends VectorCachedUniform<Vector2i> {
public Int2VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Vector2i> supplier) {
super(name, updateFrequency, new Vector2i(), supplier);
}
@Override
protected void setFrom(Vector2i other) {
this.cached.set(other);
}
@Override
public void push(int location) {
GL20.glUniform2i(location, this.cached.x, this.cached.y);
}
@Override
public void writeTo(FunctionReturn functionReturn) {
functionReturn.objectReturn = this.cached;
}
@Override
public VectorType getType() {
return VectorType.I_VEC2;
}
}
@@ -0,0 +1,30 @@
package net.coderbot.iris.uniforms.custom.cached;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.parsing.VectorType;
import org.joml.Vector3i;
import org.lwjgl.opengl.GL20;
import java.util.function.Supplier;
public class Int3VectorCachedUniform extends VectorCachedUniform<Vector3i> {
public Int3VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, Supplier<Vector3i> supplier) {
super(name, updateFrequency, new Vector3i(), supplier);
}
@Override
protected void setFrom(Vector3i other) {
this.cached.set(other);
}
@Override
public void push(int location) {
GL20.glUniform3i(location, this.cached.x, this.cached.y, this.cached.z);
}
@Override
public VectorType getType() {
return VectorType.I_VEC3;
}
}
@@ -0,0 +1,41 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import org.lwjgl.opengl.GL20;
import java.util.function.IntSupplier;
public class IntCachedUniform extends CachedUniform {
final private IntSupplier supplier;
private int cached;
public IntCachedUniform(String name, UniformUpdateFrequency updateFrequency, IntSupplier supplier) {
super(name, updateFrequency);
this.supplier = supplier;
}
@Override
protected boolean doUpdate() {
int prev = this.cached;
this.cached = this.supplier.getAsInt();
return prev != cached;
}
@Override
public void push(int location) {
GL20.glUniform1i(location, this.cached);
}
@Override
public void writeTo(FunctionReturn functionReturn) {
functionReturn.intReturn = this.cached;
}
@Override
public Type getType() {
return Type.Int;
}
}
@@ -0,0 +1,47 @@
package net.coderbot.iris.uniforms.custom.cached;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;
public abstract class VectorCachedUniform<T> extends CachedUniform {
final protected T cached;
final private Supplier<T> supplier;
public VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, T cache, Supplier<@NotNull T> supplier) {
super(name, updateFrequency);
this.supplier = supplier;
this.cached = cache;
}
abstract protected void setFrom(T other);
@Override
protected boolean doUpdate() {
T other = this.supplier.get();
if (other == null) {
Iris.logger.warn("Cached Uniform supplier gave null back");
return false;
}
if (!this.cached.equals(other)) {
this.setFrom(other);
return true;
} else return false;
}
@Override
public void writeTo(FunctionReturn functionReturn) {
functionReturn.objectReturn = this.cached;
}
@Override
public Type getType() {
return Type.Float;
}
}