UNPKG

gpu.js

Version:

GPU Accelerated JavaScript

28 lines 300 kB
/** * gpu.js * http://gpu.rocks/ * * GPU Accelerated JavaScript * * @version 2.16.0 * @date Wed Nov 16 2022 15:48:39 GMT-0500 (Eastern Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2022 gpu.js Team *//** * gpu.js * http://gpu.rocks/ * * GPU Accelerated JavaScript * * @version 2.16.0 * @date Wed Nov 16 2022 15:48:37 GMT-0500 (Eastern Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2022 gpu.js Team */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).GPU=e()}}((function(){return function e(t,n,r){function i(a,o){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!o&&u)return u(a,!0);if(s)return s(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,(function(e){return i(t[a][1][e]||e)}),c,c.exports,e,t,n,r)}return n[a].exports}for(var s="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(e,t,n){},{}],2:[function(e,t,n){function r(e,t={}){const{contextName:n="gl",throwGetError:r,useTrackablePrimitives:o,readPixelsFile:u,recording:l=[],variables:c={},onReadPixels:h,onUnrecognizedArgumentLookup:p}=t,d=new Proxy(e,{get:function(t,d){switch(d){case"addComment":return w;case"checkThrowError":return D;case"getReadPixelsVariableName":return f;case"insertVariable":return A;case"reset":return b;case"setIndent":return v;case"toString":return T;case"getContextVariableName":return F}if("function"==typeof e[d])return function(){switch(d){case"getError":return r?l.push(`${y}if (${n}.getError() !== ${n}.NONE) throw new Error('error');`):l.push(`${y}${n}.getError();`),e.getError();case"getExtension":{const t=`${n}Variables${m.length}`;l.push(`${y}const ${t} = ${n}.getExtension('${arguments[0]}');`);const r=e.getExtension(arguments[0]);if(r&&"object"==typeof r){const e=i(r,{getEntity:S,useTrackablePrimitives:o,recording:l,contextName:t,contextVariables:m,variables:c,indent:y,onUnrecognizedArgumentLookup:p});return m.push(e),e}return m.push(null),r}case"readPixels":const t=m.indexOf(arguments[6]);let a;if(-1===t){const e=I(arguments[6]);e?(a=e,l.push(`${y}${e}`)):(a=`${n}Variable${m.length}`,m.push(arguments[6]),l.push(`${y}const ${a} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else a=`${n}Variable${t}`;f=a;const d=[arguments[0],arguments[1],arguments[2],arguments[3],S(arguments[4]),S(arguments[5]),a];return l.push(`${y}${n}.readPixels(${d.join(", ")});`),u&&E(arguments[2],arguments[3]),h&&h(a,d),e.readPixels.apply(e,arguments);case"drawBuffers":return l.push(`${y}${n}.drawBuffers([${s(arguments[0],{contextName:n,contextVariables:m,getEntity:S,addVariable:_,variables:c,onUnrecognizedArgumentLookup:p})}]);`),e.drawBuffers(arguments[0])}let t=e[d].apply(e,arguments);switch(typeof t){case"undefined":return void l.push(`${y}${$(d,arguments)};`);case"number":case"boolean":if(o&&-1===m.indexOf(a(t))){l.push(`${y}const ${n}Variable${m.length} = ${$(d,arguments)};`),m.push(t=a(t));break}default:null===t?l.push(`${$(d,arguments)};`):l.push(`${y}const ${n}Variable${m.length} = ${$(d,arguments)};`),m.push(t)}return t};return g[e[d]]=d,e[d]}}),m=[],g={};let f,x=0,y="";return d;function T(){return l.join("\n")}function b(){for(;l.length>0;)l.pop()}function A(e,t){c[e]=t}function S(e){const t=g[e];return t?n+"."+t:e}function v(e){y=" ".repeat(e)}function _(e,t){const r=`${n}Variable${m.length}`;return l.push(`${y}const ${r} = ${t};`),m.push(e),r}function E(e,t){const r=`${n}Variable${m.length}`,i=`imageDatum${x}`;l.push(`${y}let ${i} = ["P3\\n# ${u}.ppm\\n", ${e}, ' ', ${t}, "\\n255\\n"].join("");`),l.push(`${y}for (let i = 0; i < ${i}.length; i += 4) {`),l.push(`${y} ${i} += ${r}[i] + ' ' + ${r}[i + 1] + ' ' + ${r}[i + 2] + ' ';`),l.push(`${y}}`),l.push(`${y}if (typeof require !== "undefined") {`),l.push(`${y} require('fs').writeFileSync('./${u}.ppm', ${i});`),l.push(`${y}}`),x++}function w(e){l.push(`${y}// ${e}`)}function D(){l.push(`${y}(() => {\n${y}const error = ${n}.getError();\n${y}if (error !== ${n}.NONE) {\n${y} const names = Object.getOwnPropertyNames(gl);\n${y} for (let i = 0; i < names.length; i++) {\n${y} const name = names[i];\n${y} if (${n}[name] === error) {\n${y} throw new Error('${n} threw ' + name);\n${y} }\n${y} }\n${y}}\n${y}})();`)}function $(e,t){return`${n}.${e}(${s(t,{contextName:n,contextVariables:m,getEntity:S,addVariable:_,variables:c,onUnrecognizedArgumentLookup:p})})`}function I(e){if(c)for(const t in c)if(c[t]===e)return t;return null}function F(e){const t=m.indexOf(e);return-1!==t?`${n}Variable${t}`:null}}function i(e,t){const n=new Proxy(e,{get:function(t,n){if("function"==typeof t[n])return function(){if("drawBuffersWEBGL"===n)return c.push(`${p}${i}.drawBuffersWEBGL([${s(arguments[0],{contextName:i,contextVariables:o,getEntity:m,addVariable:f,variables:h,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[n].apply(e,arguments);switch(typeof t){case"undefined":return void c.push(`${p}${g(n,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(a(t))?(c.push(`${p}const ${i}Variable${o.length} = ${g(n,arguments)};`),o.push(t=a(t))):(c.push(`${p}const ${i}Variable${o.length} = ${g(n,arguments)};`),o.push(t));break;default:null===t?c.push(`${g(n,arguments)};`):c.push(`${p}const ${i}Variable${o.length} = ${g(n,arguments)};`),o.push(t)}return t};return r[e[n]]=n,e[n]}}),r={},{contextName:i,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:c,variables:h,indent:p,onUnrecognizedArgumentLookup:d}=t;return n;function m(e){return r.hasOwnProperty(e)?`${i}.${r[e]}`:u(e)}function g(e,t){return`${i}.${e}(${s(t,{contextName:i,contextVariables:o,getEntity:m,addVariable:f,variables:h,onUnrecognizedArgumentLookup:d})})`}function f(e,t){const n=`${i}Variable${o.length}`;return o.push(e),c.push(`${p}const ${n} = ${t};`),n}}function s(e,t){const{variables:n,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map((e=>{const i=function(e){if(n)for(const t in n)if(n.hasOwnProperty(t)&&n[t]===e)return t;if(r)return r(e);return null}(e);return i||function(e,t){const{contextName:n,contextVariables:r,getEntity:i,addVariable:s,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${n}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),n=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":n&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return i(e);case"Array":return s(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return s(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)})).join(", ")}function a(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:i}),"undefined"!=typeof window&&(r.glExtensionWiretap=i,window.glWiretap=r)},{}],3:[function(e,t,n){function r(e){const t=new Array(e.length);for(let n=0;n<e.length;n++){const r=e[n];r.toArray?t[n]=r.toArray():t[n]=r}return t}function i(){const e=r(arguments),t=new Float32Array(this.output.x);for(let n=0;n<this.output.x;n++)this.thread.x=n,this.thread.y=0,this.thread.z=0,t[n]=this._fn.apply(this,e);return t}function s(){const e=r(arguments),t=new Array(this.output.y);for(let n=0;n<this.output.y;n++){const r=new Float32Array(this.output.x);for(let t=0;t<this.output.x;t++)this.thread.x=t,this.thread.y=n,this.thread.z=0,r[t]=this._fn.apply(this,e);t[n]=r}return t}function a(){const e=r(arguments);for(let t=0;t<this.output.y;t++)for(let n=0;n<this.output.x;n++)this.thread.x=n,this.thread.y=t,this.thread.z=0,this._fn.apply(this,e)}function o(){const e=r(arguments),t=new Array(this.output.z);for(let n=0;n<this.output.z;n++){const r=new Array(this.output.y);for(let t=0;t<this.output.y;t++){const i=new Float32Array(this.output.x);for(let r=0;r<this.output.x;r++)this.thread.x=r,this.thread.y=t,this.thread.z=n,i[r]=this._fn.apply(this,e);r[t]=i}t[n]=r}return t}function u(e){e.setOutput=t=>{e.output=c(t),e.graphical&&l(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&l(e),e.exec=function(){return new Promise(((t,n)=>{try{t(e.apply(e,arguments))}catch(e){n(e)}}))},e.getPixels=t=>{const{x:n,y:r}=e.output;return t?function(e,t,n){const r=n/2|0,i=4*t,s=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;e<r;++e){const t=e*i,r=(n-e-1)*i;s.set(a.subarray(t,t+i)),a.copyWithin(t,r,r+i),a.set(s,r)}return a}(e._imageData.data,n,r):e._imageData.data.slice(0)},e.color=function(t,n,r,i){void 0===i&&(i=1),t=Math.floor(255*t),n=Math.floor(255*n),r=Math.floor(255*r),i=Math.floor(255*i);const s=e.output.x,a=e.output.y,o=e.thread.x+(a-e.thread.y-1)*s;e._colorData[4*o+0]=t,e._colorData[4*o+1]=n,e._colorData[4*o+2]=r,e._colorData[4*o+3]=i};const t=()=>e,n=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r<n.length;r++)e[n[r]]=t;return e}function l(e){const{x:t,y:n}=e.output;if(e.context&&e.context.createImageData){const r=new Uint8ClampedArray(t*n*4);e._imageData=e.context.createImageData(t,n),e._colorData=r}else{const r=new Uint8ClampedArray(t*n*4);e._imageData={data:r},e._colorData=r}}function c(e){let t=null;if(e.length)if(3===e.length){const[n,r,i]=e;t={x:n,y:r,z:i}}else if(2===e.length){const[n,r]=e;t={x:n,y:r}}else{const[n]=e;t={x:n}}else t=e;return t}t.exports={gpuMock:function(e,t={}){const n=t.output?c(t.output):null;function r(){return r.output.z?o.apply(r,arguments):r.output.y?r.graphical?a.apply(r,arguments):s.apply(r,arguments):i.apply(r,arguments)}return r._fn=e,r.constants=t.constants||null,r.context=t.context||null,r.canvas=t.canvas||null,r.graphical=t.graphical||!1,r._imageData=null,r._colorData=null,r.output=n,r.thread={x:0,y:0,z:0},u(r)}}},{}],4:[function(e,t,n){const{utils:r}=e("./utils");t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}},{"./utils":113}],5:[function(e,t,n){const{FunctionNode:r}=e("../function-node");t.exports={CPUFunctionNode:class extends r{astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e<this.argumentNames.length;++e){const n=this.argumentNames[e];e>0&&t.push(", "),t.push("user_"),t.push(n)}t.push(") {\n")}for(let n=0;n<e.body.body.length;++n)this.astGeneric(e.body.body[n],t),t.push("\n");return this.isRootKernel||t.push("}\n"),t}astReturnStatement(e,t){const n=this.returnType||this.getType(e.argument);return this.returnType||(this.returnType=n),this.isRootKernel?(t.push(this.leadingReturnStatement),this.astGeneric(e.argument,t),t.push(";\n"),t.push(this.followingReturnStatement),t.push("continue;\n")):this.isSubKernel?(t.push(`subKernelResult_${this.name} = `),this.astGeneric(e.argument,t),t.push(";"),t.push(`return subKernelResult_${this.name};`)):(t.push("return "),this.astGeneric(e.argument,t),t.push(";")),t}astLiteral(e,t){if(isNaN(e.value))throw this.astErrorOutput("Non-numeric literal not supported : "+e.value,e);return t.push(e.value),t}astBinaryExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);if("Infinity"===e.name)t.push("Infinity");else this.constants&&this.constants.hasOwnProperty(e.name)?t.push("constants_"+e.name):t.push("user_"+e.name);return t}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const n=[],r=[],i=[],s=[];let a=null;if(e.init){this.pushState("in-for-loop-init"),this.astGeneric(e.init,n);for(let e=0;e<n.length;e++)n[e].includes&&n[e].includes(",")&&(a=!1);this.popState("in-for-loop-init")}else a=!1;if(e.test?this.astGeneric(e.test,r):a=!1,e.update?this.astGeneric(e.update,i):a=!1,e.body&&(this.pushState("loop-body"),this.astGeneric(e.body,s),this.popState("loop-body")),null===a&&(a=this.isSafe(e.init)&&this.isSafe(e.test)),a)t.push(`for (${n.join("")};${r.join("")};${i.join("")}){\n`),t.push(s.join("")),t.push("}\n");else{const e=this.getInternalVariableName("safeI");n.length>0&&t.push(n.join(""),";\n"),t.push(`for (let ${e}=0;${e}<LOOP_MAX;${e}++){\n`),r.length>0&&t.push(`if (!${r.join("")}) break;\n`),t.push(s.join("")),t.push(`\n${i.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),this.astGeneric(e.body,t),t.push("if (!"),this.astGeneric(e.test,t),t.push(") {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astAssignmentExpression(e,t){const n=this.getDeclaration(e.left);if(n&&!n.assignable)throw this.astErrorOutput(`Variable ${e.left.name} is not assignable here`,e);return this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let n=0;n<e.body.length;n++)this.astGeneric(e.body[n],t);this.popState("block-body")}else{t.push("{\n");for(let n=0;n<e.body.length;n++)this.astGeneric(e.body[n],t);t.push("}\n")}return t}astVariableDeclaration(e,t){t.push(`${e.kind} `);const{declarations:n}=e;for(let e=0;e<n.length;e++){e>0&&t.push(",");const r=n[e],i=this.getDeclaration(r.id);i.valueType||(i.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:n,cases:r}=e;t.push("switch ("),this.astGeneric(n,t),t.push(") {\n");for(let e=0;e<r.length;e++)null!==r[e].test?(t.push("case "),this.astGeneric(r[e].test,t),t.push(":\n"),r[e].consequent&&r[e].consequent.length>0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:n,type:r,property:i,xProperty:s,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(n){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(i){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${l}_${u}`),t}const c=`${l}_${u}`;{let e,n;if("constants"===l){const t=this.constants[u];n="Input"===this.constantTypes[u],e=n?t.size:null}else n=this.isInput(u),e=n?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${c}`),o&&a?n?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(s,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(s,t),t.push("]")):a?n?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(s,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(s,t),t.push("]")):void 0!==s&&(t.push("["),this.astGeneric(s,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let n=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n);this.isAstMathFunction(e);this.onFunctionCall&&this.onFunctionCall(this.name,n,e.arguments),t.push(n),t.push("(");const r=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i<e.arguments.length;++i){const s=e.arguments[i];let a=this.getType(s);r[i]||this.triggerImplyArgumentType(n,i,a,this),i>0&&t.push(", "),this.astGeneric(s,t)}return t.push(")"),t}astArrayExpression(e,t){const n=this.getType(e),r=e.elements.length,i=[];for(let t=0;t<r;++t){const n=[];this.astGeneric(e.elements[t],n),i.push(n.join(""))}switch(n){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`[${i.join(", ")}]`);break;default:t.push(`new Float32Array([${i.join(", ")}])`)}return t}astDebuggerStatement(e,t){return t.push("debugger;"),t}}}},{"../function-node":9}],6:[function(e,t,n){const{utils:r}=e("../../utils");t.exports={cpuKernelString:function(e,t){const n=[],i=[],s=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const n=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const i=t[r],s=e[r];switch(i){case"Number":case"Integer":case"Float":case"Boolean":n.push(`${r}:${s}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":n.push(`${r}:new ${s.constructor.name}(${JSON.stringify(Array.from(s))})`)}}return`{ ${n.join()} }`}(e.constants,e.constantTypes)};`),i.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});i.push(" _imageData,"," _colorData,",` color: ${t},`),s.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t<u.length;t++)o.push(e.constantTypes[u]);if(-1!==e.argumentTypes.indexOf("HTMLImageArray")||-1!==o.indexOf("HTMLImageArray")){const t=r.flattenFunctionToString((a?"function ":"")+e._imageTo3DArray.toString(),{doNotDefine:["canvas"],findDependency:(t,n)=>"this"===t?(a?"function ":"")+e[n].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});s.push(t),i.push(" _mediaTo2DArray,"),i.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});s.push(t),i.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${i.join("\n")} });\n ${s.join("\n")}\n return kernel;\n}`}}},{"../../utils":113}],7:[function(e,t,n){const{Kernel:r}=e("../kernel"),{FunctionBuilder:i}=e("../function-builder"),{CPUFunctionNode:s}=e("./function-node"),{utils:a}=e("../../utils"),{cpuKernelString:o}=e("./kernel-string");t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d"):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=a.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t<this.subKernels.length;t++){const{name:n}=this.subKernels[t];e.push(this.output.length>1?`resultX_${n}[x] = subKernelResult_${n};\n`:`result_${n}[x] = subKernelResult_${n};\n`)}this.followingReturnStatement=e.join("")}const e=i.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const n=t[0],r=t[1]||1;e.width=n,e.height=r,this._imageData=this.context.createImageData(n,r),this._colorData=new Uint8ClampedArray(n*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,n,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),n=Math.floor(255*n),r=Math.floor(255*r);const i=this.output[0],s=this.output[1],a=this.thread.x+(s-this.thread.y-1)*i;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=n,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter((t=>/^function/.test(t)?t:(e=t,!1))):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map((e=>"user_"+e)).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return o(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants){switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t<this.argumentTypes.length;t++)"Array"===this.argumentTypes[t]&&e.push(this.argumentNames[t]);if(0===e.length)return"";const t=[];for(let n=0;n<e.length;n++){const r=e[n],i=this._mapSubKernels((e=>`user_${r} === result_${e.name}`)).join(" || ");t.push(`user_${r} === result${i?` || ${i}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t<this.argumentTypes.length;t++){const n=`user_${this.argumentNames[t]}`;switch(this.argumentTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` ${n} = this._mediaTo2DArray(${n});\n`);break;case"HTMLImageArray":e.push(` ${n} = this._imageTo3DArray(${n});\n`);break;case"Input":e.push(` ${n} = ${n}.value;\n`);break;case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"NumberTexture":case"MemoryOptimizedNumberTexture":e.push(`\n if (${n}.toArray) {\n if (!_this.textureCache) {\n _this.textureCache = [];\n _this.arrayCache = [];\n }\n const textureIndex = _this.textureCache.indexOf(${n});\n if (textureIndex !== -1) {\n ${n} = _this.arrayCache[textureIndex];\n } else {\n _this.textureCache.push(${n});\n ${n} = ${n}.toArray();\n _this.arrayCache.push(${n});\n }\n }`)}}return e.join("")}_mediaTo2DArray(e){const t=this.canvas,n=e.width>0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width<n&&(t.width=n),t.height<r&&(t.height=r);const i=this.context;let s;e.constructor===ImageData?s=e.data:(i.drawImage(e,0,0,n,r),s=i.getImageData(0,0,n,r).data);const a=new Array(r);let o=0;for(let e=r-1;e>=0;e--){const t=a[e]=new Array(n);for(let e=0;e<n;e++){const n=new Float32Array(4);n[0]=s[o++]/255,n[1]=s[o++]/255,n[2]=s[o++]/255,n[3]=s[o++]/255,t[e]=n}}return a}getPixels(e){const[t,n]=this.output;return e?a.flipPixels(this._imageData.data,t,n):this._imageData.data.slice(0)}_imageTo3DArray(e){const t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=this._mediaTo2DArray(e[n]);return t}_resultKernelHeader(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";switch(this.output.length){case 1:return this._mutableKernel1DResults();case 2:return this._mutableKernel2DResults();case 3:return this._mutableKernel3DResults()}}_resultKernelBody(e){switch(this.output.length){case 1:return(!this.immutable&&this.pipeline?this._resultMutableKernel1DLoop(e):this._resultImmutableKernel1DLoop(e))+this._kernelOutput();case 2:return(!this.immutable&&this.pipeline?this._resultMutableKernel2DLoop(e):this._resultImmutableKernel2DLoop(e))+this._kernelOutput();case 3:return(!this.immutable&&this.pipeline?this._resultMutableKernel3DLoop(e):this._resultImmutableKernel3DLoop(e))+this._kernelOutput();default:throw new Error("unsupported size kernel")}}_graphicalKernelBody(e){if(2===this.output.length)return this._graphicalKernel2DLoop(e)+this._graphicalOutput();throw new Error("unsupported size kernel")}_graphicalOutput(){return"\n this._imageData.data.set(this._colorData);\n this.context.putImageData(this._imageData, 0, 0);\n return;"}_getKernelResultTypeConstructorString(){switch(this.returnType){case"LiteralInteger":case"Number":case"Integer":case"Float":return"Float32Array";case"Array(2)":case"Array(3)":case"Array(4)":return"Array";default:if(this.graphical)return"Float32Array";throw new Error(`unhandled returnType ${this.returnType}`)}}_resultImmutableKernel1DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${t}(outputX);\n ${this._mapSubKernels((e=>`const result_${e.name} = new ${t}(outputX);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels((t=>`const result_${t.name} = new ${e}(outputX);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels((e=>`const result_${e.name} = new Array(outputY);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels((e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`)).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels((e=>`const result_${e.name} = new Array(outputY);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels((t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`)).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels((e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`)).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels((e=>`const result_${e.name} = new Array(outputZ);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels((e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`)).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels((e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`)).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels((e=>`const result_${e.name} = new Array(outputZ);\n`)).join(" ")}\n ${this._mapSubKernels((e=>`let subKernelResult_${e.name};\n`)).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels((e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`)).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels((t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`)).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map((e=>`${e.property}: result_${e.name}`)).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=i.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,n]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,n),this._colorData=new Uint8ClampedArray(t*n*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}},{"../../utils":113,"../function-builder":8,"../kernel":35,"./function-node":5,"./kernel-string":6}],8:[function(e,t,n){class r{static fromKernel(e,t,n){const{kernelArguments:i,kernelConstants:s,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:c,debug:h,loopMaxIterations:p,nativeFunctions:d,output:m,optimizeFloatMemory:g,precision:f,plugins:x,source:y,subKernels:T,functions:b,leadingReturnStatement:A,followingReturnStatement:S,dynamicArguments:v,dynamicOutput:_}=e,E=new Array(i.length),w={};for(let e=0;e<i.length;e++)E[e]=i[e].type;for(let e=0;e<s.length;e++){const t=s[e];w[t.name]=t.type}const D=(e,t)=>U.needsArgumentType(e,t),$=(e,t,n)=>{U.assignArgumentType(e,t,n)},I=(e,t,n)=>U.lookupReturnType(e,t,n),F=e=>U.lookupFunctionArgumentTypes(e),k=(e,t)=>U.lookupFunctionArgumentName(e,t),R=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),L=(e,t,n,r)=>{U.assignArgumentType(e,t,n,r)},z=(e,t,n,r)=>{U.assignArgumentBitRatio(e,t,n,r)},C=(e,t,n)=>{U.trackFunctionCall(e,t,n)},M=(e,n)=>{const r=[];for(let t=0;t<e.params.length;t++)r.push(e.params[t].name);const i=new t(n,Object.assign({},N,{returnType:null,ast:e,name:e.id.name,argumentNames:r,lookupReturnType:I,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:k,lookupFunctionArgumentBitRatio:R,needsArgumentType:D,assignArgumentType:$,triggerImplyArgumentType:L,triggerImplyArgumentBitRatio:z,onFunctionCall:C}));i.traceFunctionAST(e),U.addFunctionNode(i)},N=Object.assign({isRootKernel:!1,onNestedFunction:M,lookupReturnType:I,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:k,lookupFunctionArgumentBitRatio:R,needsArgumentType:D,assignArgumentType:$,triggerImplyArgumentType:L,triggerImplyArgumentBitRatio:z,onFunctionCall:C,optimizeFloatMemory:g,precision:f,constants:l,constantTypes:w,constantBitRatios:c,debug:h,loopMaxIterations:p,output:m,plugins:x,dynamicArguments:v,dynamicOutput:_},n||{}),O=Object.assign({},N,{isRootKernel:!0,name:"kernel",argumentNames:a,argumentTypes:E,argumentSizes:o,argumentBitRatios:u,leadingReturnStatement:A,followingReturnStatement:S});if("object"==typeof y&&y.functionNodes)return(new r).fromJSON(y.functionNodes,t);const V=new t(y,O);let K=null;b&&(K=b.map((e=>new t(e.source,{returnType:e.returnType,argumentTypes:e.argumentTypes,output:m,plugins:x,constants:l,constantTypes:w,constantBitRatios:c,optimizeFloatMemory:g,precision:f,lookupReturnType:I,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:k,lookupFunctionArgumentBitRatio:R,needsArgumentType:D,assignArgumentType:$,triggerImplyArgumentType:L,triggerImplyArgumentBitRatio:z,onFunctionCall:C,onNestedFunction:M}))));let G=null;T&&(G=T.map((e=>{const{name:n,source:r}=e;return new t(r,Object.assign({},N,{name:n,isSubKernel:!0,isRootKernel:!1}))})));const U=new r({kernel:e,rootNode:V,functionNodes:K,nativeFunctions:d,subKernelNodes:G});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e<this.functionNodes.length;e++)this.functionMap[this.functionNodes[e].name]=this.functionNodes[e];if(this.subKernelNodes)for(let e=0;e<this.subKernelNodes.length;e++)this.functionMap[this.subKernelNodes[e].name]=this.subKernelNodes[e];if(this.nativeFunctions)for(let e=0;e<this.nativeFunctions.length;e++){const t=this.nativeFunctions[e];this.nativeFunctionNames.push(t.name)}}addFunctionNode(e){if(!e.name)throw new Error("functionNode.name needs set");this.functionMap[e.name]=e,e.isRootKernel&&(this.rootNode=e)}traceFunctionCalls(e,t){if(e=e||"kernel",t=t||[],this.nativeFunctionNames.indexOf(e)>-1){const n=t.indexOf(e);if(-1===n)t.push(e);else{const e=t.splice(n,1)[0];t.push(e)}return t}const n=this.functionMap[e];if(n){const r=t.indexOf(e);if(-1===r){t.push(e),n.toString();for(let e=0;e<n.calledFunctions.length;++e)this.traceFunctionCalls(n.calledFunctions[e],t)}else{const e=t.splice(r,1)[0];t.push(e)}}return t}getPrototypeString(e){return this.getPrototypes(e).join("\n")}getPrototypes(e){return this.rootNode&&this.rootNode.toString(),e?this.getPrototypesFromFunctionNames(this.traceFunctionCalls(e,[]).reverse()):this.getPrototypesFromFunctionNames(Object.keys(this.functionMap))}getStringFromFunctionNames(e){const t=[];for(let n=0;n<e.length;++n){this.functionMap[e[n]]&&t.push(this.functionMap[e[n]].toString())}return t.join("\n")}getPrototypesFromFunctionNames(e){const t=[];for(let n=0;n<e.length;++n){const r=e[n],i=this.nativeFunctionNames.indexOf(r);if(i>-1){t.push(this.nativeFunctions[i].source);continue}const s=this.functionMap[r];s&&t.push(s.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map((e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)}))}fromJSON(e,t){this.functionMap={};for(let n=0;n<e.length;n++){const r=e[n];this.functionMap[r.settings.name]=new t(r.ast,r.settings)}return this}getString(e){return e?this.getStringFromFunctionNames(this.traceFunctionCalls(e).reverse()):this.getStringFromFunctionNames(Object.keys(this.functionMap))}lookupReturnType(e,t,n){if("CallExpression"!==t.type)throw new Error(`expected ast type of "CallExpression", but is ${t.type}`);if(this._isNativeFunction(e))return this._lookupNativeFunctionReturnType(e);if(this._isFunction(e)){const r=this._getFunction(e);if(r.returnType)return r.returnType;{for(let e=0;e<this.lookupChain.length;e++)if(this.lookupChain[e].ast===t){if(0===r.argumentTypes.length&&t.arguments.length>0){const i=t.arguments;for(let t=0;t<i.length;t++)this.lookupChain.push({name:n.name,ast:i[e],requestingNode:n}),r.argumentTypes[t]=n.getType(i[t]),this.lookupChain.pop();return r.returnType=r.getType(r.getJsAST())}throw new Error("circlical logic detected!")}this.lookupChain.push({name:n.name,ast:t,requestingNode:n});const e=r.getType(r.getJsAST());return this.lookupChain.pop(),r.returnType=e}}return null}_getFunction(e){return this._isFunction(e)||new Error(`Function ${e} not found`),this.functionMap[e]}_isFunction(e){return Boolean(this.functionMap[e])}_getNativeFunction(e){for(let t=0;t<this.nativeFunctions.length;t++)if(this.nativeFunctions[t].name===e)return this.nativeFunctions[t];return null}_isNativeFunction(e){return Boolean(this._getNativeFunction(e))}_lookupNativeFunctionReturnType(e){let t=this._getNativeFunction(e);if(t)return t.returnType;throw new Error(`Native function ${e} not found`)}lookupFunctionArgumentTypes(e){return this._isNativeFunction(e)?this._getNativeFunction(e).argumentTypes:this._isFunction(e)?this._getFunction(e).argumentTypes:null}lookupFunctionArgumentName(e,t){return this._getFunction(e).argumentNames[t]}lookupFunctionArgumentBitRatio(e,t){if(!this._isFunction(e))throw new Error("function not found");if(this.rootNode.name===e){const e=this.rootNode.argumentNames.indexOf(t);if(-1!==e)return this.rootNode.argumentBitRatios[e]}const n=this._getFunction(e),r=n.argumentNames.indexOf(t);if(-1===r)throw new Error("argument not found");const i=n.argumentBitRatios[r];if("number"!=typeof i)throw new Error("argument bit ratio not found");return i}needsArgumentType(e,t){if(!this._isFunction(e))return!1;return!this._getFunction(e).argumentTypes[t]}assignArgumentType(e,t,n,r){if(!this._isFunction(e))return;const i=this._getFunction(e);i.argumentTypes[t]||(i.argumentTypes[t]=n)}assignArgumentBitRatio(e,t,n,r){const i=this._getFunction(e);if(this._isNativeFunction(n))return null;const s=this._getFunction(n),a=i.argumentNames.indexOf(t);if(-1===a)throw new Error(`Argument ${t} not found in arguments from function ${e}`);const o=i.argumentBitRatios[a];if("number"!=typeof o)throw new Error(`Bit ratio for argument ${t} not found in function ${e}`);s.argumentBitRatios||(s.argumentBitRatios=new Array(s.argumentNames.length));const u=s.argumentBitRatios[a];if("number"==typeof u){if(u!==o)throw new Error(`Incompatible bit ratio found at function ${e} at argument ${t}`);return u}return s.argumentBitRatios[a]=o,o}trackFunctionCall(e,t,n){this.functionNodeDependencies[e]||(this.functionNodeDependencies[e]=new Set,this.functionCalls[e]=[]),this.functionNodeDependencies[e].add(t),this.functionCalls[e].push(n)}getKernelResultType(){return this.rootNode.returnType||this.rootNode.getType(this.rootNode.ast)}getSubKernelResultType(e){const t=this.subKernelNodes[e];let n=!1;for(let e=0;e<this.rootNode.functionCalls.length;e++){this.rootNode.functionCalls[e].ast.callee.name===t.name&&(n=!0)}if(!n)throw new Error(`SubKernel ${t.name} never called by kernel`);return t.returnType||t.getType(t.getJsAST())}getReturnTypes(){const e={[this.rootNode.name]:this.rootNode.getType(this.rootNode.ast)},t=this.traceFunctionCalls(this.rootNode.name);for(let n=0;n<t.length;n++){const r=t[n],i=this.functionMap[r];e[r]=i.getType(i.ast)}return e}}t.exports={FunctionBuilder:r}},{}],9:[function(e,t,n){const r=e("acorn"),{utils:i}=e("../utils"),{FunctionTracer:s}=e("./function-tracer");const a={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};t.exports={FunctionNode:class{constructor(e,t){if(!e&&!t.ast)throw new Error("source parameter is missing");if(t=t||{},this.source=e,this.ast=null,this.name="string"==typeof e?t.isRootKernel?"kernel":t.name||i.getFunctionNameFromString(e):null,this.calledFunctions=[],this.constants={},this.constantTypes={},this.constantBitRatios={},this.isRootKernel=!1,this.isSubKernel=!1,this.debug=null,this.functions=null,this.identifiers=null,this.contexts=null,this.functionCalls=null,this.states=[],this.needsArgumentType=null,this.assignArgumentType=null,this.lookupReturnType=null,this.lookupFunctionArgumentTypes=null,this.lookupFunctionArgumentBitRatio=null,this.triggerImplyArgumentType=null,this.triggerImplyArgumentBitRatio=null,this.onNestedFunction=null,this.onFunctionCall=null,this.optimizeFloatMemory=null,this.precision=null,this.loopMaxIterations=null,this.argumentNames="string"==typeof this.source?i.getArgumentNamesFromString(this.source):null,this.argumentTypes=[],this.argumentSizes=[],this.argumentBitRatios=null,this.returnType=null,this.output=[],this.plugins=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.dynamicOutput=null,this.dynamicArguments=null,this.strictTypingChecking=!1,this.fixIntegerDivisionAccuracy=null,t)for(const e in t)t.hasOwnProperty(e)&&this.hasOwnProperty(e)&&(this[e]=t[e]);this.literalTypes={},this.validate(),this._string=null,this._internalVariableNames={}}validate(){if("string"!=typeof this.source&&!this.ast)throw new Error("this.source not a string");if(!this.ast&&!i.isFunctionString(this.source))throw new Error("this.source not a function string");if(!this.name)throw new Error("this.name could not be set");if(this.argumentTypes.length>0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return th