/** * gpu.js * https://gpu.rocks/ * * GPU Accelerated JavaScript * * @version 2.24.0 * @date Wed Aug 05 2026 23:37:10 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(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&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["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{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}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-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.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 s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={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)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&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)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.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);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.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:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(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:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){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(n){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("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(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(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.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 s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.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=s.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});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.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")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.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({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{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",{willReadFrequently:!0}):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=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.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;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),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 s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*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,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,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 l(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`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;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=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),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}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(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 i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!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);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{let s=null;try{s=d()}catch(e){}const{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!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);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");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=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,r)}),i=()=>{this._inFlight--,s.length>0&&m(s)};return n.then(i,i),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const r=new Array(t.length).fill(null);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=r||new Array(t.length).fill(null);if(a&&!r)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>{const e=s.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=s.plan;if(!t)return null;for(const[e,s]of t.genericClones)if(0!==e.indexOf("up:"))return s.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()});