Skip to content

Commit 2655de2

Browse files
committed
infer types from function calls
1 parent a41f773 commit 2655de2

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

src/webgl/ShaderGenerator.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ function shadergenerator(p5, fn) {
5858

5959
const ASTCallbacks = {
6060
VariableDeclarator(node, _state, _ancestors) {
61-
if (node.init.callee && node.init.callee.name.startsWith('uniform')) {
61+
if (node.init.callee && node.init.callee.name?.startsWith('uniform')) {
6262
const uniformNameLiteral = {
6363
type: 'Literal',
6464
value: node.id.name
@@ -344,11 +344,28 @@ function shadergenerator(p5, fn) {
344344
// Function Call Nodes
345345
class FunctionCallNode extends BaseNode {
346346
constructor(name, args, properties, isInternal = false) {
347-
let returnType = properties.returnType;
348-
if (returnType === 'genType') {
349-
returnType = args[0].type;
347+
let inferredType = args.find((arg, i) => {
348+
properties.args[i] === 'genType'
349+
&& isShaderNode(arg)
350+
})?.type;
351+
if (!inferredType) {
352+
let arrayArg = args.find(arg => Array.isArray(arg));
353+
inferredType = arrayArg ? `vec${arrayArg.length}` : undefined;
354+
}
355+
if (!inferredType) {
356+
inferredType = 'float';
357+
}
358+
args = args.map((arg, i) => {
359+
if (!isShaderNode(arg)) {
360+
const typeName = properties.args[i] === 'genType' ? inferredType : properties.args[i];
361+
arg = nodeConstructors[typeName](arg);
362+
}
363+
return arg;
364+
})
365+
if (properties.returnType === 'genType') {
366+
properties.returnType = inferredType;
350367
}
351-
super(isInternal, returnType);
368+
super(isInternal, properties.returnType);
352369
this.name = name;
353370
this.args = args;
354371
this.argumentTypes = properties.args;
@@ -741,7 +758,7 @@ function shadergenerator(p5, fn) {
741758
// genType clamp(genType x,
742759
// float minVal,
743760
// float maxVal);
744-
const builtInFunctions = {
761+
const builtInGLSLFunctions = {
745762
//////////// Trigonometry //////////
746763
'acos': { args: ['genType'], returnType: 'genType', isp5Function: true},
747764
'acosh': { args: ['genType'], returnType: 'genType', isp5Function: false},
@@ -804,7 +821,7 @@ function shadergenerator(p5, fn) {
804821
'texture': {args: ['sampler2D', 'vec2'], returnType: 'vec4', isp5Function: true},
805822
}
806823

807-
Object.entries(builtInFunctions).forEach(([functionName, properties]) => {
824+
Object.entries(builtInGLSLFunctions).forEach(([functionName, properties]) => {
808825
if (properties.isp5Function) {
809826
const originalFn = fn[functionName];
810827

0 commit comments

Comments
 (0)