p5
Version:
[](https://www.npmjs.com/package/p5)
62 lines (61 loc) • 3.02 kB
JavaScript
import { structType } from "./ir_types.js";
import { sortCFG } from "./ir_cfg.js";
//#region src/strands/strands_codegen.js
function generateShaderCode(strandsContext) {
const { cfg, backend, vertexDeclarations, fragmentDeclarations, computeDeclarations } = strandsContext;
const hooksObj = {
uniforms: {},
storageUniforms: {},
varyingVariables: [],
shaderNameMap: strandsContext.shaderNameMap,
shaderNameState: strandsContext.shaderNameState
};
for (const { name, typeInfo, defaultValue } of strandsContext.uniforms) if (typeInfo.baseType === "storage") {
if (defaultValue !== null && defaultValue !== void 0) hooksObj.storageUniforms[name] = defaultValue;
} else {
const key = backend.generateHookUniformKey(name, typeInfo);
if (key !== null) hooksObj.uniforms[key] = defaultValue;
}
if (backend.addTextureBindingsToDeclarations) backend.addTextureBindingsToDeclarations(strandsContext);
if (backend.addStorageBufferBindingsToDeclarations) backend.addStorageBufferBindingsToDeclarations(strandsContext);
for (const { hookType, rootNodeID, entryBlockID, shaderContext } of strandsContext.hooks) {
const generationContext = {
indent: 1,
codeLines: [],
write(line) {
this.codeLines.push(" ".repeat(this.indent) + line);
},
tempNames: {},
declarations: [],
nextTempID: 0,
visitedNodes: /* @__PURE__ */ new Set(),
shaderContext,
strandsContext
};
const blocks = sortCFG(cfg.outgoingEdges, entryBlockID);
for (const blockID of blocks) backend.generateBlock(blockID, strandsContext, generationContext);
const firstLine = backend.hookEntry(hookType);
let returnType;
if (hookType.returnType.properties) returnType = structType(hookType.returnType);
else if (!hookType.returnType.dataType || hookType.returnType.typeName?.trim() === "void") returnType = null;
else returnType = hookType.returnType.dataType;
if (rootNodeID !== void 0) backend.generateReturnStatement(strandsContext, generationContext, rootNodeID, returnType);
hooksObj[`${hookType.returnType.typeName} ${hookType.name}`] = [
firstLine,
...generationContext.codeLines,
"}"
].join("\n");
}
if (strandsContext.sharedVariables) {
for (const [varName, varInfo] of strandsContext.sharedVariables) if (varInfo.usedInVertex && varInfo.usedInFragment) hooksObj.varyingVariables.push(backend.generateVaryingVariable(varName, varInfo.typeInfo));
else if (varInfo.usedInVertex) vertexDeclarations.add(backend.generateLocalDeclaration(varName, varInfo.typeInfo));
else if (varInfo.usedInFragment) fragmentDeclarations.add(backend.generateLocalDeclaration(varName, varInfo.typeInfo));
}
if (strandsContext._instanceIDUsedInFragment) hooksObj.instanceIDVarying = backend.generateInstanceIDVarying();
hooksObj.vertexDeclarations = [...vertexDeclarations].join("\n");
hooksObj.fragmentDeclarations = [...fragmentDeclarations].join("\n");
hooksObj.computeDeclarations = [...computeDeclarations].join("\n");
return hooksObj;
}
//#endregion
export { generateShaderCode };