Compare commits

...
Author SHA1 Message Date
Darren Eberly bed724ba59 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
2025-03-18 10:04:31 -07:00
Jason Mitchell 6fa973dbc8 Adds two new overloads (#906) 2025-03-13 08:24:57 -07:00
91 changed files with 4634 additions and 268 deletions

No files matched your search

@@ -863,6 +863,16 @@ public class GLStateManager {
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, FloatBuffer pixels) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, DoubleBuffer pixels) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels != null ? pixels.asIntBuffer() : (IntBuffer) null);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
@@ -97,6 +97,8 @@ public class RenderSystem {
GL20.glUniform3f(location, v0, v1, v2);
}
public static void uniform3i(int location, int v0, int v1, int v2) { GL20.glUniform3i(location, v0, v1, v2); }
public static void uniform4f(int location, float v0, float v1, float v2, float v3) {
GL20.glUniform4f(location, v0, v1, v2, v3);
}
@@ -6,7 +6,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import java.nio.IntBuffer;
import java.nio.Buffer;
public class TextureInfoCache {
/**
@@ -25,7 +25,7 @@ public class TextureInfoCache {
return cache.computeIfAbsent(id, TextureInfo::new);
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) {
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTexture());
if(info == null) return;
+13
View File
@@ -0,0 +1,13 @@
package kroppeb.stareval;
import java.util.function.Consumer;
public class Util {
public static <T> T make(T item, Consumer<T> init) {
init.accept(item);
return item;
}
}
@@ -1,23 +1,12 @@
package kroppeb.stareval.element.tree;
import com.github.bsideup.jabel.Desugar;
import kroppeb.stareval.element.AccessibleExpressionElement;
public class AccessExpressionElement implements AccessibleExpressionElement {
private final AccessibleExpressionElement base;
private final String index;
@Desugar
public record AccessExpressionElement(AccessibleExpressionElement base,
String index) implements AccessibleExpressionElement {
public AccessExpressionElement(AccessibleExpressionElement base, String index) {
this.base = base;
this.index = index;
}
public AccessibleExpressionElement getBase() {
return this.base;
}
public String getIndex() {
return this.index;
}
@Override
public String toString() {
@@ -1,30 +1,13 @@
package kroppeb.stareval.element.tree;
import com.github.bsideup.jabel.Desugar;
import kroppeb.stareval.element.ExpressionElement;
import kroppeb.stareval.parser.BinaryOp;
public class BinaryExpressionElement implements ExpressionElement {
private final BinaryOp op;
private final ExpressionElement left;
private final ExpressionElement right;
@Desugar
public record BinaryExpressionElement(BinaryOp op, ExpressionElement left,
ExpressionElement right) implements ExpressionElement {
public BinaryExpressionElement(BinaryOp op, ExpressionElement left, ExpressionElement right) {
this.op = op;
this.left = left;
this.right = right;
}
public BinaryOp getOp() {
return this.op;
}
public ExpressionElement getLeft() {
return this.left;
}
public ExpressionElement getRight() {
return this.right;
}
@Override
public String toString() {
@@ -1,25 +1,13 @@
package kroppeb.stareval.element.tree;
import com.github.bsideup.jabel.Desugar;
import kroppeb.stareval.element.ExpressionElement;
import java.util.List;
public class FunctionCall implements ExpressionElement {
private final String id;
private final List<? extends ExpressionElement> args;
@Desugar
public record FunctionCall(String id, List<? extends ExpressionElement> args) implements ExpressionElement {
public FunctionCall(String id, List<? extends ExpressionElement> args) {
this.id = id;
this.args = args;
}
public String getId() {
return this.id;
}
public List<? extends ExpressionElement> getArgs() {
return this.args;
}
@Override
public String toString() {
@@ -1,24 +1,12 @@
package kroppeb.stareval.element.tree;
import com.github.bsideup.jabel.Desugar;
import kroppeb.stareval.element.ExpressionElement;
import kroppeb.stareval.parser.UnaryOp;
public class UnaryExpressionElement implements ExpressionElement {
private final UnaryOp op;
private final ExpressionElement inner;
@Desugar
public record UnaryExpressionElement(UnaryOp op, ExpressionElement inner) implements ExpressionElement {
public UnaryExpressionElement(UnaryOp op, ExpressionElement inner) {
this.op = op;
this.inner = inner;
}
public UnaryOp getOp() {
return op;
}
public ExpressionElement getInner() {
return inner;
}
@Override
public String toString() {
@@ -21,7 +21,7 @@ public class PartialBinaryExpression extends PartialExpression implements Priori
@Override
public int getPriority() {
return this.op.getPriority();
return this.op.priority();
}
@Override
@@ -1,10 +1,7 @@
package kroppeb.stareval.exception;
public class MissingTokenException extends ParseException {
private static final long serialVersionUID = -2096321911994168858L;
public MissingTokenException(String message, int index) {
public MissingTokenException(String message, int index) {
super(message + " at index " + index);
}
}
@@ -1,10 +1,7 @@
package kroppeb.stareval.exception;
public abstract class ParseException extends Exception{
private static final long serialVersionUID = -5014053641238717471L;
public ParseException() {
public abstract class ParseException extends Exception {
public ParseException() {
}
public ParseException(String message) {
@@ -1,10 +1,7 @@
package kroppeb.stareval.exception;
public class UnexpectedCharacterException extends ParseException {
private static final long serialVersionUID = -3886198952263126846L;
public UnexpectedCharacterException(char expected, char actual, int index) {
public UnexpectedCharacterException(char expected, char actual, int index) {
this("Expected to read '" + expected + "' but got '" + actual + "' at index " + index);
}
@@ -1,10 +1,7 @@
package kroppeb.stareval.exception;
public class UnexpectedEndingException extends ParseException {
private static final long serialVersionUID = -3704913315979481520L;
public UnexpectedEndingException() {
public UnexpectedEndingException() {
this("Expected to read more text, but the string has ended");
}
@@ -1,10 +1,7 @@
package kroppeb.stareval.exception;
public class UnexpectedTokenException extends ParseException {
private static final long serialVersionUID = 689385399380177588L;
public UnexpectedTokenException(String message, int index) {
public UnexpectedTokenException(String message, int index) {
super(message + " at index " + index);
}
}
@@ -0,0 +1,31 @@
package kroppeb.stareval.expression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
public class BasicVariableExpression implements VariableExpression {
final private String name;
final private Type type;
public BasicVariableExpression(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public void evaluateTo(FunctionContext c, FunctionReturn r) {
c.getVariable(name).evaluateTo(c, r);
}
@Override
public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) {
if (context.hasVariable(this.name)) {
context.getVariable(this.name).evaluateTo(context, functionReturn);
return type.createConstant(functionReturn);
} else {
return this;
}
}
}
@@ -0,0 +1,84 @@
package kroppeb.stareval.expression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.TypedFunction;
import java.util.Collection;
public class CallExpression implements Expression {
private final TypedFunction function;
private final Expression[] arguments;
public CallExpression(TypedFunction function, Expression[] arguments) {
this.function = function;
this.arguments = arguments;
}
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
this.function.evaluateTo(this.arguments, context, functionReturn);
}
@Override
public void listVariables(Collection<? super VariableExpression> variables) {
for (Expression argument : this.arguments) {
argument.listVariables(variables);
}
}
private boolean isConstant() {
for (Expression i : arguments) {
if (!(i instanceof ConstantExpression)) {
return false;
}
}
return true;
}
@Override
public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) {
// the dirty way would be this
/*
try{
this.evaluateTo(context, functionReturn);
return this.function.getReturnType().createConstant(functionReturn);
}catch(Exception e){
return this;
}
*/
if (this.function.isPure() && isConstant()) {
this.evaluateTo(context, functionReturn);
return function.getReturnType().createConstant(functionReturn);
}
Expression[] partialEvaluatedParams = new Expression[this.arguments.length];
boolean allFullySimplified = true;
boolean noneSimplified = true;
for (int i = 0; i < this.arguments.length; i++) {
Expression simplified = this.arguments[i].partialEval(context, functionReturn);
if (simplified instanceof ConstantExpression) {
noneSimplified = false;
} else {
allFullySimplified = false;
if (simplified != this.arguments[i]) {
noneSimplified = false;
}
}
partialEvaluatedParams[i] = simplified;
}
if (this.function.isPure() && allFullySimplified) {
this.function.evaluateTo(partialEvaluatedParams, context, functionReturn);
return this.function.getReturnType().createConstant(functionReturn);
}
if (noneSimplified) {
return this;
}
return new CallExpression(this.function, partialEvaluatedParams);
}
}
@@ -0,0 +1,21 @@
package kroppeb.stareval.expression;
import kroppeb.stareval.function.Type;
import java.util.Collection;
public abstract class ConstantExpression implements Expression {
private final Type type;
protected ConstantExpression(Type type) {
this.type = type;
}
public Type getType() {
return this.type;
}
@Override
public void listVariables(Collection<? super VariableExpression> variables) {
}
}
@@ -0,0 +1,16 @@
package kroppeb.stareval.expression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionReturn;
import java.util.Collection;
public interface Expression {
void evaluateTo(FunctionContext context, FunctionReturn functionReturn);
default Expression partialEval(FunctionContext context, FunctionReturn functionReturn) {
return this;
}
void listVariables(Collection<? super VariableExpression> variables);
}
@@ -0,0 +1,10 @@
package kroppeb.stareval.expression;
import java.util.Collection;
public interface VariableExpression extends Expression {
@Override
default void listVariables(Collection<? super VariableExpression> variables) {
variables.add(this);
}
}
@@ -0,0 +1,67 @@
package kroppeb.stareval.function;
import java.util.Arrays;
import java.util.Objects;
public abstract class AbstractTypedFunction implements TypedFunction {
private final Type returnType;
private final Parameter[] parameters;
private final int priority;
private final boolean isPure;
public AbstractTypedFunction(Type returnType, Parameter[] parameters, int priority, boolean isPure) {
this.returnType = returnType;
this.parameters = parameters;
this.priority = priority;
this.isPure = isPure;
}
public AbstractTypedFunction(Type returnType, Type[] parameterType) {
this.returnType = returnType;
this.parameters = Arrays.stream(parameterType).map(Parameter::new).toArray(Parameter[]::new);
this.priority = 0;
this.isPure = true;
}
@Override
public Type getReturnType() {
return this.returnType;
}
@Override
public Parameter[] getParameters() {
return this.parameters;
}
@Override
public boolean isPure() {
return this.isPure;
}
@Override
public int priority() {
return this.priority;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AbstractTypedFunction func) {
return Objects.equals(returnType, func.returnType) &&
Arrays.equals(parameters, func.parameters) &&
priority == func.priority &&
isPure == func.isPure;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(returnType, Arrays.hashCode(parameters), priority, isPure);
}
@Override
public String toString() {
return TypedFunction.format(this, "unknown");
}
}
@@ -0,0 +1,26 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface B2BFunction extends TypedFunction {
boolean eval(boolean a);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
boolean a = functionReturn.booleanReturn;
functionReturn.booleanReturn = this.eval(a);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.BooleanParameter};
}
}
@@ -0,0 +1,29 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface BB2BFunction extends TypedFunction {
boolean eval(boolean a, boolean b);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
boolean a = functionReturn.booleanReturn;
params[1].evaluateTo(context, functionReturn);
boolean b = functionReturn.booleanReturn;
functionReturn.booleanReturn = this.eval(a, b);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.BooleanParameter, Type.BooleanParameter};
}
}
@@ -0,0 +1,36 @@
package kroppeb.stareval.function;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import java.util.Map;
public class BasicFunctionContext implements FunctionContext {
final private Map<String, Expression> variables = new Object2ObjectOpenHashMap<>();
public void setVariable(String name, Expression value) {
variables.put(name, value);
}
public void setIntVariable(String name, int value) {
setVariable(name, (VariableExpression) (c, r) -> r.intReturn = value);
}
public void setFloatVariable(String name, float value) {
setVariable(name, (VariableExpression) (c, r) -> r.floatReturn = value);
}
@Override
public Expression getVariable(String name) {
Expression expression = variables.get(name);
if (expression == null)
throw new RuntimeException("Variable hasn't been set: " + name);
return expression;
}
@Override
public boolean hasVariable(String name) {
return variables.containsKey(name);
}
}
@@ -0,0 +1,24 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface F2FFunction extends TypedFunction {
float eval(float a);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
functionReturn.floatReturn = this.eval(functionReturn.floatReturn);
}
@Override
default Type getReturnType() {
return Type.Float;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter};
}
}
@@ -0,0 +1,24 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface F2IFunction extends TypedFunction {
int eval(float a);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
functionReturn.intReturn = this.eval(functionReturn.floatReturn);
}
@Override
default Type getReturnType() {
return Type.Int;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter};
}
}
@@ -0,0 +1,29 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface FF2BFunction extends TypedFunction {
boolean eval(float a, float b);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
float a = functionReturn.floatReturn;
params[1].evaluateTo(context, functionReturn);
float b = functionReturn.floatReturn;
functionReturn.booleanReturn = this.eval(a, b);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter, Type.FloatParameter};
}
}
@@ -0,0 +1,29 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface FF2FFunction extends TypedFunction {
float eval(float a, float b);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
float a = functionReturn.floatReturn;
params[1].evaluateTo(context, functionReturn);
float b = functionReturn.floatReturn;
functionReturn.floatReturn = this.eval(a, b);
}
@Override
default Type getReturnType() {
return Type.Float;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter, Type.FloatParameter};
}
}
@@ -0,0 +1,32 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface FFF2BFunction extends TypedFunction {
boolean eval(float a, float b, float c);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
float a = functionReturn.floatReturn;
params[1].evaluateTo(context, functionReturn);
float b = functionReturn.floatReturn;
params[2].evaluateTo(context, functionReturn);
float c = functionReturn.floatReturn;
functionReturn.booleanReturn = this.eval(a, b, c);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter, Type.FloatParameter, Type.FloatParameter};
}
}
@@ -0,0 +1,32 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface FFF2FFunction extends TypedFunction {
float eval(float a, float b, float c);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
float a = functionReturn.floatReturn;
params[1].evaluateTo(context, functionReturn);
float b = functionReturn.floatReturn;
params[2].evaluateTo(context, functionReturn);
float c = functionReturn.floatReturn;
functionReturn.floatReturn = this.eval(a, b, c);
}
@Override
default Type getReturnType() {
return Type.Float;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.FloatParameter, Type.FloatParameter, Type.FloatParameter};
}
}
@@ -0,0 +1,9 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
public interface FunctionContext {
Expression getVariable(String name);
boolean hasVariable(String name);
}
@@ -0,0 +1,131 @@
package kroppeb.stareval.function;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class FunctionResolver {
private final Map<String, Map<Type, List<TypedFunction>>> functions;
// TODO: instead of a suplier we could use an int->function to make varargs
private final Map<String, Map<Type, List<Supplier<? extends TypedFunction>>>> dynamicFunctions;
public FunctionResolver(
Map<String, Map<Type, List<TypedFunction>>> functions,
Map<String, Map<Type, List<Supplier<? extends TypedFunction>>>> dynamicFunctions) {
this.functions = functions;
this.dynamicFunctions = dynamicFunctions;
}
public List<? extends TypedFunction> resolve(String name, Type returnType) {
Map<Type, List<TypedFunction>> normal = this.functions.get(name);
Map<Type, List<Supplier<? extends TypedFunction>>> dynamic = this.dynamicFunctions.get(name);
List<? extends TypedFunction> u = null;
if (normal == null && dynamic == null)
throw new RuntimeException("No such function: " + name);
if (normal != null)
u = normal.get(returnType);
if (dynamic != null) {
List<Supplier<? extends TypedFunction>> p = dynamic.get(returnType);
if (p != null) {
List<? extends TypedFunction> uDynamic = p.stream().map(Supplier::get).collect(Collectors.toList());
if (u == null) {
u = uDynamic;
} else {
List<TypedFunction> newU = new ArrayList<>(u.size() + uDynamic.size());
newU.addAll(u);
newU.addAll(uDynamic);
u = newU;
}
}
}
if (u == null)
return Collections.emptyList();
return u;
}
public void logAllFunctions() {
final Set<String> names = new LinkedHashSet<>();
names.addAll(this.functions.keySet());
names.addAll(this.dynamicFunctions.keySet());
for (final String name : names) {
final Map<Type, List<TypedFunction>> overloads = new Object2ObjectLinkedOpenHashMap<>();
Map<Type, List<TypedFunction>> normal = this.functions.get(name);
if (normal != null)
overloads.putAll(normal);
Map<Type, List<Supplier<? extends TypedFunction>>> dynamic = this.dynamicFunctions.get(name);
if (dynamic != null)
overloads.putAll(
dynamic
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> entry.getValue()
.stream()
.map(Supplier::get)
.collect(Collectors.toList())
)
)
);
for (Map.Entry<Type, List<TypedFunction>> returnTypeOverloads : overloads.entrySet()) {
for (TypedFunction typedFunction : returnTypeOverloads.getValue()) {
System.out.println(TypedFunction.format(typedFunction, name));
}
System.out.println();
}
System.out.println();
}
}
public static class Builder {
private final Map<String, List<TypedFunction>> functions = new Object2ObjectLinkedOpenHashMap<>();
private final Map<String, Map<Type, List<Supplier<? extends TypedFunction>>>> dynamicFunctions = new Object2ObjectLinkedOpenHashMap<>();
public <T extends TypedFunction> void add(String name, T function) {
this.addFunction(name, function);
}
public <T extends TypedFunction> void addDynamic(String name, Type returnType, Supplier<T> function) {
this.addDynamicFunction(name, returnType, function);
}
public void addDynamicFunction(String name, Type returnType, Supplier<? extends TypedFunction> function) {
this.dynamicFunctions
.computeIfAbsent(name, (n) -> new Object2ObjectLinkedOpenHashMap<>())
.computeIfAbsent(returnType, (n) -> new ObjectArrayList<>())
.add(function);
}
public void addFunction(String name, TypedFunction function) {
this.functions.computeIfAbsent(name, (n) -> new ObjectArrayList<>()).add(function);
}
public FunctionResolver build() {
Map<String, Map<Type, List<TypedFunction>>> functions = new Object2ObjectLinkedOpenHashMap<>();
for (Map.Entry<String, List<TypedFunction>> entry : this.functions.entrySet()) {
Map<Type, List<TypedFunction>> typeMap = new Object2ObjectLinkedOpenHashMap<>();
for (TypedFunction function : entry.getValue()) {
typeMap.computeIfAbsent(function.getReturnType(), i -> new ObjectArrayList<>())
.add(function);
}
functions.put(entry.getKey(), typeMap);
}
return new FunctionResolver(functions, this.dynamicFunctions);
}
}
}
@@ -0,0 +1,12 @@
package kroppeb.stareval.function;
public class FunctionReturn {
public boolean booleanReturn;
public byte byteReturn;
public short shortReturn;
public int intReturn;
public long longReturn;
public float floatReturn;
public double doubleReturn;
public Object objectReturn;
}
@@ -0,0 +1,24 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface I2FFunction extends TypedFunction {
float eval(int a);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
functionReturn.floatReturn = this.eval(functionReturn.intReturn);
}
@Override
default Type getReturnType() {
return Type.Float;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter};
}
}
@@ -0,0 +1,24 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface I2IFunction extends TypedFunction {
int eval(int a);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
functionReturn.intReturn = this.eval(functionReturn.intReturn);
}
@Override
default Type getReturnType() {
return Type.Int;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter};
}
}
@@ -0,0 +1,29 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface II2BFunction extends TypedFunction {
boolean eval(int a, int b);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
int a = functionReturn.intReturn;
params[1].evaluateTo(context, functionReturn);
int b = functionReturn.intReturn;
functionReturn.booleanReturn = this.eval(a, b);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter, Type.IntParameter};
}
}
@@ -0,0 +1,29 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface II2IFunction extends TypedFunction {
int eval(int a, int b);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
int a = functionReturn.intReturn;
params[1].evaluateTo(context, functionReturn);
int b = functionReturn.intReturn;
functionReturn.intReturn = this.eval(a, b);
}
@Override
default Type getReturnType() {
return Type.Int;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter, Type.IntParameter};
}
}
@@ -0,0 +1,32 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface III2BFunction extends TypedFunction {
boolean eval(int a, int b, int c);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
int a = functionReturn.intReturn;
params[1].evaluateTo(context, functionReturn);
int b = functionReturn.intReturn;
params[2].evaluateTo(context, functionReturn);
int c = functionReturn.intReturn;
functionReturn.booleanReturn = this.eval(a, b, c);
}
@Override
default Type getReturnType() {
return Type.Boolean;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter, Type.IntParameter, Type.IntParameter};
}
}
@@ -0,0 +1,32 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface III2IFunction extends TypedFunction {
int eval(int a, int b, int c);
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
params[0].evaluateTo(context, functionReturn);
int a = functionReturn.intReturn;
params[1].evaluateTo(context, functionReturn);
int b = functionReturn.intReturn;
params[2].evaluateTo(context, functionReturn);
int c = functionReturn.intReturn;
functionReturn.intReturn = this.eval(a, b, c);
}
@Override
default Type getReturnType() {
return Type.Int;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{Type.IntParameter, Type.IntParameter, Type.IntParameter};
}
}
@@ -0,0 +1,182 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.ConstantExpression;
import kroppeb.stareval.function.TypedFunction.Parameter;
import net.coderbot.iris.gl.uniform.UniformType;
import net.coderbot.iris.parsing.MatrixType;
import net.coderbot.iris.parsing.VectorType;
public abstract class Type {
public static final Boolean Boolean = new Boolean();
public static final Int Int = new Int();
public static final Float Float = new Float();
public static final Parameter BooleanParameter = new Parameter(Boolean);
public static final Parameter IntParameter = new Parameter(Int);
public static final Parameter FloatParameter = new Parameter(Float);
public static final Primitive[] AllPrimitives = {Type.Boolean, Type.Int, Type.Float};
public static UniformType convert(Type type) {
if (type == Type.Int || type == Type.Boolean) return UniformType.INT;
else if (type == Type.Float) return UniformType.FLOAT;
else if (type == VectorType.VEC2) return UniformType.VEC2;
else if (type == VectorType.VEC3) return UniformType.VEC3;
else if (type == VectorType.VEC4) return UniformType.VEC4;
else if (type == VectorType.I_VEC2) return UniformType.VEC2I;
else if (type == VectorType.I_VEC3) return UniformType.VEC3I;
else if (type == MatrixType.MAT4) return UniformType.MAT4;
else throw new IllegalArgumentException("Unsupported custom uniform type: " + type);
}
public abstract ConstantExpression createConstant(FunctionReturn functionReturn);
public abstract Object createArray(int length);
public abstract void setValueFromReturn(Object array, int index, FunctionReturn value);
public abstract void getValueFromArray(Object array, int index, FunctionReturn value);
public abstract String toString();
public abstract static class Primitive extends Type {
}
public static class ObjectType extends Type {
@Override
public ConstantExpression createConstant(FunctionReturn functionReturn) {
Object object = functionReturn.objectReturn;
return new ConstantExpression(this) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.objectReturn = object;
}
};
}
@Override
public Object createArray(int length) {
return new Object[length];
}
@Override
public void setValueFromReturn(Object array, int index, FunctionReturn value) {
Object[] arr = (Object[]) array;
arr[index] = value.objectReturn;
}
@Override
public void getValueFromArray(Object array, int index, FunctionReturn value) {
Object[] arr = (Object[]) array;
value.objectReturn = arr[index];
}
@Override
public String toString() {
return "Object";
}
}
public static class Boolean extends Primitive {
@Override
public ConstantExpression createConstant(FunctionReturn functionReturn) {
boolean value = functionReturn.booleanReturn;
return new ConstantExpression(this) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.booleanReturn = value;
}
};
}
@Override
public Object createArray(int length) {
return new boolean[length];
}
@Override
public void setValueFromReturn(Object array, int index, FunctionReturn value) {
boolean[] arr = (boolean[]) array;
arr[index] = value.booleanReturn;
}
@Override
public void getValueFromArray(Object array, int index, FunctionReturn value) {
boolean[] arr = (boolean[]) array;
value.booleanReturn = arr[index];
}
@Override
public String toString() {
return "bool";
}
}
public static class Int extends Primitive {
@Override
public ConstantExpression createConstant(FunctionReturn functionReturn) {
int value = functionReturn.intReturn;
return new ConstantExpression(this) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.intReturn = value;
}
};
}
@Override
public Object createArray(int length) {
return new int[length];
}
@Override
public void setValueFromReturn(Object array, int index, FunctionReturn value) {
int[] arr = (int[]) array;
arr[index] = value.intReturn;
}
@Override
public void getValueFromArray(Object array, int index, FunctionReturn value) {
int[] arr = (int[]) array;
value.intReturn = arr[index];
}
@Override
public String toString() {
return "int";
}
}
public static class Float extends Primitive {
@Override
public ConstantExpression createConstant(FunctionReturn functionReturn) {
float value = functionReturn.floatReturn;
return new ConstantExpression(this) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.floatReturn = value;
}
};
}
@Override
public Object createArray(int length) {
return new float[length];
}
@Override
public void setValueFromReturn(Object array, int index, FunctionReturn value) {
float[] arr = (float[]) array;
arr[index] = value.floatReturn;
}
@Override
public void getValueFromArray(Object array, int index, FunctionReturn value) {
float[] arr = (float[]) array;
value.floatReturn = arr[index];
}
@Override
public String toString() {
return "float";
}
}
}
@@ -0,0 +1,72 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
public interface TypedFunction {
static String format(TypedFunction function, String name) {
return String.format("%s %s(%s) (priority: %d, pure:%s)",
function.getReturnType().toString(),
name,
Arrays.stream(function.getParameters())
.map(param -> param.constant() ? "const " + param.type() : param.type().toString())
.collect(Collectors.joining(", ")),
function.priority(),
function.isPure() ? "yes" : "no"
);
}
Type getReturnType();
Parameter[] getParameters();
void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn);
default boolean isPure() {
return true;
}
default int priority() {
return 0;
}
class Parameter {
private final Type type;
private final boolean isConstant;
public Parameter(Type type, boolean isConstant) {
this.type = type;
this.isConstant = isConstant;
}
public Parameter(Type type) {
this(type, false);
}
public Type type() {
return this.type;
}
public boolean constant() {
return this.isConstant;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Parameter p) {
return Objects.equals(type, p.type) && Objects.equals(isConstant, p.isConstant);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(type) + 3192 + Objects.hashCode(isConstant);
}
}
}
@@ -0,0 +1,23 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface V2FFunction extends TypedFunction {
float eval();
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
functionReturn.floatReturn = this.eval();
}
@Override
default Type getReturnType() {
return Type.Float;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{};
}
}
@@ -0,0 +1,23 @@
package kroppeb.stareval.function;
import kroppeb.stareval.expression.Expression;
@FunctionalInterface
public interface V2IFunction extends TypedFunction {
int eval();
@Override
default void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) {
functionReturn.intReturn = this.eval();
}
@Override
default Type getReturnType() {
return Type.Int;
}
@Override
default Parameter[] getParameters() {
return new Parameter[]{};
}
}
@@ -1,20 +1,15 @@
package kroppeb.stareval.parser;
public class BinaryOp {
private final String name;
private final int priority;
import com.github.bsideup.jabel.Desugar;
@Desugar
public record BinaryOp(String name, int priority) {
public BinaryOp(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public String toString() {
return this.name + "{" + this.priority + "}";
}
public int getPriority() {
return this.priority;
}
}
@@ -7,6 +7,7 @@ import java.util.Map;
/**
* OpResolver maps the trailing characters identifying an operator to an actual operator.
*
* @param <T>
*/
abstract class OpResolver<T> {
@@ -27,7 +28,7 @@ abstract class OpResolver<T> {
* Adds a new multi-character operator. Calling this with an empty string is equivalent to calling singleChar.
*
* @param trailing every character after the first character of the operator.
* @param op the operator
* @param op the operator
*/
public void multiChar(String trailing, T op) {
T previous = map.put(trailing, op);
@@ -40,14 +41,14 @@ abstract class OpResolver<T> {
public OpResolver<T> build() {
if (map.size() > 2) {
throw new RuntimeException("unimplemented: Cannot currently build an optimized operator resolver " +
"tree when more than two operators start with the same character");
"tree when more than two operators start with the same character");
}
T singleChar = map.get("");
if (singleChar != null) {
if (map.size() == 1) {
return new SingleChar<>(singleChar);
return new OpResolver.SingleChar<>(singleChar);
} else {
for (Map.Entry<String, T> subEntry : map.entrySet()) {
if ("".equals(subEntry.getKey())) {
@@ -57,33 +58,33 @@ abstract class OpResolver<T> {
if (subEntry.getKey().length() != 1) {
throw new RuntimeException("unimplemented: Optimized operator resolver trees can " +
"currently only be built of operators that contain one or two characters.");
"currently only be built of operators that contain one or two characters.");
}
// We can assume that this is the only other entry in the map due to the size check above
return new SingleDualChar<>(
singleChar,
subEntry.getValue(),
subEntry.getKey().charAt(0)
return new OpResolver.SingleDualChar<>(
singleChar,
subEntry.getValue(),
subEntry.getKey().charAt(0)
);
}
}
} else {
if (map.size() > 1) {
throw new RuntimeException("unimplemented: Optimized operator resolver trees can currently only " +
"handle two operators starting with the same character if one operator is a single character");
"handle two operators starting with the same character if one operator is a single character");
}
for (Map.Entry<String, T> subEntry : map.entrySet()) {
if (subEntry.getKey().length() != 1) {
throw new RuntimeException("unimplemented: Optimized operator resolver trees can " +
"currently only be built of operators that contain one or two characters.");
"currently only be built of operators that contain one or two characters.");
}
// We can assume that this is the only entry in the map due to the size check above.
return new DualChar<>(
subEntry.getValue(),
subEntry.getKey().charAt(0)
return new OpResolver.DualChar<>(
subEntry.getValue(),
subEntry.getKey().charAt(0)
);
}
}
@@ -60,9 +60,13 @@ public class Parser {
Parser() {
}
public static ExpressionElement parse(String input, ParserOptions options) throws ParseException {
return Tokenizer.parse(input, options);
}
private Element peek() {
if (!this.stack.isEmpty()) {
return this.stack.get(this.stack.size() - 1);
return this.stack.get(this.stack.size() - 1);
}
return null;
@@ -115,6 +119,8 @@ public class Parser {
return token;
}
// visitor methods
/**
* Executes following reduce step:
* <ul>
@@ -134,8 +140,8 @@ public class Parser {
if (args == null) {
throw new MissingTokenException(
"Expected an opening bracket '(' before seeing a comma ',' or closing bracket ')'",
index
"Expected an opening bracket '(' before seeing a comma ',' or closing bracket ')'",
index
);
}
@@ -143,13 +149,11 @@ public class Parser {
((UnfinishedArgsExpression) args).tokens.add(expr);
} else {
throw new UnexpectedTokenException(
"Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " +
"closing bracket ')' or a comma ','", index);
"Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " +
"closing bracket ')' or a comma ','", index);
}
}
// visitor methods
void visitId(String id) {
this.push(new IdToken(id));
}
@@ -213,8 +217,8 @@ public class Parser {
if (!(pop instanceof UnfinishedArgsExpression)) {
throw new UnexpectedTokenException(
"Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " +
"closing bracket ')' or a comma ','", index);
"Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " +
"closing bracket ')' or a comma ','", index);
}
args = (UnfinishedArgsExpression) pop;
}
@@ -256,7 +260,7 @@ public class Parser {
*/
void visitBinaryOperator(BinaryOp binaryOp) {
// reduce the expressions to the needed priority level
ExpressionElement left = this.expressionReducePop(binaryOp.getPriority());
ExpressionElement left = this.expressionReducePop(binaryOp.priority());
// stack[ {'a', '*'}, 'b'], token = '+' -> stack[], left = {'a', '*', 'b'}
// -> stack[{{'a', '*', 'b'}, '+'}]
// stack[ {'a', '+'}, 'b'], token = '+' -> stack[], left = {'a', '+', 'b'}
@@ -287,8 +291,8 @@ public class Parser {
throw new MissingTokenException("Expected a closing bracket", endIndex);
} else {
throw new UnexpectedTokenException(
"The stack of tokens isn't empty at the end of the expression: " + this.stack +
" top: " + result, endIndex);
"The stack of tokens isn't empty at the end of the expression: " + this.stack +
" top: " + result, endIndex);
}
} else {
Element top = this.peek();
@@ -296,20 +300,16 @@ public class Parser {
throw new MissingTokenException("Expected a closing bracket", endIndex);
} else if (top instanceof PriorityOperatorElement) {
throw new MissingTokenException(
"Expected a identifier, constant or subexpression on the right side of the operator",
endIndex);
"Expected a identifier, constant or subexpression on the right side of the operator",
endIndex);
} else {
throw new UnexpectedTokenException(
"The stack of tokens contains an unexpected token at the top: " + this.stack,
endIndex);
"The stack of tokens contains an unexpected token at the top: " + this.stack,
endIndex);
}
}
} else {
throw new MissingTokenException("The input seems to be empty", endIndex);
}
}
public static ExpressionElement parse(String input, ParserOptions options) throws ParseException {
return Tokenizer.parse(input, options);
}
}
@@ -9,9 +9,9 @@ public final class ParserOptions {
private final TokenRules tokenRules;
private ParserOptions(
Char2ObjectMap<? extends OpResolver<? extends UnaryOp>> unaryOpResolvers,
Char2ObjectMap<? extends OpResolver<? extends BinaryOp>> binaryOpResolvers,
TokenRules tokenRules) {
Char2ObjectMap<? extends OpResolver<? extends UnaryOp>> unaryOpResolvers,
Char2ObjectMap<? extends OpResolver<? extends BinaryOp>> binaryOpResolvers,
TokenRules tokenRules) {
this.unaryOpResolvers = unaryOpResolvers;
this.binaryOpResolvers = binaryOpResolvers;
this.tokenRules = tokenRules;
@@ -29,52 +29,12 @@ public final class ParserOptions {
return this.binaryOpResolvers.get(c);
}
public static class Builder {
private final Char2ObjectMap<OpResolver.Builder<UnaryOp>> unaryOpResolvers = new Char2ObjectOpenHashMap<>();
private final Char2ObjectMap<OpResolver.Builder<BinaryOp>> binaryOpResolvers = new Char2ObjectOpenHashMap<>();
private TokenRules tokenRules = TokenRules.DEFAULT;
public void addUnaryOp(String s, UnaryOp op) {
char first = s.charAt(0);
String trailing = s.substring(1);
this.unaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op);
}
public void addBinaryOp(String s, BinaryOp op) {
char first = s.charAt(0);
String trailing = s.substring(1);
this.binaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op);
}
public void setTokenRules(TokenRules tokenRules) {
this.tokenRules = tokenRules;
}
private static <T> Char2ObjectMap<? extends OpResolver<? extends T>> buildOpResolvers(
Char2ObjectMap<OpResolver.Builder<T>> ops) {
Char2ObjectMap<OpResolver<T>> result = new Char2ObjectOpenHashMap<>();
ops.char2ObjectEntrySet().forEach(
entry -> result.put(entry.getCharKey(), entry.getValue().build()));
return result;
}
public ParserOptions build() {
return new ParserOptions(
buildOpResolvers(this.unaryOpResolvers),
buildOpResolvers(this.binaryOpResolvers),
this.tokenRules);
}
}
/**
* Defines a set of rules that allows the tokenizer to identify tokens within a string.
*/
public interface TokenRules {
TokenRules DEFAULT = new TokenRules() {};
TokenRules DEFAULT = new TokenRules() {
};
static boolean isNumber(final char c) {
return c >= '0' && c <= '9';
@@ -116,4 +76,45 @@ public final class ParserOptions {
return this.isAccessStart(c);
}
}
public static class Builder {
private final Char2ObjectMap<OpResolver.Builder<UnaryOp>> unaryOpResolvers = new Char2ObjectOpenHashMap<>();
private final Char2ObjectMap<OpResolver.Builder<BinaryOp>> binaryOpResolvers = new Char2ObjectOpenHashMap<>();
private TokenRules tokenRules = TokenRules.DEFAULT;
private static <T> Char2ObjectMap<? extends OpResolver<? extends T>> buildOpResolvers(
Char2ObjectMap<OpResolver.Builder<T>> ops) {
Char2ObjectMap<OpResolver<T>> result = new Char2ObjectOpenHashMap<>();
ops.char2ObjectEntrySet().forEach(
entry -> result.put(entry.getCharKey(), entry.getValue().build()));
return result;
}
public void addUnaryOp(String s, UnaryOp op) {
char first = s.charAt(0);
String trailing = s.substring(1);
this.unaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op);
}
public void addBinaryOp(String s, BinaryOp op) {
char first = s.charAt(0);
String trailing = s.substring(1);
this.binaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op);
}
public void setTokenRules(TokenRules tokenRules) {
this.tokenRules = tokenRules;
}
public ParserOptions build() {
return new ParserOptions(
buildOpResolvers(this.unaryOpResolvers),
buildOpResolvers(this.binaryOpResolvers),
this.tokenRules);
}
}
}
@@ -1,11 +1,10 @@
package kroppeb.stareval.parser;
public class UnaryOp {
private final String name;
import com.github.bsideup.jabel.Desugar;
@Desugar
public record UnaryOp(String name) {
public UnaryOp(String name) {
this.name = name;
}
@Override
public String toString() {
@@ -0,0 +1,320 @@
package kroppeb.stareval.resolver;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import kroppeb.stareval.element.ExpressionElement;
import kroppeb.stareval.element.token.IdToken;
import kroppeb.stareval.element.token.NumberToken;
import kroppeb.stareval.element.tree.AccessExpressionElement;
import kroppeb.stareval.element.tree.BinaryExpressionElement;
import kroppeb.stareval.element.tree.FunctionCall;
import kroppeb.stareval.element.tree.UnaryExpressionElement;
import kroppeb.stareval.expression.CallExpression;
import kroppeb.stareval.expression.ConstantExpression;
import kroppeb.stareval.expression.Expression;
import kroppeb.stareval.expression.VariableExpression;
import kroppeb.stareval.function.FunctionContext;
import kroppeb.stareval.function.FunctionResolver;
import kroppeb.stareval.function.FunctionReturn;
import kroppeb.stareval.function.Type;
import kroppeb.stareval.function.TypedFunction;
import kroppeb.stareval.function.TypedFunction.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class ExpressionResolver {
private final FunctionResolver functionResolver;
private final Function<String, Type> variableTypeMap;
private final boolean enableDebugging;
private final Map<String, ConstantExpression> numbers = new Object2ObjectOpenHashMap<>();
private List<String> logs;
public ExpressionResolver(FunctionResolver functionResolver, Function<String, Type> variableTypeMap) {
this(functionResolver, variableTypeMap, false);
}
public ExpressionResolver(FunctionResolver functionResolver, Function<String, Type> variableTypeMap, boolean enableDebugging) {
this.functionResolver = functionResolver;
this.variableTypeMap = variableTypeMap;
this.enableDebugging = enableDebugging;
}
public Expression resolveExpression(Type targetType, ExpressionElement expression) {
this.clearLogs();
Expression result = this.resolveExpressionInternal(targetType, expression, true, true);
if (result != null) {
return result;
}
throw new RuntimeException("Couldn't resolve: \n" + String.join("\n", this.extractLogs()));
}
Expression resolveCallExpressionInternal(
Type targetType,
String name,
List<? extends ExpressionElement> inner,
boolean implicit
) {
int innerLength = inner.size();
Expression result = null;
TypedFunction resultFunction = null;
functions:
for (TypedFunction f : this.functionResolver.resolve(name, targetType)) {
Parameter[] paramTypes = f.getParameters();
if (paramTypes.length != innerLength)
continue;
Expression[] params = new Expression[innerLength];
for (int i = 0; i < innerLength; i++) {
ExpressionElement paramExpression = inner.get(i);
Parameter param = paramTypes[i];
if (param.constant() && !(paramExpression instanceof NumberToken)) {
// not a constant
continue functions;
}
Expression expression = this.resolveExpressionInternal(param.type(), paramExpression,
!implicit || innerLength > 1, implicit);
if (expression == null)
continue functions;
params[i] = expression;
}
// FIXME
if (result != null && f.priority() == resultFunction.priority()) {
throw new RuntimeException("Ambiguity, \n\told: " + TypedFunction.format(resultFunction, "") + "\n\tnew: " + TypedFunction.format(f, ""));
} else if (resultFunction == null || f.priority() >= resultFunction.priority()) {
result = new CallExpression(f, params);
resultFunction = f;
}
}
return result;
}
private Expression resolveCallExpression(
Type targetType,
String name,
List<? extends ExpressionElement> inner,
boolean allowNonImplicit,
boolean allowImplicit) {
this.log("[DEBUG] resolving function %s with args %s to type %s",
name, inner, targetType);
Expression result = null;
if (allowNonImplicit) {
result = this.resolveCallExpressionInternal(targetType, name, inner, false);
}
if (result != null) {
this.log("[DEBUG] resolved function %s with args %s to type %s directly",
name, inner, targetType);
return result;
} else if (!allowImplicit) {
this.log("[DEBUG] Failed to resolve function %s with args %s to type %s directly",
name, inner, targetType);
return null;
}
List<? extends TypedFunction> casts = this.functionResolver.resolve("<cast>", targetType);
for (TypedFunction f : casts) {
Expression u = this.resolveCallExpression(f.getParameters()[0].type(), name, inner, true, true);
if (u == null)
continue;
if (result != null)
throw new RuntimeException("Ambiguity");
result = new CallExpression(f, new Expression[]{u});
}
if (result != null) {
this.log("[DEBUG] resolved function %s with args %s to type %s using only final cast",
name, inner, targetType);
return result;
}
result = this.resolveCallExpressionInternal(targetType, name, inner, true);
if (result != null) {
this.log("[DEBUG] resolved function %s with args %s to type %s using implicit inner casts",
name, inner, targetType);
} else {
this.log("[DEBUG] failed to resolve function %s with args %s to type %s",
name, inner, targetType);
}
return result;
}
public List<String> extractLogs() {
List<String> old = this.logs;
this.clearLogs();
return old;
}
public void clearLogs() {
this.logs = new ArrayList<>();
}
private void log(String str) {
if (this.enableDebugging)
this.logs.add(str);
}
private void log(String str, Object... args) {
if (this.enableDebugging)
this.logs.add(String.format(str, args));
}
private void log(Supplier<String> str) {
if (this.enableDebugging)
this.log(str.get());
}
private Expression resolveExpressionInternal(
Type targetType,
ExpressionElement expression,
boolean allowNonImplicit,
boolean allowImplicit) {
Expression castable;
Type innerType;
this.log("[DEBUG] resolving %s to type %s (%d%d)",
expression, targetType, allowNonImplicit ? 1 : 0, allowImplicit ? 1 : 0);
if (expression instanceof UnaryExpressionElement token) {
return this.resolveCallExpression(targetType, token.op().name(), Collections.singletonList(token.inner()),
allowNonImplicit, allowImplicit);
} else if (expression instanceof BinaryExpressionElement token) {
return this.resolveCallExpression(targetType, token.op().name(), Arrays.asList(token.left(), token.right()),
allowNonImplicit, allowImplicit);
} else if (expression instanceof FunctionCall token) {
return this.resolveCallExpression(targetType, token.id(), token.args(),
allowNonImplicit, allowImplicit);
} else if (expression instanceof AccessExpressionElement token) {
return this.resolveCallExpression(targetType, "<access$" + token.index() + ">",
Collections.singletonList(token.base()),
allowNonImplicit, allowImplicit);
} else if (expression instanceof NumberToken token) {
ConstantExpression exp = this.resolveNumber(token.getNumber());
if (exp.getType().equals(targetType)) {
this.log("[DEBUG] resolved constant %s to type %s", token.getNumber(), targetType);
return exp;
}
// TODO: implicit casting is split up too much
if (!allowImplicit) {
this.log("[DEBUG] failed to resolve constant %s (of type %s) to type %s without implicit casts",
token.getNumber(), exp.getType(), targetType);
return null;
}
this.log("[DEBUG] trying implicit casts to resolve constant %s (of type %s) to type %s",
token.getNumber(), exp.getType(), targetType);
castable = exp;
innerType = exp.getType();
} else if (expression instanceof IdToken token) {
final String name = token.getId();
Type type = this.variableTypeMap.apply(name);
if (type == null)
throw new RuntimeException("Unknown variable: " + name);
if (type.equals(targetType)) {
log("[DEBUG] resolved variable %s to type %s", name, targetType);
// TODO: We should add a variable provider (and have this as default)
// doing so would remove the need for a FunctionContext.
return new VariableExpression() {
@Override
public void evaluateTo(FunctionContext c, FunctionReturn r) {
c.getVariable(name).evaluateTo(c, r);
}
@Override
public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) {
return context.hasVariable(name) ? context.getVariable(name) : this;
}
};
}
if (!allowImplicit) {
log("[DEBUG] failed to resolve variable %s (of type %s) to type %s without implicit casts",
name, type, targetType);
return null;
}
// TODO duplicate of above
castable = new VariableExpression() {
@Override
public void evaluateTo(FunctionContext c, FunctionReturn r) {
c.getVariable(name).evaluateTo(c, r);
}
@Override
public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) {
return context.hasVariable(name) ? context.getVariable(name) : this;
}
};
innerType = type;
} else {
throw new RuntimeException("unexpected token: " + expression.toString());
}
List<? extends TypedFunction> casts = this.functionResolver.resolve("<cast>", targetType);
for (TypedFunction f : casts) {
if (f.getParameters()[0].type().equals(innerType)) {
this.log("[DEBUG] resolved %s to type %s using implicit casts",
expression, targetType);
return new CallExpression(f, new Expression[]{castable});
}
}
this.log("[DEBUG] failed to resolved %s to type %s, even using implicit casts", expression, targetType);
return null;
}
private ConstantExpression resolveNumber(String s) {
return this.numbers.computeIfAbsent(s, str -> {
NumberFormatException p;
try {
final int val;
if (str.length() >= 2 && str.charAt(0) == '0') {
switch (str.charAt(1)) {
case 'b': {
val = Integer.parseInt(str.substring(2), 2);
break;
}
case 'x': {
val = Integer.parseInt(str.substring(2), 16);
break;
}
default: {
val = Integer.parseInt(str.substring(1), 8);
break;
}
}
} else
val = Integer.parseInt(str);
return new ConstantExpression(Type.Int) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.intReturn = val;
}
};
} catch (NumberFormatException ex) {
p = ex;
}
try {
final float res = Float.parseFloat(str);
return new ConstantExpression(Type.Float) {
@Override
public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) {
functionReturn.floatReturn = res;
}
};
} catch (NumberFormatException ex) {
RuntimeException exception = new RuntimeException("Illegal number: " + str, ex);
exception.addSuppressed(p);
throw exception;
}
});
}
}
@@ -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;
}
}