p5
Version:
[](https://www.npmjs.com/package/p5)
430 lines (407 loc) • 23.1 kB
JavaScript
import { INSTANCE_ID_VARYING_NAME, NodeTypeToName, NodeType, OpCode, BaseType, OpCodeToSymbol, isStructType, StatementType, HOOK_PARAM_PREFIX, DataType, BlockType } from './strands/ir_types.js';
import { getNodeDataFromID, extractNodeTypeInfo } from './strands/ir_dag.js';
import { internalError } from './strands/strands_FES.js';
import { f as functionCallNode } from './ir_builders-CMXkjMoV.js';
var noiseGLSL = "// Based on https://github.com/stegu/webgl-noise/blob/22434e04d7753f7e949e8d724ab3da2864c17a0f/src/noise3D.glsl\n// MIT licensed, adapted for p5.strands\n\nvec3 mod289(vec3 x) {\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\n\nvec4 mod289(vec4 x) {\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\n\nvec4 permute(vec4 x) {\n return mod289(((x*34.0)+10.0)*x);\n}\n\nvec4 taylorInvSqrt(vec4 r)\n{\n return 1.79284291400159 - 0.85373472095314 * r;\n}\n\nfloat baseNoise(vec3 v)\n{\n const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;\n const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n\n // First corner\n vec3 i = floor(v + dot(v, C.yyy) );\n vec3 x0 = v - i + dot(i, C.xxx) ;\n\n // Other corners\n vec3 g = step(x0.yzx, x0.xyz);\n vec3 l = 1.0 - g;\n vec3 i1 = min( g.xyz, l.zxy );\n vec3 i2 = max( g.xyz, l.zxy );\n\n // x0 = x0 - 0.0 + 0.0 * C.xxx;\n // x1 = x0 - i1 + 1.0 * C.xxx;\n // x2 = x0 - i2 + 2.0 * C.xxx;\n // x3 = x0 - 1.0 + 3.0 * C.xxx;\n vec3 x1 = x0 - i1 + C.xxx;\n vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y\n vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y\n\n // Permutations\n i = mod289(i);\n vec4 p = permute( permute( permute(\n i.z + vec4(0.0, i1.z, i2.z, 1.0 ))\n + i.y + vec4(0.0, i1.y, i2.y, 1.0 ))\n + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));\n\n // Gradients: 7x7 points over a square, mapped onto an octahedron.\n // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)\n float n_ = 0.142857142857; // 1.0/7.0\n vec3 ns = n_ * D.wyz - D.xzx;\n\n vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)\n\n vec4 x_ = floor(j * ns.z);\n vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)\n\n vec4 x = x_ *ns.x + ns.yyyy;\n vec4 y = y_ *ns.x + ns.yyyy;\n vec4 h = 1.0 - abs(x) - abs(y);\n\n vec4 b0 = vec4( x.xy, y.xy );\n vec4 b1 = vec4( x.zw, y.zw );\n\n //vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;\n //vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;\n vec4 s0 = floor(b0)*2.0 + 1.0;\n vec4 s1 = floor(b1)*2.0 + 1.0;\n vec4 sh = -step(h, vec4(0.0));\n\n vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;\n vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;\n\n vec3 p0 = vec3(a0.xy,h.x);\n vec3 p1 = vec3(a0.zw,h.y);\n vec3 p2 = vec3(a1.xy,h.z);\n vec3 p3 = vec3(a1.zw,h.w);\n\n //Normalise gradients\n vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n p0 *= norm.x;\n p1 *= norm.y;\n p2 *= norm.z;\n p3 *= norm.w;\n\n // Mix final noise value\n vec4 m = max(0.5 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n m = m * m;\n return 105.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),\n dot(p2,x2), dot(p3,x3) ) );\n}\n\nfloat noise(vec3 st, int octaves, float ampFalloff) {\n float result = 0.0;\n float amplitude = 1.0;\n float frequency = 1.0;\n\n for (int i = 0; i < 8; i++) {\n if (i >= octaves) break;\n result += amplitude * baseNoise(st * frequency);\n frequency *= 2.0;\n amplitude *= ampFalloff;\n }\n return (result + 1.0) * 0.5;\n}\n";
var randomGLSL = "// _p5_hash: \"Hash without Sine\" by Dave Hoskins (https://www.shadertoy.com/view/4djSRW)\n// Mixing constants: R₂ sequence by Martin Roberts (https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)\n// α₁ = 1/φ₂ = 0.7548776662 (plastic constant reciprocal)\n// α₂ = 1/φ₂² = 0.5698402910\n// 1/φ = 0.6180339887 (golden ratio conjugate)\n\nint _p5_randomCallIndex = 0;\n\nfloat _p5_hash(vec3 p) {\n p = fract(p * vec3(0.1031, 0.1030, 0.0973));\n p += dot(p, p.yxz + 33.33);\n return fract((p.x + p.y) * p.z);\n}\n\nfloat random(float seed) {\n vec2 pixelCoord = gl_FragCoord.xy;\n float callIndex = float(_p5_randomCallIndex);\n _p5_randomCallIndex += 1;\n // fract(seed * α₁) normalizes large seeds (e.g. performance.now()) into [0,1)\n // and spreads them optimally via the R₂ sequence's plastic constant\n float s = fract(seed * 0.7548776662);\n return _p5_hash(vec3(\n pixelCoord.x + s,\n pixelCoord.y + callIndex * 0.5698402910,\n s + callIndex * 0.6180339887\n ));\n}\n";
var randomVertGLSL = "// _p5_hash: \"Hash without Sine\" by Dave Hoskins (https://www.shadertoy.com/view/4djSRW)\n// Mixing constants: R₂ sequence by Martin Roberts (https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)\n// α₁ = 1/φ₂ = 0.7548776662 (plastic constant reciprocal)\n// α₂ = 1/φ₂² = 0.5698402910\n// 1/φ = 0.6180339887 (golden ratio conjugate)\n\nint _p5_randomCallIndex = 0;\n\nfloat _p5_hash(vec3 p) {\n p = fract(p * vec3(0.1031, 0.1030, 0.0973));\n p += dot(p, p.yxz + 33.33);\n return fract((p.x + p.y) * p.z);\n}\n\nfloat random(float seed) {\n float vid = float(gl_VertexID);\n float callIndex = float(_p5_randomCallIndex);\n _p5_randomCallIndex += 1;\n float s = fract(seed * 0.7548776662);\n return _p5_hash(vec3(\n vid + s,\n vid * 0.5698402910 + callIndex * 0.6180339887,\n s + callIndex * 0.7548776662\n ));\n}\n";
function shouldCreateTemp(dag, nodeID) {
const nodeType = dag.nodeTypes[nodeID];
if (nodeType !== NodeType.OPERATION) return false;
if (dag.baseTypes[nodeID] === BaseType.SAMPLER2D) return false;
const uses = dag.usedBy[nodeID] || [];
return uses.length > 1;
}
const TypeNames = {
'float1': 'float',
'float2': 'vec2',
'float3': 'vec3',
'float4': 'vec4',
'int1': 'int',
'int2': 'ivec2',
'int3': 'ivec3',
'int4': 'ivec4',
'bool1': 'bool',
'bool2': 'bvec2',
'bool3': 'bvec3',
'bool4': 'bvec4',
'mat2': 'mat2x2',
'mat3': 'mat3x3',
'mat4': 'mat4x4',
};
const cfgHandlers = {
[BlockType.DEFAULT]: (blockID, strandsContext, generationContext) => {
const { dag, cfg } = strandsContext;
const instructions = cfg.blockInstructions[blockID] || [];
for (const nodeID of instructions) {
const nodeType = dag.nodeTypes[nodeID];
if (shouldCreateTemp(dag, nodeID)) {
const declaration = glslBackend.generateDeclaration(generationContext, dag, nodeID);
generationContext.write(declaration);
}
if (nodeType === NodeType.STATEMENT) {
glslBackend.generateStatement(generationContext, dag, nodeID);
}
if (nodeType === NodeType.ASSIGNMENT) {
glslBackend.generateAssignment(generationContext, dag, nodeID);
generationContext.visitedNodes.add(nodeID);
}
}
},
[BlockType.BRANCH](blockID, strandsContext, generationContext) {
const { dag, cfg } = strandsContext;
// Find all phi nodes in this branch block and declare them
const blockInstructions = cfg.blockInstructions[blockID] || [];
for (const nodeID of blockInstructions) {
const node = getNodeDataFromID(dag, nodeID);
if (node.nodeType === NodeType.PHI) {
// Check if the phi node's first dependency already has a temp name
const dependsOn = node.dependsOn || [];
if (dependsOn.length > 0) {
const firstDependency = dependsOn[0];
const existingTempName = generationContext.tempNames[firstDependency];
if (existingTempName) {
// Reuse the existing temp name instead of creating a new one
generationContext.tempNames[nodeID] = existingTempName;
continue; // Skip declaration, just alias to existing variable
}
}
// Otherwise, create a new temp variable for the phi node
const tmp = `T${generationContext.nextTempID++}`;
generationContext.tempNames[nodeID] = tmp;
const T = extractNodeTypeInfo(dag, nodeID);
const typeName = glslBackend.getTypeName(T.baseType, T.dimension);
generationContext.write(`${typeName} ${tmp};`);
}
}
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
},
[BlockType.IF_COND](blockID, strandsContext, generationContext) {
const { dag, cfg } = strandsContext;
const conditionID = cfg.blockConditions[blockID];
const condExpr = glslBackend.generateExpression(generationContext, dag, conditionID);
generationContext.write(`if (${condExpr})`);
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
},
[BlockType.ELSE_COND](blockID, strandsContext, generationContext) {
generationContext.write(`else`);
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
},
[BlockType.IF_BODY](blockID, strandsContext, generationContext) {
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
this.assignPhiNodeValues(blockID, strandsContext, generationContext);
},
[BlockType.SCOPE_START](blockID, strandsContext, generationContext) {
generationContext.write(`{`);
generationContext.indent++;
},
[BlockType.SCOPE_END](blockID, strandsContext, generationContext) {
generationContext.indent--;
generationContext.write(`}`);
},
[BlockType.MERGE](blockID, strandsContext, generationContext) {
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
},
[BlockType.FUNCTION](blockID, strandsContext, generationContext) {
this[BlockType.DEFAULT](blockID, strandsContext, generationContext);
},
[BlockType.FOR](blockID, strandsContext, generationContext) {
const { dag, cfg } = strandsContext;
const instructions = cfg.blockInstructions[blockID] || [];
generationContext.write(`for (`);
// Set flag to suppress semicolon on the last statement
const originalSuppressSemicolon = generationContext.suppressSemicolon;
for (let i = 0; i < instructions.length; i++) {
const nodeID = instructions[i];
const node = getNodeDataFromID(dag, nodeID);
const isLast = i === instructions.length - 1;
// Suppress semicolon on the last statement
generationContext.suppressSemicolon = isLast;
if (shouldCreateTemp(dag, nodeID)) {
const declaration = glslBackend.generateDeclaration(generationContext, dag, nodeID);
generationContext.write(declaration);
}
if (node.nodeType === NodeType.STATEMENT) {
glslBackend.generateStatement(generationContext, dag, nodeID);
}
if (node.nodeType === NodeType.ASSIGNMENT) {
glslBackend.generateAssignment(generationContext, dag, nodeID);
generationContext.visitedNodes.add(nodeID);
}
}
// Restore original flag
generationContext.suppressSemicolon = originalSuppressSemicolon;
generationContext.write(`)`);
},
assignPhiNodeValues(blockID, strandsContext, generationContext) {
const { dag, cfg } = strandsContext;
// Find all phi nodes that this block feeds into
const successors = cfg.outgoingEdges[blockID] || [];
for (const successorBlockID of successors) {
const instructions = cfg.blockInstructions[successorBlockID] || [];
for (const nodeID of instructions) {
const node = getNodeDataFromID(dag, nodeID);
if (node.nodeType === NodeType.PHI) {
// Find which input of this phi node corresponds to our block
const branchIndex = node.phiBlocks?.indexOf(blockID);
if (branchIndex !== -1 && branchIndex < node.dependsOn.length) {
const sourceNodeID = node.dependsOn[branchIndex];
const tempName = generationContext.tempNames[nodeID];
if (tempName && sourceNodeID !== null) {
const sourceExpr = glslBackend.generateExpression(generationContext, dag, sourceNodeID);
generationContext.write(`${tempName} = ${sourceExpr};`);
}
}
}
}
}
},
};
const glslBackend = {
hookEntry(hookType) {
const firstLine = `(${hookType.parameters.flatMap((param) => {
return `${param.qualifiers?.length ? param.qualifiers.join(' ') : ''}${param.type.typeName} ${HOOK_PARAM_PREFIX}${param.name}`;
}).join(', ')}) {`;
return firstLine;
},
getNoiseShaderSnippet() {
return noiseGLSL;
},
getRandomFragmentShaderSnippet() {
return randomGLSL;
},
getRandomVertexShaderSnippet() {
return randomVertGLSL;
},
getTypeName(baseType, dimension) {
const primitiveTypeName = TypeNames[baseType + dimension];
if (!primitiveTypeName) {
return baseType;
}
return primitiveTypeName;
},
generateHookUniformKey(name, typeInfo) {
return `${this.getTypeName(typeInfo.baseType, typeInfo.dimension)} ${name}`;
},
generateVaryingVariable(varName, typeInfo) {
return `${typeInfo.fnName} ${varName}`;
},
generateLocalDeclaration(varName, typeInfo) {
const typeName = typeInfo.fnName;
return `${typeName} ${varName};`;
},
generateStatement(generationContext, dag, nodeID) {
const node = getNodeDataFromID(dag, nodeID);
// Generate the expression followed by semicolon (unless suppressed)
const semicolon = generationContext.suppressSemicolon ? '' : ';';
if (node.statementType === StatementType.DISCARD) {
generationContext.write(`discard${semicolon}`);
} else if (node.statementType === StatementType.BREAK) {
generationContext.write(`break${semicolon}`);
} else if (node.statementType === StatementType.EXPRESSION) {
const exprNodeID = node.dependsOn[0];
const expr = this.generateExpression(generationContext, dag, exprNodeID);
generationContext.write(`${expr}${semicolon}`);
} else if (node.statementType === StatementType.EMPTY) {
generationContext.write(semicolon);
} else if (node.statementType === StatementType.EARLY_RETURN) {
const exprNodeID = node.dependsOn[0];
const expr = this.generateExpression(generationContext, dag, exprNodeID);
generationContext.write(`return ${expr}${semicolon}`);
}
},
generateAssignment(generationContext, dag, nodeID) {
const node = getNodeDataFromID(dag, nodeID);
// dependsOn[0] = targetNodeID, dependsOn[1] = sourceNodeID
const targetNodeID = node.dependsOn[0];
const sourceNodeID = node.dependsOn[1];
// Generate the target expression (could be variable or swizzle)
const targetExpr = this.generateExpression(generationContext, dag, targetNodeID);
const sourceExpr = this.generateExpression(generationContext, dag, sourceNodeID);
const semicolon = generationContext.suppressSemicolon ? '' : ';';
// Generate assignment if we have both target and source
if (targetExpr && sourceExpr && targetExpr !== sourceExpr) {
generationContext.write(`${targetExpr} = ${sourceExpr}${semicolon}`);
}
},
generateDeclaration(generationContext, dag, nodeID) {
const expr = this.generateExpression(generationContext, dag, nodeID);
const tmp = `T${generationContext.nextTempID++}`;
generationContext.tempNames[nodeID] = tmp;
const T = extractNodeTypeInfo(dag, nodeID);
const typeName = this.getTypeName(T.baseType, T.dimension);
return `${typeName} ${tmp} = ${expr};`;
},
generateReturnStatement(strandsContext, generationContext, rootNodeID, returnType) {
if (!returnType) {
generationContext.write('return;');
return;
}
const dag = strandsContext.dag;
const rootNode = getNodeDataFromID(dag, rootNodeID);
if (isStructType(returnType) && rootNode.identifier) {
const structTypeInfo = returnType;
for (let i = 0; i < structTypeInfo.properties.length; i++) {
const prop = structTypeInfo.properties[i];
const val = this.generateExpression(generationContext, dag, rootNode.dependsOn[i]);
if (prop.name !== val) {
generationContext.write(
`${rootNode.identifier}.${prop.name} = ${val};`
);
}
}
}
generationContext.write(`return ${this.generateExpression(generationContext, dag, rootNodeID)};`);
},
generateExpression(generationContext, dag, nodeID) {
const node = getNodeDataFromID(dag, nodeID);
if (generationContext.tempNames?.[nodeID]) {
return generationContext.tempNames[nodeID];
}
switch (node.nodeType) {
case NodeType.LITERAL:
if (node.baseType === BaseType.FLOAT) {
return node.value.toFixed(4);
}
else {
return node.value;
}
case NodeType.VARIABLE:
// Track shared variable usage context
if (generationContext.shaderContext && generationContext.strandsContext?.sharedVariables?.has(node.identifier)) {
const sharedVar = generationContext.strandsContext.sharedVariables.get(node.identifier);
if (generationContext.shaderContext === 'vertex') {
sharedVar.usedInVertex = true;
} else if (generationContext.shaderContext === 'fragment') {
sharedVar.usedInFragment = true;
}
}
// Detect instanceID usage in fragment context and rewrite to varying name
if (node.identifier === this.instanceIdReference() && generationContext.shaderContext === 'fragment') {
generationContext.strandsContext._instanceIDUsedInFragment = true;
return INSTANCE_ID_VARYING_NAME;
}
return node.identifier;
case NodeType.OPERATION:
const useParantheses = node.usedBy.length > 0;
if (node.opCode === OpCode.Nary.CONSTRUCTOR) {
// TODO: differentiate casts and constructors for more efficient codegen.
// if (node.dependsOn.length === 1 && node.dimension === 1) {
// return this.generateExpression(generationContext, dag, node.dependsOn[0]);
// }
if (node.baseType === BaseType.SAMPLER2D) {
return this.generateExpression(generationContext, dag, node.dependsOn[0]);
}
const T = this.getTypeName(node.baseType, node.dimension);
const deps = node.dependsOn.map((dep) => this.generateExpression(generationContext, dag, dep));
return `${T}(${deps.join(', ')})`;
}
if (node.opCode === OpCode.Nary.FUNCTION_CALL) {
const functionArgs = node.dependsOn.map(arg =>this.generateExpression(generationContext, dag, arg));
return `${node.identifier}(${functionArgs.join(', ')})`;
}
if (node.opCode === OpCode.Nary.TERNARY) {
const [condID, trueID, falseID] = node.dependsOn;
const cond = this.generateExpression(generationContext, dag, condID);
const trueExpr = this.generateExpression(generationContext, dag, trueID);
const falseExpr = this.generateExpression(generationContext, dag, falseID);
return `(${cond} ? ${trueExpr} : ${falseExpr})`;
}
if (node.opCode === OpCode.Binary.MEMBER_ACCESS) {
const [lID, rID] = node.dependsOn;
const lName = this.generateExpression(generationContext, dag, lID);
const rName = this.generateExpression(generationContext, dag, rID);
return `${lName}.${rName}`;
}
if (node.opCode === OpCode.Unary.SWIZZLE) {
const parentID = node.dependsOn[0];
const parentExpr = this.generateExpression(generationContext, dag, parentID);
return `${parentExpr}.${node.swizzle}`;
}
if (node.opCode === OpCode.Binary.ARRAY_ACCESS) {
const [bufferID, indexID] = node.dependsOn;
const bufferExpr = this.generateExpression(generationContext, dag, bufferID);
const indexExpr = this.generateExpression(generationContext, dag, indexID);
return `${bufferExpr}[${indexExpr}]`;
}
if (node.dependsOn.length === 2) {
const [lID, rID] = node.dependsOn;
const left = this.generateExpression(generationContext, dag, lID);
const right = this.generateExpression(generationContext, dag, rID);
// Special case for modulo: use mod() function for floats in GLSL
if (node.opCode === OpCode.Binary.MODULO) {
const leftNode = getNodeDataFromID(dag, lID);
const rightNode = getNodeDataFromID(dag, rID);
// If either operand is float, use mod() function
if (leftNode.baseType === BaseType.FLOAT || rightNode.baseType === BaseType.FLOAT) {
return `mod(${left}, ${right})`;
}
// For integers, use % operator
return `(${left} % ${right})`;
}
const opSym = OpCodeToSymbol[node.opCode];
if (useParantheses) {
return `(${left} ${opSym} ${right})`;
} else {
return `${left} ${opSym} ${right}`;
}
}
if (node.opCode === OpCode.Unary.LOGICAL_NOT
|| node.opCode === OpCode.Unary.NEGATE
|| node.opCode === OpCode.Unary.PLUS
) {
const [i] = node.dependsOn;
const val = this.generateExpression(generationContext, dag, i);
const sym = OpCodeToSymbol[node.opCode];
return `${sym}${val}`;
}
case NodeType.PHI:
// Phi nodes represent conditional merging of values
// If this phi node has an identifier (like varying variables), use that
if (node.identifier) {
return node.identifier;
}
// Otherwise, they should have been declared as temporary variables
// and assigned in the appropriate branches
if (generationContext.tempNames?.[nodeID]) {
return generationContext.tempNames[nodeID];
} else {
// If no temp was created, this phi node only has one input
// so we can just use that directly
const validInputs = node.dependsOn.filter(id => id !== null);
if (validInputs.length > 0) {
return this.generateExpression(generationContext, dag, validInputs[0]);
} else {
throw new Error(`No valid inputs for node`)
}
}
case NodeType.ASSIGNMENT:
internalError(`ASSIGNMENT nodes should not be used as expressions`);
default:
internalError(`${NodeTypeToName[node.nodeType]} code generation not implemented yet`);
}
},
generateBlock(blockID, strandsContext, generationContext) {
const type = strandsContext.cfg.blockTypes[blockID];
const handler = cfgHandlers[type] || cfgHandlers[BlockType.DEFAULT];
handler.call(cfgHandlers, blockID, strandsContext, generationContext);
},
createGetTextureCall(strandsContext, args) {
// In GLSL, getTexture is straightforward - just pass through the args
// First argument should be a texture (sampler2D), second should be coordinates
const { id, dimension } = functionCallNode(strandsContext, 'getTexture', args, {
overloads: [{
params: [DataType.sampler2D, DataType.float2],
returnType: DataType.float4
}]
});
return { id, dimension };
},
instanceIdReference() {
return 'gl_InstanceID';
},
generateInstanceIDVarying() {
return { name: INSTANCE_ID_VARYING_NAME, declaration: `int ${INSTANCE_ID_VARYING_NAME}`, source: 'gl_InstanceID', interpolation: 'flat' };
},
};
export { randomVertGLSL as a, glslBackend as g, randomGLSL as r };