@mapvx/web-kit 0.0.0-stage → 1.2.0-develop.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +17 -0
- package/README.md +187 -2
- package/dist/cjs/chunks/DRACOLoader-BatVMFjv.cjs +2 -0
- package/dist/cjs/chunks/GLTFLoader-DPzCuhq_.cjs +2 -0
- package/dist/cjs/chunks/KTX2Loader-D3UkVYrQ.cjs +2 -0
- package/dist/cjs/chunks/accessibility-DSrJvXsP.cjs +2 -0
- package/dist/cjs/chunks/back_arrow-DDucL2vy.cjs +2 -0
- package/dist/cjs/chunks/debug-hooks-6E-6XyZt.cjs +2 -0
- package/dist/cjs/chunks/dist-Bn3kS9il.cjs +2 -0
- package/dist/cjs/chunks/dist-C7Xq932f.cjs +2 -0
- package/dist/cjs/chunks/dist-CyU0uhT_.cjs +2 -0
- package/dist/cjs/chunks/expression-YhbojQDk.cjs +2 -0
- package/dist/cjs/chunks/globe-viewport-L8jhK17I.cjs +2 -0
- package/dist/cjs/chunks/icon-origin-point-Fx1ItO6l.cjs +2 -0
- package/dist/cjs/chunks/meshopt_decoder.module-CfZgR5oC.cjs +2 -0
- package/dist/cjs/chunks/repeat_icon-DTL5IJer.cjs +2 -0
- package/dist/cjs/chunks/rolldown-runtime-X-Z9OGZI.cjs +2 -0
- package/dist/cjs/chunks/shader-type-decoder-CM9es9dC.cjs +2 -0
- package/dist/cjs/chunks/styles-DSsNALyl.cjs +2 -0
- package/dist/cjs/chunks/three.module-DrkjviT-.cjs +2 -0
- package/dist/cjs/chunks/walking-DH57xlEw.cjs +2 -0
- package/dist/cjs/chunks/webgl-CmQcn-HM.cjs +2 -0
- package/dist/cjs/chunks/webgl-device-Bjj2DuDc.cjs +2 -0
- package/dist/cjs/web-kit.cjs +425 -0
- package/dist/es/chunks/DRACOLoader-Coaeymvd.js +2 -0
- package/dist/es/chunks/GLTFLoader-Cg9W7uGp.js +2 -0
- package/dist/es/chunks/KTX2Loader-CW7QOwqk.js +2 -0
- package/dist/es/chunks/accessibility-CY2Znzrd.js +2 -0
- package/dist/es/chunks/back_arrow-DXxWd53C.js +2 -0
- package/dist/es/chunks/debug-hooks-CttUbwx0.js +2 -0
- package/dist/es/chunks/dist-DrDbx8fV.js +2 -0
- package/dist/es/chunks/dist-Dzp0YWIR.js +4 -0
- package/dist/es/chunks/dist-TkIGGp-O.js +2 -0
- package/dist/es/chunks/expression-DK4fcsrz.js +2 -0
- package/dist/es/chunks/globe-viewport-CmXSxt1e.js +2 -0
- package/dist/es/chunks/icon-origin-point-CsdwEebb.js +2 -0
- package/dist/es/chunks/meshopt_decoder.module-CymL9NxH.js +2 -0
- package/dist/es/chunks/repeat_icon-VI8TF8gY.js +2 -0
- package/dist/es/chunks/rolldown-runtime-DD4WNi4o.js +2 -0
- package/dist/es/chunks/shader-type-decoder-aS2S_0ef.js +2 -0
- package/dist/es/chunks/styles-CT7CDFlr.js +2 -0
- package/dist/es/chunks/three.module-BeGwQoXi.js +22 -0
- package/dist/es/chunks/walking-DJUq61cT.js +2 -0
- package/dist/es/chunks/webgl-Cm54xPsy.js +2 -0
- package/dist/es/chunks/webgl-device-Cmfm4mkc.js +2 -0
- package/dist/es/web-kit.mjs +428 -0
- package/dist/iife/web-kit.iife.js +425 -0
- package/dist/sw/mvx-tiles-sw.js +582 -0
- package/dist/types/index.d.ts +1765 -0
- package/package.json +87 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! Web-kit v1.2.0-develop.10 | (c) 2026 MapVX */
|
|
2
|
+
!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="55eef6d4-a57a-45dc-b33c-7f0d8e622a56",e._sentryDebugIdIdentifier="sentry-dbid-55eef6d4-a57a-45dc-b33c-7f0d8e622a56")}catch(e){}}();exports.default='<svg width="24" height="24" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path\n d="M23.3111 5.74765C23.3048 7.25788 22.0259 8.47682 20.4559 8.47028C18.8858 8.46374 17.6171 7.23418 17.6234 5.72394C17.6297 4.21371 18.9086 2.99477 20.4787 3.00131C22.0487 3.00785 23.3174 4.23741 23.3111 5.74765ZM15.6027 14.335C15.5493 14.3576 15.49 14.3801 15.4365 14.4027L14.7837 14.6791C13.8762 15.0627 13.1628 15.7662 12.7918 16.6476L12.7015 16.8637C12.3089 17.7964 11.2038 18.2476 10.2331 17.8675C9.26247 17.4875 8.79409 16.4259 9.18665 15.4932L9.27701 15.2771C10.0184 13.5198 11.4457 12.1073 13.2548 11.34L13.9076 11.0636C15.1445 10.5446 16.4254 10.2765 17.8236 10.2823C20.4661 10.2933 22.8414 11.83 23.8448 14.1756L24.6951 16.2757L26.0079 16.8907C26.9421 17.3447 27.3167 18.44 26.8449 19.3382C26.3731 20.2363 25.2341 20.5962 24.2998 20.1422L22.7211 19.378C22.1121 19.0792 21.6343 18.5816 21.3761 17.9766L20.8128 16.664L19.6538 20.3906L22.5736 23.4849C22.8922 23.8223 23.1215 24.2277 23.2323 24.6726L24.5731 29.9193C24.8238 30.9003 24.2035 31.8889 23.1894 32.124C22.1693 32.3647 21.1409 31.7679 20.8428 30.7925L19.6077 25.7627L15.4431 21.353C14.5701 20.4321 14.1962 19.1487 14.5864 17.9483L15.6027 14.335ZM12.1328 25.6404L13.6265 22.0917C13.7531 22.2631 13.8899 22.4232 14.0397 22.5834L16.4406 25.1228L15.5729 27.1815C15.4292 27.5284 15.2146 27.8408 14.941 28.096L11.2726 31.5958C10.5291 32.3048 9.32871 32.2998 8.59121 31.5846C7.85382 30.8694 7.85862 29.7186 8.60194 29.0096L12.1328 25.6404Z"\n fill="currentColor" />\n</svg>';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! Web-kit v1.2.0-develop.10 | (c) 2026 MapVX */
|
|
2
|
+
!function(){try{var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},e=(new n.Error).stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="c2413f38-7f13-4f19-a113-e8589ff0ca74",n._sentryDebugIdIdentifier="sentry-dbid-c2413f38-7f13-4f19-a113-e8589ff0ca74")}catch(n){}}();const n=require("./debug-hooks-6E-6XyZt.cjs"),e=require("./expression-YhbojQDk.cjs"),t=require("./dist-CyU0uhT_.cjs");function r(n,e,t=!1){if(t)return 1===e?"float":`vec${e}`;switch(n){case"uint8":case"uint16":case"uint32":return 1===e?"uint":`uvec${e}`;case"sint8":case"sint16":case"sint32":return 1===e?"int":`ivec${e}`;default:return 1===e?"float":`vec${e}`}}function i(n,e,t=!1){let r;if(t)switch(n){case"uint8":r="unorm8";break;case"sint8":r="snorm8";break;case"uint16":r="unorm16";break;case"sint16":r="snorm16";break;case"float32":r="float32";break;default:throw new Error(`Unsupported normalized vertex format for ${n}`)}else r=n;return 1===e?r:3!==e||r.startsWith("float32")||r.endsWith("32")?`${r}x${e}`:`${r}x3-webgl`}function s(n){switch(n[0]){case"u":return"0u";case"s":return"0";default:return"0."}}function u(n){switch(n){case"uint8":return"r8uint";case"sint8":return"r8sint";case"uint16":return"r16uint";case"sint16":return"r16sint";case"uint32":return"r32uint";case"sint32":return"r32sint";case"float32":return"r32float";default:throw new Error(`Unsupported WebGL gather texture format for ${n}`)}}var o=new n.GLSLShaderAssembler;function a({module:n,elementWise:i=!1,expression:u,inputs:a,output:d,operationType:p=d.type,outputBuffer:m}){const g=m.device,h=c("result",d.type,d.size,d.normalized),_=[n,h],x=[],v={},E=r(d.type,1,d.normalized),y=r(p,1,d.normalized);let b="",T=null;const $={TYPE:y,RESULT_LEN:d.size.toString()},w=function(n){return Array.isArray(n)?n.map((n,e)=>[`x${e}`,n]):Object.entries(n)}(a);for(const[t,r]of w)_.push(l(t,r.type,r.size,r.normalized,p)),x.push(f(t,r)),r instanceof e.GPUDataEvaluator?v[t]=r.buffer:(T=T||e.bufferPool.createOrReuse(g,m.byteLength),v[t]=T),b+=`TYPE ${t}[${r.size}]; get_${t}(${t});\n`,$[`${t.toUpperCase()}_LEN`]=r.size.toString();let S="";if(u)for(let e=0;e<d.size;e++)S+=`result[${e}]=${u(e)};\n`;else if(i)for(let e=0;e<d.size;e++){const t=s(y),r=w.map(([n,r])=>e<r.size?`${n}[${e}]`:t);S+=`result[${e}]=${n.name}(${r.join(", ")});\n`}else S=`${n.name}(${w.map(([n])=>n).join(", ")}, result);`;const L=`#version 300 es\n\nvoid main() {\n${b}\n${E} result[${d.size}];\n${S}\nset_result(result);\n}\n `,z=new t.BufferTransform(g,{vs:L,shaderAssembler:o,defines:$,modules:_,bufferLayout:x,vertexCount:1,instanceCount:d.length,attributes:v,feedbackBufferMode:"interleaved",outputs:h.varyings});g.statsManager.getStats("GPGPU Operation Counts").get("Transform Runs").incrementCount(),z.run({inputBuffers:v,outputBuffers:{[h.varyings[0]]:0===d.offset?m:{buffer:m,byteOffset:d.offset,byteLength:d.byteLength}}}),T&&e.bufferPool.recycle(T)}function l(n,e,t,i=!1,s=e){let u="",o="";for(let a=0;a<t;a+=4){const l=Math.min(t-a,4);u+=`in ${r(e,l,i)} a${n}_${a};\n`;for(let t=0;t<l;t++){let r=`a${n}_${a}`;l>1&&(r=`${r}[${t}]`),(i||e!==s)&&(r=`TYPE(${r})`),o+=`v[${a+t}]=${r};\n`}}return{name:n,vs:`\n${u}\nvoid get_${n}(out TYPE v[${t}]) {\n ${o}\n}\n`}}function f(n,e){const t={name:n,stepMode:e.isConstant?"vertex":"instance",byteStride:e.stride,attributes:[]};for(let r=0;r<e.size;r+=4){const s=Math.min(e.size-r,4);t.attributes.push({attribute:`a${n}_${r}`,format:i(e.type,s,e.normalized),byteOffset:e.offset+e.ValueType.BYTES_PER_ELEMENT*r})}return t}function c(n,e,t,i=!1){const s=[],u=r(e,1,i);let o="",a="";for(let l=0;l<t;l+=4){const u=Math.min(t-l,4),f=r(e,u,i);s.push(`${n}_${l}`),o+=`flat out ${f} ${n}_${l};\n`;const c=Array.from({length:u},(n,e)=>l+e);a+=`${n}_${l} = ${f}(${c.map(n=>`v[${n}]`).join(",")});\n`}return{name:n,varyings:s,vs:`\n${o}\nvoid set_${n}(in ${u} v[${t}]) {\n ${a}\n}\n`}}var d=({inputs:t,output:i,target:u})=>{const o=i.type,l=r(o,1,i.normalized),f=s(l),c=t.namedInputs;return a({module:{name:"arithmetic",dependencies:[n.fp32],vs:"TYPE arithmetic_add(TYPE x, TYPE y) {\n return x + y;\n}\n\nTYPE arithmetic_subtract(TYPE x, TYPE y) {\n return x - y;\n}\n\nTYPE arithmetic_multiply(TYPE x, TYPE y) {\n return x * y;\n}\n\nTYPE arithmetic_divide(TYPE x, TYPE y) {\n return x / y;\n}\n\nfloat arithmetic_tan(float x) {\n return tan_fp32(x);\n}\n"},inputs:c,output:i,operationType:o,outputBuffer:u,expression:n=>e.compileExpression(t.expression,{operations:e.ARITHMETIC_OPERATIONS,inputs:c,laneIndex:n,formatInput:e=>`${e}[${n}]`,formatOutOfBoundsInput:n=>1===c[n].size?`${n}[0]`:f,formatLiteral:e=>{const t=Array.isArray(e)?e[n]??0:e;return`${l}(${function(n,e){switch(n){case"uint8":case"uint16":case"uint32":return`${Math.trunc(e)}u`;case"sint8":case"sint16":case"sint32":return`${Math.trunc(e)}`;default:return Number.isInteger(e)?`${e}.0`:`${e}`}}(o,t)})`},formatCall:(n,e)=>`${n}(${e.join(", ")})`})}),{success:!0}},p=3e38;var m=`#define LE ${function(){const n=new Uint16Array([255]);return new Uint8Array(n.buffer)[0]>0}()?1:0}\nconst uint F32_NAN = 0xffffffffu;\nconst uint F32_INF = 0x7f800000u;\n\n// Find first set bit using binary search\n// https://en.wikipedia.org/wiki/Find_first_set#CLZ\nint countLeadingZeros(uint a) {\n if (a == 0u) return 32;\n int n = 0;\n if ((a & 0xffff0000u) == 0u) { n += 16; a = a << 16; }\n if ((a & 0xff000000u) == 0u) { n += 8; a = a << 8; }\n if ((a & 0xf0000000u) == 0u) { n += 4; a = a << 4; }\n if ((a & 0xc0000000u) == 0u) { n += 2; a = a << 2; }\n if ((a & 0x80000000u) == 0u) return n + 1;\n return n;\n}\n\nuint roundShiftRight(uint value, int shift) {\n if (shift <= 0) {\n return value << (-shift);\n }\n\n if (shift >= 32) {\n if (shift == 32 && value > 0x80000000u) {\n return 1u;\n }\n return 0u;\n }\n\n uint truncated = value >> shift;\n uint halfShift = 1u << (shift - 1);\n uint remainder = value & ((1u << shift) - 1u);\n if (remainder > halfShift || (remainder == halfShift && (truncated & 1u) == 1u)) {\n return truncated + 1u;\n }\n return truncated;\n}\n\nuint makeFloat_(uint sign, int exponent, uint mantissa) {\n return (sign << 31) | (uint(exponent + 127) << 23) | (mantissa & 0x7fffffu);\n}\n\n/**\n * Assemble a float32 in bit representation according to IEEE 754\n * https://en.wikipedia.org/wiki/Single-precision_floating-point_format\n */\nuint makeFloat(uint sign, int exponent, uint significand) {\n if (significand == 0u) {\n return sign << 31;\n }\n\n // Remove any extra leading zeros for better precision\n int lead_zeros = countLeadingZeros(significand);\n // Significand is encoded as 1.fraction\n int normalizedExponent = exponent + 31 - lead_zeros;\n\n if (normalizedExponent > 127) {\n return (sign << 31) | F32_INF;\n }\n\n uint mantissa;\n if (normalizedExponent >= -126) {\n mantissa = roundShiftRight(significand, 8 - lead_zeros);\n if (mantissa >= 0x1000000u) {\n mantissa >>= 1;\n normalizedExponent++;\n if (normalizedExponent > 127) {\n return (sign << 31) | F32_INF;\n }\n }\n return makeFloat_(sign, normalizedExponent, mantissa);\n }\n\n int subnormalShift = -149 - exponent;\n mantissa = roundShiftRight(significand, subnormalShift);\n if (mantissa >= 0x800000u) {\n return (sign << 31) | (1u << 23);\n }\n return (sign << 31) | mantissa;\n}\n\n/**\n * Parse 8-byte memory as a float64 number according to IEEE 754\n * https://en.wikipedia.org/wiki/Double-precision_floating-point_format\n * Returns 8-byte memory as 2 float32 numbers, consisting of\n * high part: fround(d)\n * low part: d - fround(d)\n */\nuvec2 parseAsDouble(uvec2 d) {\n #if LE\n d = d.yx; // to big endian\n #endif\n\n uint sign = (d[0] >> 31) & 1u; // first bit\n uint exponentBits = (d[0] >> 20) & 0x7ffu;\n int exponent = int(exponentBits) - 1023; // next 11 bits\n uint fractionHigh = d[0] & 0xfffffu;\n uint fractionLow = d[1];\n\n if (exponentBits == 0x7ffu) {\n if (fractionHigh == 0u && fractionLow == 0u) {\n return uvec2((sign << 31) | F32_INF, F32_NAN);\n }\n return uvec2(F32_NAN);\n }\n \n if (exponentBits == 0u) {\n // All float64 subnormals are too small to survive a float32 split.\n return uvec2(sign << 31);\n }\n\n if (exponent > 127) {\n return uvec2((sign << 31) | F32_INF, ((1u - sign) << 31) | F32_INF);\n }\n\n uint hi_part;\n uint low_part;\n\n // float64 significand has 52 bits\n // float32 significand has 23 bits\n // The significand of the high part is the significand of the double, trimmed\n uint f_hi = 0x800000u | (fractionHigh << 3) | (fractionLow >> 29);\n uint f_low = fractionLow & 0x1fffffffu;\n\n if (exponent < -126) {\n // For tiny normals, the top 24 significand bits still contribute to the float32\n // high part, but they land in the float32 subnormal range.\n hi_part = makeFloat(sign, exponent - 23, f_hi);\n\n // The residual keeps the remaining 29 significand bits at the original double scale.\n low_part = makeFloat(sign, exponent - 52, f_low);\n return uvec2(hi_part, low_part);\n }\n\n bool roundUp = f_low > 0x10000000u || (f_low == 0x10000000u && (f_hi & 1u) == 1u);\n\n uint f_rounded = f_hi + (roundUp ? 1u : 0u);\n int exponent_hi = exponent;\n if (f_rounded == 0x1000000u) {\n f_rounded = 0x800000u;\n exponent_hi++;\n }\n\n if (exponent_hi > 127) {\n // Overflows float32 limit\n hi_part = (sign << 31) | F32_INF;\n low_part = ((1u - sign) << 31) | F32_INF;\n return uvec2(hi_part, low_part);\n }\n \n hi_part = makeFloat_(sign, exponent_hi, f_rounded);\n\n int remainder = int(f_low);\n uint sign_low = sign;\n if (roundUp) {\n remainder -= 0x20000000;\n }\n if (remainder < 0) {\n sign_low = 1u - sign;\n remainder = -remainder;\n }\n low_part = makeFloat(sign_low, exponent - 52, uint(remainder));\n\n return uvec2(hi_part, low_part);\n}\n\nvoid fround(in uint x[X_LEN], out float result[X_LEN]) {\n int n = X_LEN / 2;\n for (int i = 0; i < n; i++) {\n uvec2 f = parseAsDouble(uvec2(x[i * 2], x[i * 2 + 1]));\n result[i] = uintBitsToFloat(f.x);\n result[i + n] = uintBitsToFloat(f.y);\n }\n}\n`;function g(n,e,t){const i=function(n){switch(n){case"uint32":return"usampler2D";case"sint32":return"isampler2D";case"float32":return"sampler2D";default:throw new Error(`Unsupported WebGL gather sampler type for ${n}`)}}(t),s=r(e,1),u=Array.from({length:n.size},(n,e)=>` v[${e}] = ${s}(texelFetch(source_values_texture, ivec2(${e}, rowIndex), 0).r);`).join("\n");return{name:"source_values_texture",vs:`\nuniform highp ${i} source_values_texture;\nvoid read_source_values(int rowIndex, out TYPE v[${n.size}]) {\n${u}\n}\n`}}function h(e,t,r){const i=r.createTexture({width:Math.max(e.size,1),height:e.length,format:u(t),usage:n.Texture.SAMPLE|n.Texture.COPY_DST});if(0===e.length)return i;const s=r.createCommandEncoder();return s.copyBufferToTexture({sourceBuffer:e.buffer,destinationTexture:i,byteOffset:e.offset,bytesPerRow:e.stride,rowsPerImage:e.length,size:[e.size,e.length,1]}),r.submit(s.finish()),i}function _(n,e){const t=r(n.type,1);let i="aids_0";return n.type!==function(n){switch(n){case"uint":return"uint32";case"int":return"sint32";default:return"float32"}}(e)&&(i=`${e}(${i})`),{name:"ids",vs:`\nin ${t} aids_0;\nvoid get_ids(out INDEX_TYPE v[1]) {\n v[0] = ${i};\n}\n`}}function x(n,e,t,r){return t<e.size?`${n}[${t}]`:1===e.size?`${n}[0]`:r}exports.arithmetic=d,exports.dot=({inputs:n,output:e,target:t})=>(a({module:{name:"row_dot",vs:"void row_dot(in TYPE x[X_LEN], in TYPE y[Y_LEN], out float result[1]) {\n float sum = 0.0;\n for (int i = 0; i < X_LEN; i++) {\n sum += float(x[i]) * float(y[i]);\n }\n result[0] = sum;\n}\n"},inputs:n,output:e,operationType:"float32",outputBuffer:t}),{success:!0}),exports.equalAll=({inputs:n,output:e,target:t})=>(a({module:{name:"equalAll",vs:"void equalAll(in TYPE x[X_LEN], in TYPE y[Y_LEN], out uint result[1]) {\n uint allEqual = uint(1);\n for (int i = 0; i < X_LEN; i++) {\n if (x[i] != y[i]) {\n allEqual = uint(0);\n break;\n }\n }\n result[0] = allEqual;\n}\n"},inputs:n,output:e,operationType:"uint32"===e.type?n.x.type:e.type,outputBuffer:t}),{success:!0}),exports.extent=({inputs:r,output:i,target:s})=>{const{sourceValues:u}=r,o=s.device;if(0===u.length){const n=new i.ValueType(i.length*i.size);return s.write(n),{success:!0,value:n}}if(u.isConstant){const n=u.value,e=new i.ValueType(i.length*i.size);for(let t=0;t<i.length;t++){const r=n[t];e[2*t]=r,e[2*t+1]=r}return s.write(e),{success:!0,value:e}}const a=o.createTexture({width:1,height:i.length,format:"rg32float",usage:n.Texture.RENDER|n.Texture.COPY_SRC|n.Texture.COPY_DST}),c=o.createFramebuffer({colorAttachments:[a]}),m=new t.Model(o,{vs:"#version 300 es\n\nflat out float extent_value;\n\nvoid main() {\n float sourceValues[SOURCE_VALUES_LEN];\n get_sourceValues(sourceValues);\n extent_value = sourceValues[gl_VertexID];\n\n float y = (float(gl_VertexID) + 0.5) / float(CHANNEL_COUNT) * 2.0 - 1.0;\n gl_Position = vec4(0.0, y, 0.0, 1.0);\n gl_PointSize = 1.0;\n}\n ",fs:"#version 300 es\n\nprecision highp float;\n\nflat in float extent_value;\nout vec2 fragColor;\n\nvoid main() {\n fragColor = vec2(-extent_value, extent_value);\n}\n ",topology:"point-list",parameters:{depthCompare:"always",blend:!0,blendColorSrcFactor:"one",blendColorDstFactor:"one",blendColorOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one",blendAlphaOperation:"max"},modules:[l("sourceValues",u.type,u.size,u.normalized)],defines:{TYPE:"float",SOURCE_VALUES_LEN:u.size.toString(),CHANNEL_COUNT:i.length.toString()},attributes:{sourceValues:u.buffer},bufferLayout:[f("sourceValues",u)],instanceCount:u.length,vertexCount:i.length,disableWarnings:!0}),g=e.bufferPool.createOrReuse(o,i.byteLength);try{const n=o.beginRenderPass({framebuffer:c,parameters:{viewport:[0,0,1,i.length]},clearColor:[-p,-p,0,0],clearDepth:!1,clearStencil:!1});o.statsManager.getStats("GPGPU Operation Counts").get("Transform Runs").incrementCount(),m.draw(n),n.end();const t=o.createCommandEncoder();return t.copyTextureToBuffer({sourceTexture:a,width:1,height:i.length,destinationBuffer:g,byteOffset:0,bytesPerRow:8}),o.submit(t.finish()),d({device:o,inputs:{expression:{kind:"call",op:"multiply",args:[{kind:"input",name:"x"},{kind:"literal",value:[-1,1]}]},namedInputs:{x:new e.GPUDataEvaluator({buffer:g,size:2,type:"float32",length:i.length})}},output:i,target:s})}finally{m.destroy(),e.bufferPool.recycle(g),c.destroy(),a.destroy()}},exports.fround=({inputs:n,output:e,target:t})=>(a({module:{name:"fround",vs:m},inputs:n,output:e,operationType:"uint32",outputBuffer:t}),{success:!0}),exports.gather=async({inputs:n,output:e,target:u})=>{const{ids:o,sourceValues:a}=n,l=u.device,f=c("result",e.type,e.size),d=r(o.type,1),p=r(e.type,1),m=e.type,x=h(a,m,l),v=`#version 300 es\n\nvoid main() {\n INDEX_TYPE ids[1];\n get_ids(ids);\n TYPE result[${e.size}];\n gather(ids, result);\n set_result(result);\n}\n `,E=new t.BufferTransform(l,{vs:v,defines:{INDEX_TYPE:d,TYPE:p,RESULT_LEN:e.size.toString(),SOURCE_VALUES_ROWS:a.length.toString()},modules:[_(o,d),g(a,e.type,m),(b=e.type,{name:"gather",vs:`\nvoid zero_result(out TYPE result[RESULT_LEN]) {\n for (int i = 0; i < RESULT_LEN; i++) {\n result[i] = ${s(b)};\n }\n}\n\nvoid gather(in INDEX_TYPE ids[1], out TYPE result[RESULT_LEN]) {\n int sourceIndex = int(ids[0]);\n if (sourceIndex < 0 || sourceIndex >= SOURCE_VALUES_ROWS) {\n zero_result(result);\n return;\n }\n read_source_values(sourceIndex, result);\n}\n`}),f],bindings:{source_values_texture:x},bufferLayout:[(y=o,{name:"ids",stepMode:y.isConstant?"vertex":"instance",byteStride:y.stride,attributes:[{attribute:"aids_0",format:i(y.type,1,y.normalized),byteOffset:y.offset}]})],vertexCount:1,instanceCount:e.length,feedbackBufferMode:"interleaved",outputs:f.varyings});var y,b;try{return E.run({inputBuffers:{ids:o.buffer},outputBuffers:{[f.varyings[0]]:u}}),{success:!0}}finally{E.destroy(),x.destroy()}},exports.interleave=({inputs:n,output:e,target:t})=>{const r=n.map((n,e)=>[`x${e}`,n]);!function(n,e){const t=e.reduce((n,[,e])=>n+Math.ceil(e.size/4),0);if(t>n)throw new Error(`interleave() requires ${t} vertex attributes, exceeding device limit ${n}`)}(t.device.limits.maxVertexAttributes,r),function(n,e){if(e.size>n)throw new Error(`interleave() output size ${e.size} exceeds device inter-stage component limit ${n}`)}(t.device.limits.maxInterStageShaderVariables,e);const i=r.map(([n,e])=>`in TYPE ${n}[${e.size}]`).join(", ");let s=0;return a({module:{name:"interleave",vs:`void interleave(${i}, out TYPE result[RESULT_LEN]) {\n${r.map(([n,e])=>{const t=Array.from({length:e.size},(e,t)=>` result[${s+t}] = ${n}[${t}];`).join("\n");return s+=e.size,t}).join("\n")}\n}\n`},inputs:n,output:e,outputBuffer:t}),{success:!0}},exports.length=({inputs:n,output:e,target:t})=>(a({module:{name:"row_length",vs:"void row_length(in TYPE x[X_LEN], out float result[1]) {\n float sum = 0.0;\n for (int i = 0; i < X_LEN; i++) {\n sum += float(x[i]) * float(x[i]);\n }\n result[0] = sqrt(sum);\n}\n"},inputs:n,output:e,operationType:"float32",outputBuffer:t}),{success:!0}),exports.segmentedMap=async({inputs:n,output:e,target:r})=>{const{segments:i}=n,s=r.device,u=c("result",e.type,e.size),o=i.type,a=h(i,o,s),l=new t.BufferTransform(s,{vs:"#version 300 es\n\nvoid main() {\n TYPE result[RESULT_LEN];\n segmentedMap(result);\n set_result(result);\n}\n",defines:{TYPE:"uint",RESULT_LEN:e.size.toString(),SEGMENTS_LENGTH:i.length.toString()},modules:[g(i,e.type,o),{name:"segmentedMap",vs:"\nuint read_segment_start(int segmentIndex) {\n TYPE value[1];\n read_source_values(segmentIndex, value);\n return uint(value[0]);\n}\n\nvoid segmentedMap(out TYPE result[RESULT_LEN]) {\n uint vertexIndex = uint(gl_InstanceID);\n int low = 0;\n int high = SEGMENTS_LENGTH;\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n uint midStart = read_segment_start(mid);\n if (midStart <= vertexIndex) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n uint segmentIndex = uint(max(low - 1, 0));\n uint segmentStart = read_segment_start(int(segmentIndex));\n result[0] = segmentIndex;\n result[1] = vertexIndex - segmentStart;\n}\n"},u],bindings:{source_values_texture:a},vertexCount:1,instanceCount:e.length,feedbackBufferMode:"interleaved",outputs:u.varyings});try{return l.run({outputBuffers:{[u.varyings[0]]:r}}),{success:!0}}finally{l.destroy(),a.destroy()}},exports.select=async({inputs:n,output:e,target:t})=>{const i=s(r(e.type,1,e.normalized));return a({module:{name:"select",vs:""},inputs:n,output:e,operationType:e.type,outputBuffer:t,expression:e=>{const t=x("condition",n.condition,e,i),r=x("whenTrue",n.whenTrue,e,i),s=x("whenFalse",n.whenFalse,e,i);return`(${t} != ${i} ? ${r} : ${s})`}}),{success:!0}},exports.sequence=({inputs:n,output:e,target:r})=>{const i=c("result",e.type,e.size),s=new t.BufferTransform(r.device,{vs:"#version 300 es\n\nvoid main() {\n int result[1];\n result[0] = START + gl_InstanceID * STEP;\n set_result(result);\n}\n",defines:{START:n.start.toString(),STEP:n.step.toString()},modules:[i],vertexCount:1,instanceCount:e.length,feedbackBufferMode:"interleaved",outputs:i.varyings});try{return s.run({outputBuffers:{[i.varyings[0]]:r}}),{success:!0}}finally{s.destroy()}},exports.swizzle=({inputs:n,output:e,target:t})=>{const{columns:r}=n;return a({module:{name:"swizzle",vs:"// swizzle expression handled inline"},expression:n=>`x[${r[n]}]`,inputs:{x:n.x},output:e,outputBuffer:t}),{success:!0}};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! Web-kit v1.2.0-develop.10 | (c) 2026 MapVX */
|
|
2
|
+
!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4dbc466c-a1e6-4d92-994f-b3d45a37a08c",e._sentryDebugIdIdentifier="sentry-dbid-4dbc466c-a1e6-4d92-994f-b3d45a37a08c")}catch(e){}}();const e=require("./rolldown-runtime-X-Z9OGZI.cjs"),t=require("./debug-hooks-6E-6XyZt.cjs"),r=require("./shader-type-decoder-CM9es9dC.cjs");var i=class{props;_resizeObserver;_intersectionObserver;_observeDevicePixelRatioTimeout=null;_observeDevicePixelRatioMediaQuery=null;_handleDevicePixelRatioChange=()=>this._refreshDevicePixelRatio();_trackPositionInterval=null;_started=!1;get started(){return this._started}constructor(e){this.props=e}start(){if(this._started||!this.props.canvas)return;this._started=!0,this._intersectionObserver||=new IntersectionObserver(e=>this.props.onIntersection(e)),this._resizeObserver||=new ResizeObserver(e=>this.props.onResize(e)),this._intersectionObserver.observe(this.props.canvas);const e=this.props.resizeObserverBox;try{this._resizeObserver.observe(this.props.canvas,{box:e})}catch{this._resizeObserver.observe(this.props.canvas,{box:"content-box"})}this._observeDevicePixelRatioTimeout=setTimeout(()=>this._refreshDevicePixelRatio(),0),this.props.trackPosition&&this._trackPosition()}stop(){this._started&&(this._started=!1,this._observeDevicePixelRatioTimeout&&(clearTimeout(this._observeDevicePixelRatioTimeout),this._observeDevicePixelRatioTimeout=null),this._observeDevicePixelRatioMediaQuery&&(this._observeDevicePixelRatioMediaQuery.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=null),this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect())}_refreshDevicePixelRatio(){this._started&&(this.props.onDevicePixelRatioChange(),this._observeDevicePixelRatioMediaQuery?.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._observeDevicePixelRatioMediaQuery.addEventListener("change",this._handleDevicePixelRatioChange,{once:!0}))}_trackPosition(e=100){this._trackPositionInterval||(this._trackPositionInterval=setInterval(()=>{this._started?this.props.onPositionChange():this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null)},e))}};function n(e,t){if(!e){const e=new Error(t??"luma.gl assertion failed.");throw Error.captureStackTrace?.(e,n),e}}function s(e,t){return n(e,t),e}var o=class e{static isHTMLCanvas(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement}static isOffscreenCanvas(e){return"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}static defaultProps={id:void 0,canvas:null,width:800,height:600,useDevicePixels:!0,pixelSizeSource:"exact",autoResize:!0,container:null,visible:!0,alphaMode:"opaque",colorSpace:"srgb",colorFormat:void 0,toneMapping:"standard",trackPosition:!1};id;props;canvas;htmlCanvas;offscreenCanvas;type;initialized;isInitialized=!1;isVisible=!0;cssWidth;cssHeight;devicePixelRatio;devicePixelWidth;devicePixelHeight;drawingBufferWidth;drawingBufferHeight;_initializedResolvers=function(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}();_canvasObserver;_position=[0,0];destroyed=!1;_needsDrawingBufferResize=!0;_configuredDrawingBufferSize=[0,0];toString(){return`${this[Symbol.toStringTag]}(${this.id})`}constructor(t){this.props={...e.defaultProps,...t},t=this.props,this.initialized=this._initializedResolvers.promise,r.isBrowser()?t.canvas?"string"==typeof t.canvas?this.canvas=a(t.canvas):this.canvas=t.canvas:this.canvas=function(e){const{width:t,height:i}=e,n=document.createElement("canvas");n.id=r.uid("lumagl-auto-created-canvas"),n.width=t||1,n.height=i||1,n.style.width=Number.isFinite(t)?`${t}px`:"100%",n.style.height=Number.isFinite(i)?`${i}px`:"100%",e?.visible||(n.style.visibility="hidden");const s=function(e){if("string"==typeof e){const t=document.getElementById(e);if(!t)throw new Error(`${e} is not an HTML element`);return t}return e||document.body}(e?.container||null);return s.insertBefore(n,s.firstChild),n}(t):this.canvas={width:t.width||1,height:t.height||1},e.isHTMLCanvas(this.canvas)?(this.id=t.id||this.canvas.id,this.type="html-canvas",this.htmlCanvas=this.canvas):e.isOffscreenCanvas(this.canvas)?(this.id=t.id||"offscreen-canvas",this.type="offscreen-canvas",this.offscreenCanvas=this.canvas):(this.id=t.id||"node-canvas-context",this.type="node"),this.cssWidth=this.htmlCanvas?.clientWidth||this.canvas.width,this.cssHeight=this.htmlCanvas?.clientHeight||this.canvas.height,this.devicePixelWidth=this.canvas.width,this.devicePixelHeight=this.canvas.height,this.drawingBufferWidth=this.canvas.width,this.drawingBufferHeight=this.canvas.height,this._configuredDrawingBufferSize=[this.canvas.width,this.canvas.height],this.devicePixelRatio=globalThis.devicePixelRatio||1,this._position=[0,0],this._canvasObserver=new i({canvas:this.htmlCanvas,trackPosition:this.props.trackPosition,resizeObserverBox:"css-dpr"===this.props.pixelSizeSource?"content-box":"device-pixel-content-box",onResize:e=>this._handleResize(e),onIntersection:e=>this._handleIntersection(e),onDevicePixelRatioChange:()=>this._observeDevicePixelRatio(),onPositionChange:()=>this.updatePosition()})}destroy(){this.destroyed||(this.destroyed=!0,this._stopObservers(),this.device=null)}setProps(e){return"useDevicePixels"in e&&(this.props.useDevicePixels=e.useDevicePixels||!1,this._updateDrawingBufferSize()),this}getCurrentFramebuffer(e){return this._resizeDrawingBufferIfNeeded(),this._getCurrentFramebuffer(e)}getCSSSize(){return[this.cssWidth,this.cssHeight]}getPosition(){return this._position}getDevicePixelSize(){return[this.devicePixelWidth,this.devicePixelHeight]}getDrawingBufferSize(){return[this.drawingBufferWidth,this.drawingBufferHeight]}getMaxDrawingBufferSize(){const e=this.device.limits.maxTextureDimension2D;return[e,e]}setDrawingBufferSize(e,t){e=Math.floor(e),t=Math.floor(t),this.drawingBufferWidth===e&&this.drawingBufferHeight===t||(this.drawingBufferWidth=e,this.drawingBufferHeight=t,this._needsDrawingBufferResize=!0)}getDevicePixelRatio(){return"undefined"!=typeof window&&window.devicePixelRatio||1}cssToDevicePixels(e,t=!0){const r=this.cssToDeviceRatio(),[i,n]=this.getDrawingBufferSize();return function(e,t,r,i,n){const s=e,o=l(s[0],t,r);let a=c(s[1],t,i,n),u=l(s[0]+1,t,r);const h=u===r-1?u:u-1;let d;u=c(s[1]+1,t,i,n),n?(u=0===u?u:u+1,d=a,a=u):d=u===i-1?u:u-1;return{x:o,y:a,width:Math.max(h-o+1,1),height:Math.max(d-a+1,1)}}(e,r,i,n,t)}getPixelSize(){return this.getDevicePixelSize()}getAspect(){const[e,t]=this.getDrawingBufferSize();return e>0&&t>0?e/t:1}cssToDeviceRatio(){try{const[e]=this.getDrawingBufferSize(),[t]=this.getCSSSize();return t?e/t:1}catch{return 1}}resize(e){this.setDrawingBufferSize(e.width,e.height)}_setAutoCreatedCanvasId(e){"lumagl-auto-created-canvas"===this.htmlCanvas?.id&&(this.htmlCanvas.id=e)}_startObservers(){this.destroyed||this._canvasObserver.start()}_stopObservers(){this._canvasObserver.stop()}_handleIntersection(e){if(this.destroyed)return;const t=e.find(e=>e.target===this.canvas);if(!t)return;const r=t.isIntersecting;this.isVisible!==r&&(this.isVisible=r,this.device.props.onVisibilityChange(this))}_handleResize(e){if(this.destroyed)return;const t=e.find(e=>e.target===this.canvas);if(!t)return;const r=s(t.contentBoxSize?.[0]);this.cssWidth=r.inlineSize,this.cssHeight=r.blockSize;const i=this.getDevicePixelSize();this._setDevicePixelSize(this._getDevicePixelSizeFromResizeEntry(t)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:i})}_updateDrawingBufferSize(){if(this.props.autoResize)if("number"==typeof this.props.useDevicePixels){const e=this.props.useDevicePixels;this.setDrawingBufferSize(this.cssWidth*e,this.cssHeight*e)}else this.props.useDevicePixels?this.setDrawingBufferSize(this.devicePixelWidth,this.devicePixelHeight):this.setDrawingBufferSize(this.cssWidth,this.cssHeight);this._initializedResolvers.resolve(),this.isInitialized=!0,this.updatePosition()}_getDevicePixelSizeFromResizeEntry(e){const t=s(e.contentBoxSize?.[0]);return"css-dpr"===this.props.pixelSizeSource?this._getDevicePixelSizeFromCSSSize(t.inlineSize,t.blockSize):{devicePixelWidth:e.devicePixelContentBoxSize?.[0]?.inlineSize||t.inlineSize*devicePixelRatio,devicePixelHeight:e.devicePixelContentBoxSize?.[0]?.blockSize||t.blockSize*devicePixelRatio}}_getDevicePixelSizeFromCSSSize(e,t){const r=this.getDevicePixelRatio();return{devicePixelWidth:Math.floor(e*r),devicePixelHeight:Math.floor(t*r)}}_setDevicePixelSize({devicePixelWidth:e,devicePixelHeight:t}){const[r,i]=this.getMaxDrawingBufferSize();this.devicePixelWidth=Math.max(1,Math.min(e,r)),this.devicePixelHeight=Math.max(1,Math.min(t,i))}_resizeDrawingBufferIfNeeded(){if(this._needsDrawingBufferResize){this._needsDrawingBufferResize=!1,this.drawingBufferWidth===this.canvas.width&&this.drawingBufferHeight===this.canvas.height||(this.canvas.width=this.drawingBufferWidth,this.canvas.height=this.drawingBufferHeight);const[e,t]=this._configuredDrawingBufferSize;this.drawingBufferWidth===e&&this.drawingBufferHeight===t||(this._configureDevice(),this._configuredDrawingBufferSize=[this.drawingBufferWidth,this.drawingBufferHeight])}}_observeDevicePixelRatio(){if(this.destroyed||!this._canvasObserver.started)return;const e=this.devicePixelRatio;if(this.devicePixelRatio=window.devicePixelRatio,"css-dpr"===this.props.pixelSizeSource){const e=this.getDevicePixelSize();this._setDevicePixelSize(this._getDevicePixelSizeFromCSSSize(this.cssWidth,this.cssHeight)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:e})}this.updatePosition(),this.device.props.onDevicePixelRatioChange?.(this,{oldRatio:e})}updatePosition(){if(this.destroyed)return;const e=this.htmlCanvas?.getBoundingClientRect();if(e){const t=[e.left,e.top];if(this._position??=t,t[0]!==this._position[0]||t[1]!==this._position[1]){const e=this._position;this._position=t,this.device.props.onPositionChange?.(this,{oldPosition:e})}}}};function a(e){const t=document.getElementById(e);if(!o.isHTMLCanvas(t))throw new Error("Object is not a canvas element");return t}function l(e,t,r){return Math.min(Math.round(e*t),r-1)}function c(e,t,r,i){return i?Math.max(0,r-1-Math.round(e*t)):Math.min(Math.round(e*t),r-1)}var u=class extends o{static defaultProps=o.defaultProps},h=class extends o{},d=class e extends r.Resource{get[Symbol.toStringTag](){return"TextureView"}constructor(t,r){super(t,r,e.defaultProps)}static defaultProps={...r.Resource.defaultProps,format:void 0,dimension:void 0,aspect:"all",baseMipLevel:0,mipLevelCount:void 0,baseArrayLayer:0,arrayLayerCount:void 0}};function f(e,t,r,i){if(i?.inlineSource)return`\n${function(e,t,r){let i="";for(let n=t-2;n<=t;n++){const s=e[n-1];void 0!==s&&(i+=g(s,t,r))}return i}(t,r)}${e.linePos>0?`${" ".repeat(e.linePos+5)}^^^\n`:""}${e.type.toUpperCase()}: ${e.message}\n\n`;const n="error"===e.type?"red":"orange";return i?.html?`<div class='luma-compiler-log-${e.type}' style="color:${n};"><b> ${e.type.toUpperCase()}: ${e.message}</b></div>`:`${e.type.toUpperCase()}: ${e.message}`}function g(e,t,r){const i=r?.html?e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'"):e;return`${function(e,t){let r="";for(let i=e.length;i<t;++i)r+=" ";return r+e}(String(t),4)}: ${i}${r?.html?"<br/>":"\n"}`}var m=class e extends r.Resource{get[Symbol.toStringTag](){return"Shader"}stage;source;compilationStatus="pending";constructor(t,r){super(t,{id:p(r={...r,debugShaders:r.debugShaders||t.props.debugShaders||"errors"}),...r},e.defaultProps),this.stage=this.props.stage,this.source=this.props.source}getCompilationInfoSync(){return null}getTranslatedSource(){return null}async debugShader(){const e=this.props.debugShaders;switch(e){case"never":return;case"errors":if("success"===this.compilationStatus)return}try{const t=await this.getCompilationInfo();if("warnings"===e&&0===t?.length)return;this._displayShaderLog(t,this.id)}catch(t){r.log.warn(`Shader ${this.id}: failed to fetch compilation info during debug logging`,t)()}}_displayShaderLog(e,t){if("undefined"==typeof document||!document?.createElement)return;const r=t,i=`${this.stage} shader "${r}"`,n=function(e,t,r){let i="";const n=t.split(/\r?\n/),s=e.slice().sort((e,t)=>e.lineNum-t.lineNum);switch(r?.showSourceCode||"no"){case"all":let t=0;for(let e=1;e<=n.length;e++){const o=n[e-1],a=s[t];for(o&&a&&(i+=g(o,e,r));s.length>t&&a.lineNum===e;){const e=s[t++];e&&(i+=f(e,n,e.lineNum,{...r,inlineSource:!1}))}}for(;s.length>t;){const e=s[t++];e&&(i+=f(e,[],0,{...r,inlineSource:!1}))}return i;case"issues":case"no":for(const s of e)i+=f(s,n,s.lineNum,{inlineSource:"no"!==r?.showSourceCode});return i}}(e,this.source,{showSourceCode:"all",html:!0}),s=this.getTranslatedSource(),o=document.createElement("div");o.innerHTML=`<h1>Compilation error in ${i}</h1>\n<div style="display:flex;position:fixed;top:10px;right:20px;gap:2px;">\n<button id="copy">Copy source</button><br/>\n<button id="close">Close</button>\n</div>\n<code><pre>${n}</pre></code>`,s&&(o.innerHTML+=`<br /><h1>Translated Source</h1><br /><br /><code><pre>${s}</pre></code>`),o.style.top="0",o.style.left="0",o.style.background="white",o.style.position="fixed",o.style.zIndex="9999",o.style.maxWidth="100vw",o.style.maxHeight="100vh",o.style.overflowY="auto",document.body.appendChild(o),o.querySelector(".luma-compiler-log-error")?.scrollIntoView(),o.querySelector("button#close").onclick=()=>{o.remove()},o.querySelector("button#copy").onclick=()=>{navigator.clipboard.writeText(this.source)}}static defaultProps={...r.Resource.defaultProps,language:"auto",stage:void 0,source:"",sourceMap:null,entryPoint:"main",debugShaders:void 0}};function p(e){return function(e,t="unnamed"){return/#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/.exec(e)?.[1]??t}(e.source)||e.id||r.uid(`unnamed ${e.stage}-shader`)}var b=class e extends r.Resource{get[Symbol.toStringTag](){return"Framebuffer"}width;height;constructor(t,r={}){super(t,r,e.defaultProps),this.width=this.props.width,this.height=this.props.height}clone(e){const t=this.colorAttachments.map(t=>t.texture.clone(e)),r=this.depthStencilAttachment&&this.depthStencilAttachment.texture.clone(e);return this.device.createFramebuffer({...this.props,...e,colorAttachments:t,depthStencilAttachment:r})}resize(e){let t=!e;if(e){const[r,i]=Array.isArray(e)?e:[e.width,e.height];t=t||i!==this.height||r!==this.width,this.width=r,this.height=i}t&&(r.log.log(2,`Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(),this.resizeAttachments(this.width,this.height))}autoCreateAttachmentTextures(){if(0===this.props.colorAttachments.length&&!this.props.depthStencilAttachment)throw new Error("Framebuffer has noattachments");this.colorAttachments=this.props.colorAttachments.map((e,r)=>{if("string"==typeof e){const t=this.createColorTexture(e,r);return this.attachResource(t),t.view}return e instanceof t.Texture?e.view:e});const e=this.props.depthStencilAttachment;if(e)if("string"==typeof e){const t=this.createDepthStencilTexture(e);this.attachResource(t),this.depthStencilAttachment=t.view}else e instanceof t.Texture?this.depthStencilAttachment=e.view:this.depthStencilAttachment=e}createColorTexture(e,r){return this.device.createTexture({id:`${this.id}-color-attachment-${r}`,usage:t.Texture.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height,sampler:{magFilter:"linear",minFilter:"linear"}})}createDepthStencilTexture(e){return this.device.createTexture({id:`${this.id}-depth-stencil-attachment`,usage:t.Texture.RENDER_ATTACHMENT|t.Texture.SAMPLE,format:e,width:this.width,height:this.height})}resizeAttachments(e,t){if(this.colorAttachments.forEach((r,i)=>{const n=r.texture.clone({width:e,height:t});this.destroyAttachedResource(r),this.colorAttachments[i]=n.view,this.attachResource(n.view)}),this.depthStencilAttachment){const r=this.depthStencilAttachment.texture.clone({width:e,height:t});this.destroyAttachedResource(this.depthStencilAttachment),this.depthStencilAttachment=r.view,this.attachResource(r)}this.updateAttachments()}static defaultProps={...r.Resource.defaultProps,width:1,height:1,colorAttachments:[],depthStencilAttachment:null}},y=class e extends r.Resource{get[Symbol.toStringTag](){return"RenderPipeline"}shaderLayout;bufferLayout;linkStatus="pending";hash="";sharedRenderPipeline=null;get isPending(){return"pending"===this.linkStatus||"pending"===this.vs.compilationStatus||"pending"===this.fs?.compilationStatus}get isErrored(){return"error"===this.linkStatus||"error"===this.vs.compilationStatus||"error"===this.fs?.compilationStatus}constructor(t,r){super(t,r,e.defaultProps),this.shaderLayout=this.props.shaderLayout,this.bufferLayout=this.props.bufferLayout||[],this.sharedRenderPipeline=this.props._sharedRenderPipeline||null}static defaultProps={...r.Resource.defaultProps,vs:null,vertexEntryPoint:"vertexMain",vsConstants:{},fs:null,fragmentEntryPoint:"fragmentMain",fsConstants:{},shaderLayout:null,bufferLayout:[],topology:"triangle-list",colorAttachmentFormats:void 0,depthStencilAttachmentFormat:void 0,parameters:{},varyings:void 0,bufferMode:void 0,disableWarnings:!1,_sharedRenderPipeline:void 0,_uniformBlockLayouts:[],bindings:void 0,bindGroups:void 0}},v=class extends r.Resource{get[Symbol.toStringTag](){return"SharedRenderPipeline"}constructor(e,t){super(e,t,{...r.Resource.defaultProps,handle:void 0,vs:void 0,fs:void 0,varyings:void 0,bufferMode:void 0})}};function w(e,t,i){const n=e.bindings.find(e=>e.name===t||`${e.name.toLocaleLowerCase()}uniforms`===t.toLocaleLowerCase());return n||i?.ignoreWarnings||r.log.warn(`Binding ${t} not set: Not found in shader layout.`)(),n||null}function x(e,t){if(!t)return{};if(function(e){const t=Object.keys(e);return t.length>0&&t.every(e=>/^\d+$/.test(e))}(t))return Object.fromEntries(Object.entries(t).map(([e,t])=>[Number(e),{...t}]));const r={};for(const[i,n]of Object.entries(t)){const t=w(e,i)?.group??0;r[t]||={},r[t][i]=n}return r}function _(e){const t={};for(const r of Object.values(e))Object.assign(t,r);return t}var S,P=class e extends r.Resource{static defaultClearColor=[0,0,0,1];static defaultClearDepth=1;static defaultClearStencil=0;get[Symbol.toStringTag](){return"RenderPass"}constructor(t,r,i=e.defaultProps){super(t,r=e.normalizeProps(t,r),i)}static normalizeProps(e,t){return t}static defaultProps={...r.Resource.defaultProps,framebuffer:null,resolveTargets:void 0,parameters:void 0,clearColor:e.defaultClearColor,clearColors:void 0,clearDepth:e.defaultClearDepth,clearStencil:e.defaultClearStencil,depthReadOnly:!1,stencilReadOnly:!1,discard:!1,occlusionQuerySet:void 0,timestampQuerySet:void 0,beginTimestampIndex:void 0,endTimestampIndex:void 0}},T=class e extends r.Resource{get[Symbol.toStringTag](){return"CommandEncoder"}_timeProfilingQuerySet=null;_timeProfilingSlotCount=0;_gpuTimeMs;constructor(t,r){super(t,r,e.defaultProps),this._timeProfilingQuerySet=r.timeProfilingQuerySet??null,this._timeProfilingSlotCount=0,this._gpuTimeMs=void 0}async resolveTimeProfilingQuerySet(){if(this._gpuTimeMs=void 0,!this._timeProfilingQuerySet)return;const e=Math.floor(this._timeProfilingSlotCount/2);if(e<=0)return;const t=2*e,r=await this._timeProfilingQuerySet.readResults({firstQuery:0,queryCount:t});let i=0n;for(let n=0;n<t;n+=2)i+=r[n+1]-r[n];this._gpuTimeMs=Number(i)/1e6}getTimeProfilingSlotCount(){return this._timeProfilingSlotCount}getTimeProfilingQuerySet(){return this._timeProfilingQuerySet}_applyTimeProfilingToPassProps(e){const t=e||{};if(!this._supportsTimestampQueries()||!this._timeProfilingQuerySet)return t;if(void 0!==t.timestampQuerySet||void 0!==t.beginTimestampIndex||void 0!==t.endTimestampIndex)return t;const r=this._timeProfilingSlotCount;return r+1>=this._timeProfilingQuerySet.props.count?t:(this._timeProfilingSlotCount+=2,{...t,timestampQuerySet:this._timeProfilingQuerySet,beginTimestampIndex:r,endTimestampIndex:r+1})}_supportsTimestampQueries(){return this.device.features.has("timestamp-query")}static defaultProps={...r.Resource.defaultProps,measureExecutionTime:void 0,timeProfilingQuerySet:void 0}},B=class e extends r.Resource{get[Symbol.toStringTag](){return"CommandBuffer"}constructor(t,r){super(t,r,e.defaultProps)}static defaultProps={...r.Resource.defaultProps}},E=class e extends r.Resource{static defaultProps={...r.Resource.defaultProps,shaderLayout:void 0,bufferLayout:[]};get[Symbol.toStringTag](){return"VertexArray"}maxVertexAttributes;indexBuffer=null;attributes;constructor(t,r){super(t,r,e.defaultProps),this.maxVertexAttributes=t.limits.maxVertexAttributes,this.attributes=new Array(this.maxVertexAttributes).fill(null)}getBufferSlot(e){return null}getDrawValidationError(){return null}setConstantWebGL(e,t){this.device.reportError(new Error("constant attributes not supported"),this)()}},L=class e extends r.Resource{static defaultProps={...r.Resource.defaultProps,layout:void 0,buffers:{}};get[Symbol.toStringTag](){return"TransformFeedback"}constructor(t,r){super(t,r,e.defaultProps)}},A=class e extends r.Resource{get[Symbol.toStringTag](){return"QuerySet"}constructor(t,r){super(t,r,e.defaultProps)}static defaultProps={...r.Resource.defaultProps,type:void 0,count:void 0}},C=class e extends r.Resource{static defaultProps={...r.Resource.defaultProps};get[Symbol.toStringTag](){return"Fence"}constructor(t,r={}){super(t,r,e.defaultProps)}};function F(e,t={}){const i={...e},n=t.layout??"std140",s={};let o=0;for(const[r,a]of Object.entries(i))o=I(s,r,a,o,n);return o=r.alignTo(o,O(i,n)),{layout:n,byteLength:4*o,uniformTypes:i,fields:s}}function D(e,t){const i=r.resolveVariableShaderTypeAlias(e),n=r.getVariableShaderTypeInfo(i),s=/^mat(\d)x(\d)<.+>$/.exec(i);if(s){const e=Number(s[1]),o=Number(s[2]),a=$(o,i,n.type,t),l=function(e,t,i){return"std140"===i?4:r.alignTo(e,t)}(a.size,a.alignment,t);return{alignment:a.alignment,size:e*l,components:e*o,columns:e,rows:o,columnStride:l,shaderType:i,type:n.type}}const o=/^vec(\d)<.+>$/.exec(i);return o?$(Number(o[1]),i,n.type,t):{alignment:1,size:1,components:1,columns:1,rows:1,columnStride:1,shaderType:i,type:n.type}}function R(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function I(e,t,i,n,s){if("string"==typeof i){const o=D(i,s),a=r.alignTo(n,o.alignment);return e[t]={offset:a,...o},a+o.size}if(Array.isArray(i)){if(Array.isArray(i[0]))throw new Error(`Nested arrays are not supported for ${t}`);const o=i[0],a=i[1],l=M(o,s),c=r.alignTo(n,O(i,s));for(let r=0;r<a;r++)I(e,`${t}[${r}]`,o,c+r*l,s);return c+l*a}if(R(i)){const o=O(i,s);let a=r.alignTo(n,o);for(const[r,n]of Object.entries(i))a=I(e,`${t}.${r}`,n,a,s);return r.alignTo(a,o)}throw new Error(`Unsupported CompositeShaderType for ${t}`)}function k(e,t){if("string"==typeof e)return D(e,t).size;if(Array.isArray(e)){const r=e[0],i=e[1];if(Array.isArray(r))throw new Error("Nested arrays are not supported");return M(r,t)*i}let i=0;for(const n of Object.values(e)){const e=n;i=r.alignTo(i,O(e,t)),i+=k(e,t)}return r.alignTo(i,O(e,t))}function O(e,t){if("string"==typeof e)return D(e,t).alignment;if(Array.isArray(e)){const r=O(e[0],t);return W(t)?Math.max(r,4):r}let r=1;for(const i of Object.values(e)){const e=O(i,t);r=Math.max(r,e)}return function(e){return"std140"===e||"wgsl-uniform"===e}(t)?Math.max(r,4):r}function $(e,t,r,i){return{alignment:2===e?2:4,size:3===e?3:e,components:e,columns:1,rows:e,columnStride:3===e?3:e,shaderType:t,type:r}}function M(e,t){return function(e,t,i){return r.alignTo(e,W(i)?4:t)}(k(e,t),O(e,t),t)}function W(e){return"std140"===e||"wgsl-uniform"===e}function z(e){return(!S||S.byteLength<e)&&(S=new ArrayBuffer(e)),S}function G(e){return e.attributes?e.attributes.map(e=>e.attribute):[e.name]}function N(e){return Object.fromEntries(e.attributes.map(e=>[e.name,e.location]))}function U(e){let t=1/0;for(const r of e)void 0!==r&&(t=Math.min(t,r));return t}function Q(e,t,i){!function(e){for(const t of e)(t.attributes&&t.format||!t.attributes&&!t.format)&&r.log.warn(`BufferLayout ${t.name} must have either 'attributes' or 'format' field`)()}(t);const n=new Map;for(const r of t){const e=V(r);if(r.attributes)for(const t of r.attributes)n.has(t.attribute)||n.set(t.attribute,{bufferName:r.name,stepMode:r.stepMode,vertexFormat:t.format,byteOffset:t.byteOffset,byteStride:e});else r.format&&!n.has(r.name)&&n.set(r.name,{bufferName:r.name,stepMode:r.stepMode,vertexFormat:r.format,byteOffset:0,byteStride:e})}return e.attributes.map(e=>{const t=n.get(e.name);!t&&i?.warnOnMissingBufferLayout&&r.log.warn(`layout for attribute "${e.name}" not present in buffer layout`)();const s=r.shaderTypeDecoder.getAttributeShaderTypeInfo(e.type),o=t?.vertexFormat||r.vertexFormatDecoder.getCompatibleVertexFormat(s);return{attributeName:e.name,bufferName:t?.bufferName||e.name,location:e.location,vertexFormat:o,byteOffset:t?.byteOffset??0,byteStride:t?.byteStride??r.vertexFormatDecoder.getVertexFormatInfo(o).byteLength,stepMode:t?.stepMode||e.stepMode||(e.name.startsWith("instance")?"instance":"vertex")}}).sort((e,t)=>e.location-t.location)}function V(e){if("number"==typeof e.byteStride)return e.byteStride;if(e.attributes){let t=0;for(const i of e.attributes)t+=r.vertexFormatDecoder.getVertexFormatInfo(i.format).byteLength;return t}return r.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength}function j(e,t){const r={},i=Q(e,t,{warnOnMissingBufferLayout:!0});for(const n of i){const t=H(e,n);r[n.attributeName]=t}return r}function H(e,t){const i=function(e,t){const i=e.attributes.find(e=>e.name===t);i||r.log.warn(`shader layout attribute "${t}" not present in shader`)();return i||null}(e,t.attributeName),n=r.shaderTypeDecoder.getAttributeShaderTypeInfo(i.type),s=t.vertexFormat,o=r.vertexFormatDecoder.getVertexFormatInfo(s);return{attributeName:t.attributeName,bufferName:t.bufferName,location:i.location,shaderType:i.type,primitiveType:n.primitiveType,shaderComponents:n.components,vertexFormat:s,bufferDataType:o.type,bufferComponents:o.components,normalized:o.normalized,integer:n.integer,stepMode:t.stepMode,byteOffset:t.byteOffset,byteStride:t.byteStride}}var q={3042:!1,32773:new Float32Array([0,0,0,0]),32777:32774,34877:32774,32969:1,32968:0,32971:1,32970:0,3106:new Float32Array([0,0,0,0]),3107:[!0,!0,!0,!0],2884:!1,2885:1029,2929:!1,2931:1,2932:513,2928:new Float32Array([0,1]),2930:!0,3024:!0,35725:null,36006:null,36007:null,34229:null,34964:null,2886:2305,33170:4352,2849:1,32823:!1,32824:0,10752:0,32926:!1,32928:!1,32938:1,32939:!1,3089:!1,3088:new Int32Array([0,0,1024,1024]),2960:!1,2961:0,2968:4294967295,36005:4294967295,2962:519,2967:0,2963:4294967295,34816:519,36003:0,36004:4294967295,2964:7680,2965:7680,2966:7680,34817:7680,34818:7680,34819:7680,2978:[0,0,1024,1024],36389:null,36662:null,36663:null,35053:null,35055:null,35723:4352,36010:null,35977:!1,3333:4,3317:4,37440:!1,37441:!1,37443:37444,3330:0,3332:0,3331:0,3314:0,32878:0,3316:0,3315:0,32877:0},K=(e,t,r)=>t?e.enable(r):e.disable(r),Y=(e,t,r)=>e.hint(r,t),X=(e,t,r)=>e.pixelStorei(r,t),Z=(e,t,r)=>{const i=36006===r?36009:36008;return e.bindFramebuffer(i,t)},J=(e,t,r)=>{const i={34964:34962,36662:36662,36663:36663,35053:35051,35055:35052}[r];e.bindBuffer(i,t)};function ee(e){return Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView)}var te={3042:K,32773:(e,t)=>e.blendColor(...t),32777:"blendEquation",34877:"blendEquation",32969:"blendFunc",32968:"blendFunc",32971:"blendFunc",32970:"blendFunc",3106:(e,t)=>e.clearColor(...t),3107:(e,t)=>e.colorMask(...t),2884:K,2885:(e,t)=>e.cullFace(t),2929:K,2931:(e,t)=>e.clearDepth(t),2932:(e,t)=>e.depthFunc(t),2928:(e,t)=>e.depthRange(...t),2930:(e,t)=>e.depthMask(t),3024:K,35723:Y,35725:(e,t)=>e.useProgram(t),36007:(e,t)=>e.bindRenderbuffer(36161,t),36389:(e,t)=>e.bindTransformFeedback?.(36386,t),34229:(e,t)=>e.bindVertexArray(t),36006:Z,36010:Z,34964:J,36662:J,36663:J,35053:J,35055:J,2886:(e,t)=>e.frontFace(t),33170:Y,2849:(e,t)=>e.lineWidth(t),32823:K,32824:"polygonOffset",10752:"polygonOffset",35977:K,32926:K,32928:K,32938:"sampleCoverage",32939:"sampleCoverage",3089:K,3088:(e,t)=>e.scissor(...t),2960:K,2961:(e,t)=>e.clearStencil(t),2968:(e,t)=>e.stencilMaskSeparate(1028,t),36005:(e,t)=>e.stencilMaskSeparate(1029,t),2962:"stencilFuncFront",2967:"stencilFuncFront",2963:"stencilFuncFront",34816:"stencilFuncBack",36003:"stencilFuncBack",36004:"stencilFuncBack",2964:"stencilOpFront",2965:"stencilOpFront",2966:"stencilOpFront",34817:"stencilOpBack",34818:"stencilOpBack",34819:"stencilOpBack",2978:(e,t)=>e.viewport(...t),34383:K,10754:K,12288:K,12289:K,12290:K,12291:K,12292:K,12293:K,12294:K,12295:K,3333:X,3317:X,37440:X,37441:X,37443:X,3330:X,3332:X,3331:X,3314:X,32878:X,3316:X,3315:X,32877:X,framebuffer:(e,t)=>{const r=t&&"handle"in t?t.handle:t;return e.bindFramebuffer(36160,r)},blend:(e,t)=>t?e.enable(3042):e.disable(3042),blendColor:(e,t)=>e.blendColor(...t),blendEquation:(e,t)=>{const r="number"==typeof t?[t,t]:t;e.blendEquationSeparate(...r)},blendFunc:(e,t)=>{const r=2===t?.length?[...t,...t]:t;e.blendFuncSeparate(...r)},clearColor:(e,t)=>e.clearColor(...t),clearDepth:(e,t)=>e.clearDepth(t),clearStencil:(e,t)=>e.clearStencil(t),colorMask:(e,t)=>e.colorMask(...t),cull:(e,t)=>t?e.enable(2884):e.disable(2884),cullFace:(e,t)=>e.cullFace(t),depthTest:(e,t)=>t?e.enable(2929):e.disable(2929),depthFunc:(e,t)=>e.depthFunc(t),depthMask:(e,t)=>e.depthMask(t),depthRange:(e,t)=>e.depthRange(...t),dither:(e,t)=>t?e.enable(3024):e.disable(3024),derivativeHint:(e,t)=>{e.hint(35723,t)},frontFace:(e,t)=>e.frontFace(t),mipmapHint:(e,t)=>e.hint(33170,t),lineWidth:(e,t)=>e.lineWidth(t),polygonOffsetFill:(e,t)=>t?e.enable(32823):e.disable(32823),polygonOffset:(e,t)=>e.polygonOffset(...t),sampleCoverage:(e,t)=>e.sampleCoverage(t[0],t[1]||!1),scissorTest:(e,t)=>t?e.enable(3089):e.disable(3089),scissor:(e,t)=>e.scissor(...t),stencilTest:(e,t)=>t?e.enable(2960):e.disable(2960),stencilMask:(e,t)=>{t=ee(t)?t:[t,t];const[r,i]=t;e.stencilMaskSeparate(1028,r),e.stencilMaskSeparate(1029,i)},stencilFunc:(e,t)=>{t=ee(t)&&3===t.length?[...t,...t]:t;const[r,i,n,s,o,a]=t;e.stencilFuncSeparate(1028,r,i,n),e.stencilFuncSeparate(1029,s,o,a)},stencilOp:(e,t)=>{t=ee(t)&&3===t.length?[...t,...t]:t;const[r,i,n,s,o,a]=t;e.stencilOpSeparate(1028,r,i,n),e.stencilOpSeparate(1029,s,o,a)},viewport:(e,t)=>e.viewport(...t)};function re(e,t,r){return void 0!==t[e]?t[e]:r[e]}var ie={blendEquation:(e,t,r)=>e.blendEquationSeparate(re(32777,t,r),re(34877,t,r)),blendFunc:(e,t,r)=>e.blendFuncSeparate(re(32969,t,r),re(32968,t,r),re(32971,t,r),re(32970,t,r)),polygonOffset:(e,t,r)=>e.polygonOffset(re(32824,t,r),re(10752,t,r)),sampleCoverage:(e,t,r)=>e.sampleCoverage(re(32938,t,r),re(32939,t,r)),stencilFuncFront:(e,t,r)=>e.stencilFuncSeparate(1028,re(2962,t,r),re(2967,t,r),re(2963,t,r)),stencilFuncBack:(e,t,r)=>e.stencilFuncSeparate(1029,re(34816,t,r),re(36003,t,r),re(36004,t,r)),stencilOpFront:(e,t,r)=>e.stencilOpSeparate(1028,re(2964,t,r),re(2965,t,r),re(2966,t,r)),stencilOpBack:(e,t,r)=>e.stencilOpSeparate(1029,re(34817,t,r),re(34818,t,r),re(34819,t,r))},ne={enable:(e,t)=>e({[t]:!0}),disable:(e,t)=>e({[t]:!1}),pixelStorei:(e,t,r)=>e({[t]:r}),hint:(e,t,r)=>e({[t]:r}),useProgram:(e,t)=>e({35725:t}),bindRenderbuffer:(e,t,r)=>e({36007:r}),bindTransformFeedback:(e,t,r)=>e({36389:r}),bindVertexArray:(e,t)=>e({34229:t}),bindFramebuffer:(e,t,r)=>{switch(t){case 36160:return e({36006:r,36010:r});case 36009:return e({36006:r});case 36008:return e({36010:r});default:return null}},bindBuffer:(e,t,r)=>{const i={34962:[34964],36662:[36662],36663:[36663],35051:[35053],35052:[35055]}[t];return i?e({[i]:r}):{valueChanged:!0}},blendColor:(e,t,r,i,n)=>e({32773:new Float32Array([t,r,i,n])}),blendEquation:(e,t)=>e({32777:t,34877:t}),blendEquationSeparate:(e,t,r)=>e({32777:t,34877:r}),blendFunc:(e,t,r)=>e({32969:t,32968:r,32971:t,32970:r}),blendFuncSeparate:(e,t,r,i,n)=>e({32969:t,32968:r,32971:i,32970:n}),clearColor:(e,t,r,i,n)=>e({3106:new Float32Array([t,r,i,n])}),clearDepth:(e,t)=>e({2931:t}),clearStencil:(e,t)=>e({2961:t}),colorMask:(e,t,r,i,n)=>e({3107:[t,r,i,n]}),cullFace:(e,t)=>e({2885:t}),depthFunc:(e,t)=>e({2932:t}),depthRange:(e,t,r)=>e({2928:new Float32Array([t,r])}),depthMask:(e,t)=>e({2930:t}),frontFace:(e,t)=>e({2886:t}),lineWidth:(e,t)=>e({2849:t}),polygonOffset:(e,t,r)=>e({32824:t,10752:r}),sampleCoverage:(e,t,r)=>e({32938:t,32939:r}),scissor:(e,t,r,i,n)=>e({3088:new Int32Array([t,r,i,n])}),stencilMask:(e,t)=>e({2968:t,36005:t}),stencilMaskSeparate:(e,t,r)=>e({[1028===t?2968:36005]:r}),stencilFunc:(e,t,r,i)=>e({2962:t,2967:r,2963:i,34816:t,36003:r,36004:i}),stencilFuncSeparate:(e,t,r,i,n)=>e({[1028===t?2962:34816]:r,[1028===t?2967:36003]:i,[1028===t?2963:36004]:n}),stencilOp:(e,t,r,i)=>e({2964:t,2965:r,2966:i,34817:t,34818:r,34819:i}),stencilOpSeparate:(e,t,r,i,n)=>e({[1028===t?2964:34817]:r,[1028===t?2965:34818]:i,[1028===t?2966:34819]:n}),viewport:(e,t,r,i,n)=>e({2978:[t,r,i,n]})},se=(e,t)=>e.isEnabled(t),oe={3042:se,2884:se,2929:se,3024:se,32823:se,32926:se,32928:se,3089:se,2960:se,35977:se},ae=new Set([34016,36388,36387,35983,35368,34965,35739,35738,3074,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,35097,32873,35869,32874,34068]);function le(e,t){if(function(e){for(const t in e)return!1;return!0}(t))return;const r={};for(const n in t){const i=Number(n),s=te[n];s&&("string"==typeof s?r[s]=!0:s(e,t[n],i))}const i=e.lumaState?.cache;if(i)for(const n in r){(0,ie[n])(e,t,i)}}function ce(e,t=q){if("number"==typeof t){const r=t,i=oe[r];return i?i(e,r):e.getParameter(r)}const r=Array.isArray(t)?t:Object.keys(t),i={};for(const n of r){const t=oe[n];i[n]=t?t(e,Number(n)):e.getParameter(Number(n))}return i}function ue(e,t){if(e===t)return!0;if(he(e)&&he(t)&&e.length===t.length){for(let r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}return!1}function he(e){return Array.isArray(e)||ArrayBuffer.isView(e)}var de=class{static get(e){return e.lumaState}gl;program=null;stateStack=[];enable=!0;cache=null;log;initialized=!1;constructor(e,t){this.gl=e,this.log=t?.log||(()=>{}),this._updateCache=this._updateCache.bind(this),Object.seal(this)}push(e={}){this.stateStack.push({})}pop(){const e=this.stateStack[this.stateStack.length-1];le(this.gl,e),this.stateStack.pop()}trackState(e,t){if(this.cache=t?.copyState?ce(e):Object.assign({},q),this.initialized)throw new Error("WebGLStateTracker");this.initialized=!0,this.gl.lumaState=this,function(e){const t=e.useProgram.bind(e);e.useProgram=function(r){const i=de.get(e);i.program!==r&&(t(r),i.program=r)}}(e);for(const r in ne){ge(e,r,ne[r])}fe(e,"getParameter"),fe(e,"isEnabled")}_updateCache(e){let t,r=!1;const i=this.stateStack.length>0?this.stateStack[this.stateStack.length-1]:null;for(const n in e){const s=e[n],o=this.cache[n];ue(s,o)||(r=!0,t=o,i&&!(n in i)&&(i[n]=o),this.cache[n]=s)}return{valueChanged:r,oldValue:t}}};function fe(e,t){const r=e[t].bind(e);e[t]=function(t){if(void 0===t||ae.has(t))return r(t);const i=de.get(e);return t in i.cache||(i.cache[t]=r(t)),i.enable?i.cache[t]:r(t)},Object.defineProperty(e[t],"name",{value:`${t}-from-cache`,configurable:!1})}function ge(e,t,r){if(!e[t])return;const i=e[t].bind(e);e[t]=function(...t){const{valueChanged:n,oldValue:s}=r(de.get(e)._updateCache,...t);return n&&i(...t),s},Object.defineProperty(e[t],"name",{value:`${t}-to-cache`,configurable:!1})}function me(e){const t=e.luma||{_polyfilled:!1,extensions:{},softwareRenderer:!1};return t._polyfilled??=!1,t.extensions||={},e.luma=t,t}function pe(e,t,r){return void 0===r[t]&&(r[t]=e.getExtension(t)||null),r[t]}function be(e,t){return/NVIDIA/i.exec(e)||/NVIDIA/i.exec(t)?"nvidia":/INTEL/i.exec(e)||/INTEL/i.exec(t)?"intel":/Apple/i.exec(e)||/Apple/i.exec(t)?"apple":/AMD/i.exec(e)||/AMD/i.exec(t)||/ATI/i.exec(e)||/ATI/i.exec(t)?"amd":/SwiftShader/i.exec(e)||/SwiftShader/i.exec(t)?"software":"unknown"}function ye(e,t){if(/SwiftShader/i.exec(e)||/SwiftShader/i.exec(t))return"cpu";switch(be(e,t)){case"apple":return function(e,t){return/Apple (M\d|A\d|GPU)/i.test(`${e} ${t}`)}(e,t)?"integrated":"unknown";case"intel":return"integrated";case"software":return"cpu";case"unknown":return"unknown";default:return"discrete"}}function ve(e){switch(e){case"uint8":case"unorm8":return 5121;case"sint8":case"snorm8":return 5120;case"uint16":case"unorm16":return 5123;case"sint16":case"snorm16":return 5122;case"uint32":return 5125;case"sint32":return 5124;case"float16":return 5131;case"float32":return 5126}throw new Error(String(e))}var we="WEBGL_compressed_texture_s3tc",xe="WEBGL_compressed_texture_s3tc_srgb",_e="EXT_texture_compression_rgtc",Se="EXT_texture_compression_bptc",Pe="EXT_render_snorm",Te="EXT_color_buffer_float",Be="snorm8-renderable-webgl",Ee="norm16-renderable-webgl",Le="snorm16-renderable-webgl",Ae="float16-renderable-webgl",Ce="float32-renderable-webgl",Fe={"float32-renderable-webgl":{extensions:[Te]},"float16-renderable-webgl":{extensions:["EXT_color_buffer_half_float"]},"rgb9e5ufloat-renderable-webgl":{extensions:["WEBGL_render_shared_exponent"]},"snorm8-renderable-webgl":{extensions:[Pe]},"norm16-webgl":{extensions:["EXT_texture_norm16"]},"norm16-renderable-webgl":{features:["norm16-webgl"]},"snorm16-renderable-webgl":{features:["norm16-webgl"],extensions:[Pe]},"float32-filterable":{extensions:["OES_texture_float_linear"]},"float16-filterable-webgl":{extensions:["OES_texture_half_float_linear"]},"texture-filterable-anisotropic-webgl":{extensions:["EXT_texture_filter_anisotropic"]},"texture-blend-float-webgl":{extensions:["EXT_float_blend"]},"texture-compression-bc":{extensions:[we,xe,_e,Se]},"texture-compression-bc5-webgl":{extensions:[_e]},"texture-compression-bc7-webgl":{extensions:[Se]},"texture-compression-etc2":{extensions:["WEBGL_compressed_texture_etc"]},"texture-compression-astc":{extensions:["WEBGL_compressed_texture_astc"]},"texture-compression-etc1-webgl":{extensions:["WEBGL_compressed_texture_etc1"]},"texture-compression-pvrtc-webgl":{extensions:["WEBGL_compressed_texture_pvrtc"]},"texture-compression-atc-webgl":{extensions:["WEBGL_compressed_texture_atc"]}};function De(e,t,r){return Re(e,t,r,new Set)}function Re(e,t,r,i){const n=Fe[t];if(!n)return!1;if(i.has(t))return!1;i.add(t);const s=(n.features||[]).every(t=>Re(e,t,r,i));return i.delete(t),!!s&&(n.extensions||[]).every(t=>Boolean(pe(e,t,r)))}var Ie={r8unorm:{gl:33321,rb:!0},r8snorm:{gl:36756,r:Be},r8uint:{gl:33330,rb:!0},r8sint:{gl:33329,rb:!0},rg8unorm:{gl:33323,rb:!0},rg8snorm:{gl:36757,r:Be},rg8uint:{gl:33336,rb:!0},rg8sint:{gl:33335,rb:!0},r16uint:{gl:33332,rb:!0},r16sint:{gl:33331,rb:!0},r16float:{gl:33325,rb:!0,r:Ae},r16unorm:{gl:33322,rb:!0,r:Ee},r16snorm:{gl:36760,r:Le},"rgba4unorm-webgl":{gl:32854,rb:!0},"rgb565unorm-webgl":{gl:36194,rb:!0},"rgb5a1unorm-webgl":{gl:32855,rb:!0},"rgb8unorm-webgl":{gl:32849},"rgb8snorm-webgl":{gl:36758},rgba8unorm:{gl:32856},"rgba8unorm-srgb":{gl:35907},rgba8snorm:{gl:36759,r:Be},rgba8uint:{gl:36220},rgba8sint:{gl:36238},bgra8unorm:{},"bgra8unorm-srgb":{},rg16uint:{gl:33338},rg16sint:{gl:33337},rg16float:{gl:33327,rb:!0,r:Ae},rg16unorm:{gl:33324,r:Ee},rg16snorm:{gl:36761,r:Le},r32uint:{gl:33334,rb:!0},r32sint:{gl:33333,rb:!0},r32float:{gl:33326,r:Ce},rgb9e5ufloat:{gl:35901,r:"rgb9e5ufloat-renderable-webgl"},rg11b10ufloat:{gl:35898,rb:!0},rgb10a2unorm:{gl:32857,rb:!0},rgb10a2uint:{gl:36975,rb:!0},"rgb16unorm-webgl":{gl:32852,r:!1},"rgb16snorm-webgl":{gl:36762,r:!1},rg32uint:{gl:33340,rb:!0},rg32sint:{gl:33339,rb:!0},rg32float:{gl:33328,rb:!0,r:Ce},rgba16uint:{gl:36214,rb:!0},rgba16sint:{gl:36232,rb:!0},rgba16float:{gl:34842,r:Ae},rgba16unorm:{gl:32859,rb:!0,r:Ee},rgba16snorm:{gl:36763,r:Le},"rgb32float-webgl":{gl:34837,x:Te,r:Ce,dataFormat:6407,types:[5126]},rgba32uint:{gl:36208,rb:!0},rgba32sint:{gl:36226,rb:!0},rgba32float:{gl:34836,rb:!0,r:Ce},stencil8:{gl:36168,rb:!0},depth16unorm:{gl:33189,dataFormat:6402,types:[5123],rb:!0},depth24plus:{gl:33190,dataFormat:6402,types:[5125]},depth32float:{gl:36012,dataFormat:6402,types:[5126],rb:!0},"depth24plus-stencil8":{gl:35056,rb:!0,depthTexture:!0,dataFormat:34041,types:[34042]},"depth32float-stencil8":{gl:36013,dataFormat:34041,types:[36269],rb:!0},"bc1-rgb-unorm-webgl":{gl:33776,x:we},"bc1-rgb-unorm-srgb-webgl":{gl:35916,x:xe},"bc1-rgba-unorm":{gl:33777,x:we},"bc1-rgba-unorm-srgb":{gl:35916,x:xe},"bc2-rgba-unorm":{gl:33778,x:we},"bc2-rgba-unorm-srgb":{gl:35918,x:xe},"bc3-rgba-unorm":{gl:33779,x:we},"bc3-rgba-unorm-srgb":{gl:35919,x:xe},"bc4-r-unorm":{gl:36283,x:_e},"bc4-r-snorm":{gl:36284,x:_e},"bc5-rg-unorm":{gl:36285,x:_e},"bc5-rg-snorm":{gl:36286,x:_e},"bc6h-rgb-ufloat":{gl:36495,x:Se},"bc6h-rgb-float":{gl:36494,x:Se},"bc7-rgba-unorm":{gl:36492,x:Se},"bc7-rgba-unorm-srgb":{gl:36493,x:Se},"etc2-rgb8unorm":{gl:37492},"etc2-rgb8unorm-srgb":{gl:37494},"etc2-rgb8a1unorm":{gl:37496},"etc2-rgb8a1unorm-srgb":{gl:37497},"etc2-rgba8unorm":{gl:37493},"etc2-rgba8unorm-srgb":{gl:37495},"eac-r11unorm":{gl:37488},"eac-r11snorm":{gl:37489},"eac-rg11unorm":{gl:37490},"eac-rg11snorm":{gl:37491},"astc-4x4-unorm":{gl:37808},"astc-4x4-unorm-srgb":{gl:37840},"astc-5x4-unorm":{gl:37809},"astc-5x4-unorm-srgb":{gl:37841},"astc-5x5-unorm":{gl:37810},"astc-5x5-unorm-srgb":{gl:37842},"astc-6x5-unorm":{gl:37811},"astc-6x5-unorm-srgb":{gl:37843},"astc-6x6-unorm":{gl:37812},"astc-6x6-unorm-srgb":{gl:37844},"astc-8x5-unorm":{gl:37813},"astc-8x5-unorm-srgb":{gl:37845},"astc-8x6-unorm":{gl:37814},"astc-8x6-unorm-srgb":{gl:37846},"astc-8x8-unorm":{gl:37815},"astc-8x8-unorm-srgb":{gl:37847},"astc-10x5-unorm":{gl:37816},"astc-10x5-unorm-srgb":{gl:37848},"astc-10x6-unorm":{gl:37817},"astc-10x6-unorm-srgb":{gl:37849},"astc-10x8-unorm":{gl:37818},"astc-10x8-unorm-srgb":{gl:37850},"astc-10x10-unorm":{gl:37819},"astc-10x10-unorm-srgb":{gl:37851},"astc-12x10-unorm":{gl:37820},"astc-12x10-unorm-srgb":{gl:37852},"astc-12x12-unorm":{gl:37821},"astc-12x12-unorm-srgb":{gl:37853},"pvrtc-rgb4unorm-webgl":{gl:35840},"pvrtc-rgba4unorm-webgl":{gl:35842},"pvrtc-rgb2unorm-webgl":{gl:35841},"pvrtc-rgba2unorm-webgl":{gl:35843},"etc1-rbg-unorm-webgl":{gl:36196},"atc-rgb-unorm-webgl":{gl:35986},"atc-rgba-unorm-webgl":{gl:35986},"atc-rgbai-unorm-webgl":{gl:34798}};function ke(e,t,r){let i=t.create;const n=Ie[t.format];void 0===n?.gl&&(i=!1),n?.x&&(i=i&&Boolean(pe(e,n.x,r))),"stencil8"===t.format&&(i=!1);const s=!1!==n?.r&&(void 0===n?.r||De(e,n.r,r)),o=i&&t.render&&s&&function(e,t,r){const i=Ie[t],n=i?.gl;if(void 0===n)return!1;if(i?.x&&!pe(e,i.x,r))return!1;const s=e.getParameter(32873),o=e.getParameter(36006),a=e.createTexture(),l=e.createFramebuffer();if(!a||!l)return!1;const c=0;let u=Number(e.getError());for(;u!==c;)u=e.getError();let h=!1;try{if(e.bindTexture(3553,a),e.texStorage2D(3553,1,n,1,1),Number(e.getError())!==c)return!1;e.bindFramebuffer(36160,l),e.framebufferTexture2D(36160,36064,3553,a,0),h=36053===Number(e.checkFramebufferStatus(36160))&&Number(e.getError())===c}finally{e.bindFramebuffer(36160,o),e.deleteFramebuffer(l),e.bindTexture(3553,s),e.deleteTexture(a)}return h}(e,t.format,r);return{format:t.format,create:i&&t.create,render:o,filter:i&&t.filter,blend:i&&t.blend,store:i&&t.store}}function Oe(e){const r=Ie[e],i=function(e){const t=Ie[e]?.gl;if(void 0===t)throw new Error(`Unsupported texture format ${e}`);return t}(e),n=t.textureFormatDecoder.getInfo(e);return n.compressed&&(r.dataFormat=i),{internalFormat:i,format:r?.dataFormat||$e(n.channels,n.integer,n.normalized,i),type:n.dataType?ve(n.dataType):r?.types?.[0]||5121,compressed:n.compressed||!1}}function $e(e,t,r,i){if(6408===i||6407===i)return i;switch(e){case"r":return t&&!r?36244:6403;case"rg":return t&&!r?33320:33319;case"rgb":return t&&!r?36248:6407;case"rgba":return t&&!r?36249:6408;case"bgra":throw new Error("bgra pixels not supported by WebGL");default:return 6408}}var Me={"depth-clip-control":"EXT_depth_clamp","timestamp-query":"EXT_disjoint_timer_query_webgl2","compilation-status-async-webgl":"KHR_parallel_shader_compile","html-in-canvas":e=>t.isHTMLInCanvasSupported()&&"function"==typeof e.texElementImage2D,"polygon-mode-webgl":"WEBGL_polygon_mode","provoking-vertex-webgl":"WEBGL_provoking_vertex","shader-clip-cull-distance-webgl":"WEBGL_clip_cull_distance","shader-noperspective-interpolation-webgl":"NV_shader_noperspective_interpolation","shader-conservative-depth-webgl":"EXT_conservative_depth"},We=class extends t.DeviceFeatures{gl;extensions;testedFeatures=new Set;constructor(e,t,r){super([],r),this.gl=e,this.extensions=t,pe(e,"EXT_color_buffer_float",t)}*[Symbol.iterator](){const e=this.getFeatures();for(const t of e)this.has(t)&&(yield t);return[]}has(e){return!this.disabledFeatures?.[e]&&(this.testedFeatures.has(e)||(this.testedFeatures.add(e),function(e){return e in Fe}(e)&&De(this.gl,e,this.extensions)&&this.features.add(e),this.getWebGLFeature(e)&&this.features.add(e)),this.features.has(e))}initializeFeatures(){const e=this.getFeatures().filter(e=>"polygon-mode-webgl"!==e);for(const t of e)this.has(t)}getFeatures(){return[...Object.keys(Me),...Object.keys(Fe)]}getWebGLFeature(e){const t=Me[e];return"string"==typeof t?Boolean(pe(this.gl,t,this.extensions)):"function"==typeof t?t(this.gl):Boolean(t)}},ze=class extends t.DeviceLimits{get maxTextureDimension1D(){return 0}get maxTextureDimension2D(){return this.getParameter(3379)}get maxTextureDimension3D(){return this.getParameter(32883)}get maxTextureArrayLayers(){return this.getParameter(35071)}get maxBindGroups(){return 0}get maxBindGroupsPlusVertexBuffers(){return 0}get maxBindingsPerBindGroup(){return 0}get maxDynamicUniformBuffersPerPipelineLayout(){return 0}get maxDynamicStorageBuffersPerPipelineLayout(){return 0}get maxSampledTexturesPerShaderStage(){return this.getParameter(35660)}get maxSamplersPerShaderStage(){return this.getParameter(35661)}get maxStorageBuffersPerShaderStage(){return 0}get maxStorageBuffersInVertexStage(){return 0}get maxStorageBuffersInFragmentStage(){return 0}get maxStorageTexturesPerShaderStage(){return 0}get maxStorageTexturesInVertexStage(){return 0}get maxStorageTexturesInFragmentStage(){return 0}get maxUniformBuffersPerShaderStage(){return this.getParameter(35375)}get maxUniformBufferBindingSize(){return this.getParameter(35376)}get maxStorageBufferBindingSize(){return 0}get maxBufferSize(){return Number.MAX_SAFE_INTEGER}get minUniformBufferOffsetAlignment(){return this.getParameter(35380)}get minStorageBufferOffsetAlignment(){return 0}get maxVertexBuffers(){return 16}get maxVertexAttributes(){return this.getParameter(34921)}get maxVertexBufferArrayStride(){return 2048}get maxInterStageShaderVariables(){return this.getParameter(35659)}get maxColorAttachments(){return this.getParameter(36063)}get maxColorAttachmentBytesPerSample(){return 0}get maxComputeWorkgroupStorageSize(){return 0}get maxComputeInvocationsPerWorkgroup(){return 0}get maxComputeWorkgroupSizeX(){return 0}get maxComputeWorkgroupSizeY(){return 0}get maxComputeWorkgroupSizeZ(){return 0}get maxComputeWorkgroupsPerDimension(){return 0}gl;limits={};constructor(e){super(),this.gl=e}getParameter(e){return void 0===this.limits[e]&&(this.limits[e]=this.gl.getParameter(e)),this.limits[e]||0}},Ge=class extends b{device;gl;handle;colorAttachments=[];depthStencilAttachment=null;constructor(e,t){super(e,t);const r=t.handle,i=null===r;this.device=e,this.gl=e.gl,this.handle=r||i?r:this.gl.createFramebuffer(),i||(e._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),t.handle||(this.autoCreateAttachmentTextures(),this.updateAttachments()))}destroy(){super.destroy(),this.destroyed||null===this.handle||this.props.handle||this.gl.deleteFramebuffer(this.handle)}updateAttachments(){const e=this.gl.bindFramebuffer(36160,this.handle);for(let t=0;t<this.colorAttachments.length;++t){const e=this.colorAttachments[t];if(e){const r=36064+t;this._attachTextureView(r,e)}}if(this.depthStencilAttachment){const e=function(e){switch(t.textureFormatDecoder.getInfo(e).attachment){case"depth":return 36096;case"stencil":return 36128;case"depth-stencil":return 33306;default:throw new Error(`Not a depth stencil format: ${e}`)}}(this.depthStencilAttachment.props.format);this._attachTextureView(e,this.depthStencilAttachment)}if(this.device.props.debug){const e=this.gl.checkFramebufferStatus(36160);if(36053!==e)throw new Error(`Framebuffer ${function(e){switch(e){case 36053:return"success";case 36054:return"Mismatched attachments";case 36055:return"No attachments";case 36057:return"Height/width mismatch";case 36061:return"Unsupported or split attachments";case 36182:return"Samples mismatch";default:return`${e}`}}(e)}`)}this.gl.bindFramebuffer(36160,e)}_attachTextureView(e,t){const{gl:r}=this.device,{texture:i}=t,n=t.props.baseMipLevel,s=t.props.baseArrayLayer;switch(r.bindTexture(i.glTarget,i.handle),i.glTarget){case 35866:case 32879:r.framebufferTextureLayer(36160,e,i.handle,n,s);break;case 34067:const t=function(e){return e<34069?e+34069:e}(s);r.framebufferTexture2D(36160,e,t,i.handle,n);break;case 3553:r.framebufferTexture2D(36160,e,3553,i.handle,n);break;default:throw new Error("Illegal texture type")}r.bindTexture(i.glTarget,null)}resizeAttachments(e,t){if(null===this.handle)return this.width=e,void(this.height=t);super.resizeAttachments(e,t)}};var Ne=class extends u{device;handle=null;_framebuffer=null;get[Symbol.toStringTag](){return"WebGLCanvasContext"}constructor(e,t){super(t),this.device=e,this._setAutoCreatedCanvasId(`${this.device.id}-canvas`),this._configureDevice()}_configureDevice(){this.drawingBufferWidth===this._framebuffer?.width&&this.drawingBufferHeight===this._framebuffer?.height||this._framebuffer?.resize([this.drawingBufferWidth,this.drawingBufferHeight])}_getCurrentFramebuffer(){return this._framebuffer||=new Ge(this.device,{id:"canvas-context-framebuffer",handle:null,width:this.drawingBufferWidth,height:this.drawingBufferHeight}),this._framebuffer}},Ue=class extends h{device;handle=null;context2d;get[Symbol.toStringTag](){return"WebGLPresentationContext"}constructor(e,t={}){super(t),this.device=e;const r=`${this[Symbol.toStringTag]}(${this.id})`;if(!this.device.getDefaultCanvasContext().offscreenCanvas)throw new Error(`${r}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`);const i=this.canvas.getContext("2d");if(!i)throw new Error(`${r}: Failed to create 2d presentation context`);this.context2d=i,this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`),this._configureDevice(),this._startObservers()}present(){this._resizeDrawingBufferIfNeeded(),this.device.submit();const e=this.device.getDefaultCanvasContext(),[t,r]=e.getDrawingBufferSize();if(0!==this.drawingBufferWidth&&0!==this.drawingBufferHeight&&0!==t&&0!==r&&0!==e.canvas.width&&0!==e.canvas.height){if(t!==this.drawingBufferWidth||r!==this.drawingBufferHeight||e.canvas.width!==this.drawingBufferWidth||e.canvas.height!==this.drawingBufferHeight)throw new Error(`${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${t}x${r} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`);this.context2d.clearRect(0,0,this.drawingBufferWidth,this.drawingBufferHeight),this.context2d.drawImage(e.canvas,0,0)}}_configureDevice(){}_getCurrentFramebuffer(e){const t=this.device.getDefaultCanvasContext();return t.setDrawingBufferSize(this.drawingBufferWidth,this.drawingBufferHeight),t.getCurrentFramebuffer(e)}},Qe={};function Ve(e="id"){return Qe[e]=Qe[e]||1,`${e}-${Qe[e]++}`}var je=class extends r.Buffer{device;gl;handle;glTarget;glUsage;glIndexType=5123;byteLength=0;bytesUsed=0;constructor(e,t={}){super(e,t),this.device=e,this.gl=this.device.gl;const i="object"==typeof t?t.handle:void 0;var n;this.handle=i||this.gl.createBuffer(),e._setWebGLDebugMetadata(this.handle,this,{spector:{...this.props,data:typeof this.props.data}}),this.glTarget=(n=this.props.usage)&r.Buffer.INDEX?34963:n&r.Buffer.VERTEX?34962:n&r.Buffer.UNIFORM?35345:34962,this.glUsage=function(e){return e&r.Buffer.INDEX||e&r.Buffer.VERTEX?35044:e&r.Buffer.UNIFORM?35048:35044}(this.props.usage),this.glIndexType="uint32"===this.props.indexType?5125:5123,t.data?this._initWithData(t.data,t.byteOffset,t.byteLength):this._initWithByteLength(t.byteLength||0)}destroy(){!this.destroyed&&this.handle&&(this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Buffer"):(this.trackDeallocatedMemory(),this.gl.deleteBuffer(this.handle)),this.destroyed=!0,this.handle=null)}_initWithData(e,t=0,r=e.byteLength+t){const i=this.glTarget;this.gl.bindBuffer(i,this.handle),this.gl.bufferData(i,r,this.glUsage),this.gl.bufferSubData(i,t,e),this.gl.bindBuffer(i,null),this.bytesUsed=r,this.byteLength=r,this._setDebugData(e,t,r),this.props.handle?this.trackReferencedMemory(r,"Buffer"):this.trackAllocatedMemory(r)}_initWithByteLength(e){let t=e;0===e&&(t=new Float32Array(0));const r=this.glTarget;return this.gl.bindBuffer(r,this.handle),this.gl.bufferData(r,t,this.glUsage),this.gl.bindBuffer(r,null),this.bytesUsed=e,this.byteLength=e,this._setDebugData(null,0,e),this.props.handle?this.trackReferencedMemory(e,"Buffer"):this.trackAllocatedMemory(e),this}write(e,t=0){const r=ArrayBuffer.isView(e)?e:new Uint8Array(e),i=36663;this.gl.bindBuffer(i,this.handle),this.gl.bufferSubData(i,t,r),this.gl.bindBuffer(i,null),this._setDebugData(e,t,e.byteLength)}async mapAndWriteAsync(e,t=0,r=this.byteLength-t){const i=new ArrayBuffer(r);await e(i,"copied"),this.write(i,t)}async readAsync(e=0,t){return this.readSyncWebGL(e,t)}async mapAndReadAsync(e,t=0,r){return await e((await this.readAsync(t,r)).buffer,"copied")}readSyncWebGL(e=0,t){t=t??this.byteLength-e;const r=new Uint8Array(t);return this.gl.bindBuffer(36662,this.handle),this.gl.getBufferSubData(36662,e,r,0,t),this.gl.bindBuffer(36662,null),this._setDebugData(r,e,t),r}};function He(e){const t=e.toLowerCase();return["warning","error","info"].includes(t)?t:"info"}var qe=class extends m{device;handle;_compilationInfoLog="";constructor(e,t){super(e,t),this.device=e;const r=this.props.handle;switch(this.props.stage){case"vertex":this.handle=r||this.device.gl.createShader(35633);break;case"fragment":this.handle=r||this.device.gl.createShader(35632);break;default:throw new Error(this.props.stage)}e._setWebGLDebugMetadata(this.handle,this,{spector:this.props});const i=this._compile(this.source);i&&"function"==typeof i.catch&&i.catch(()=>{this.compilationStatus="error"})}destroy(){this.handle&&(this.removeStats(),this.device.gl.deleteShader(this.handle),this.destroyed=!0,this.handle.destroyed=!0)}get asyncCompilationStatus(){return this._waitForCompilationComplete().then(()=>(this._getCompilationStatus(),this.compilationStatus))}async getCompilationInfo(){return await this._waitForCompilationComplete(),this.getCompilationInfoSync()}getCompilationInfoSync(){const e=this._getCompilationInfoLog();return e?function(e){const t=e.split(/\r?\n/),r=[];for(const i of t){if(i.length<=1)continue;const e=i.trim(),t=i.split(":"),n=t[0]?.trim();if(2===t.length){const[i,s]=t;if(!i||!s){r.push({message:e,type:He(n||"info"),lineNum:0,linePos:0});continue}r.push({message:s.trim(),type:He(i),lineNum:0,linePos:0});continue}const[s,o,a,...l]=t;if(!s||!o||!a){r.push({message:t.slice(1).join(":").trim()||e,type:He(n||"info"),lineNum:0,linePos:0});continue}let c=parseInt(a,10);Number.isNaN(c)&&(c=0);let u=parseInt(o,10);Number.isNaN(u)&&(u=0),r.push({message:l.join(":").trim(),type:He(s),lineNum:c,linePos:u})}return r}(e):[]}getTranslatedSource(){return this.device.getExtension("WEBGL_debug_shaders").WEBGL_debug_shaders?.getTranslatedShaderSource(this.handle)||null}_compile(e){e=e.startsWith("#version ")?e:`#version 300 es\n${e}`;const{gl:t}=this.device;if(t.shaderSource(this.handle,e),t.compileShader(this.handle),this.device.props.debug){if(this.device.features.has("compilation-status-async-webgl"))return r.log.once(1,"Shader compilation is asynchronous")(),this._waitForCompilationComplete().then(()=>{r.log.info(2,`Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(),this._getCompilationStatus(),this.debugShader()});if(this._getCompilationStatus(),this.debugShader(),"error"===this.compilationStatus)throw new Error(this._getCompilationErrorMessage(e))}else this.compilationStatus="pending"}async _waitForCompilationComplete(){const e=async e=>await new Promise(t=>setTimeout(t,e));if(!this.device.features.has("compilation-status-async-webgl"))return void(await e(10));const{gl:t}=this.device;for(;;){if(t.getShaderParameter(this.handle,37297))return;await e(10)}}_getCompilationStatus(){this.compilationStatus=this.device.gl.getShaderParameter(this.handle,35713)?"success":"error","error"===this.compilationStatus&&this._getCompilationInfoLog()}_getCompilationErrorMessage(e){const t=`${this.props.stage} shader ${this.props.id}`,r=(i=this._getCompilationInfoLog(),i.split(/\r?\n/).find(e=>e.trim())?.trim());var i;const n=this.getCompilationInfoSync(),s=n.find(e=>"error"===e.type&&e.message.trim())||n.find(e=>e.message.trim())||n.find(e=>"error"===e.type)||n[0];if(!s)return r?`GLSL compilation errors in ${t}: ${r}`:`GLSL compilation errors in ${t}: WebGL did not provide a shader compiler log`;const o=s.lineNum?e.split(/\r?\n/)[s.lineNum-1]?.trim():void 0,a=o?`\nSource: ${o}`:"";return`GLSL compilation errors in ${t}:${s.lineNum?` line ${s.lineNum}`:""}: ${s.message.trim()||r||"WebGL did not provide a shader compiler log"}${a}`}_getCompilationInfoLog(){const e=this.device.gl.getShaderInfoLog(this.handle)?.trim();return e&&(this._compilationInfoLog=e),this._compilationInfoLog}};function Ke(e,t,i,n){if(function(e){let t=!0;for(const r in e){t=!1;break}return t}(t))return n(e);const s=e;s.pushState();try{return function(e,t){const i=e,{gl:n}=i;if(t.cullMode)switch(t.cullMode){case"none":n.disable(2884);break;case"front":n.enable(2884),n.cullFace(1028);break;case"back":n.enable(2884),n.cullFace(1029)}t.frontFace&&n.frontFace(et("frontFace",t.frontFace,{ccw:2305,cw:2304}));t.unclippedDepth&&e.features.has("depth-clip-control")&&n.enable(34383);void 0!==t.depthBias&&(n.enable(32823),n.polygonOffset(t.depthBias,t.depthBiasSlopeScale||0));if(t.provokingVertex&&e.features.has("provoking-vertex-webgl")){const e=i.getExtension("WEBGL_provoking_vertex").WEBGL_provoking_vertex,r=et("provokingVertex",t.provokingVertex,{first:36429,last:36430});e?.provokingVertexWEBGL(r)}if((t.polygonMode||t.polygonOffsetLine)&&e.features.has("polygon-mode-webgl")){if(t.polygonMode){const e=i.getExtension("WEBGL_polygon_mode").WEBGL_polygon_mode,r=et("polygonMode",t.polygonMode,{fill:6914,line:6913});e?.polygonModeWEBGL(1028,r),e?.polygonModeWEBGL(1029,r)}t.polygonOffsetLine&&n.enable(10754)}e.features.has("shader-clip-cull-distance-webgl")&&(t.clipDistance0&&n.enable(12288),t.clipDistance1&&n.enable(12289),t.clipDistance2&&n.enable(12290),t.clipDistance3&&n.enable(12291),t.clipDistance4&&n.enable(12292),t.clipDistance5&&n.enable(12293),t.clipDistance6&&n.enable(12294),t.clipDistance7&&n.enable(12295));void 0!==t.depthWriteEnabled&&n.depthMask((s=t.depthWriteEnabled,s));var s;t.depthCompare&&("always"!==t.depthCompare?n.enable(2929):n.disable(2929),n.depthFunc(Ye("depthCompare",t.depthCompare)));void 0!==t.clearDepth&&n.clearDepth(t.clearDepth);if(t.stencilWriteMask){const e=t.stencilWriteMask;n.stencilMaskSeparate(1028,e),n.stencilMaskSeparate(1029,e)}t.stencilReadMask&&r.log.warn("stencilReadMask not supported under WebGL");if(t.stencilCompare){const e=t.stencilReadMask||4294967295,r=Ye("depthCompare",t.stencilCompare);"always"!==t.stencilCompare?n.enable(2960):n.disable(2960),n.stencilFuncSeparate(1028,r,0,e),n.stencilFuncSeparate(1029,r,0,e)}if(t.stencilPassOperation&&t.stencilFailOperation&&t.stencilDepthFailOperation){const e=Xe("stencilPassOperation",t.stencilPassOperation),r=Xe("stencilFailOperation",t.stencilFailOperation),i=Xe("stencilDepthFailOperation",t.stencilDepthFailOperation);n.stencilOpSeparate(1028,r,i,e),n.stencilOpSeparate(1029,r,i,e)}switch(t.blend){case!0:n.enable(3042);break;case!1:n.disable(3042)}if(t.blendColorOperation||t.blendAlphaOperation){const e=Ze("blendColorOperation",t.blendColorOperation||"add"),r=Ze("blendAlphaOperation",t.blendAlphaOperation||"add");n.blendEquationSeparate(e,r);const i=Je("blendColorSrcFactor",t.blendColorSrcFactor||"one"),s=Je("blendColorDstFactor",t.blendColorDstFactor||"zero"),o=Je("blendAlphaSrcFactor",t.blendAlphaSrcFactor||"one"),a=Je("blendAlphaDstFactor",t.blendAlphaDstFactor||"zero");n.blendFuncSeparate(i,s,o,a)}}(e,t),le(s.gl,i),n(e)}finally{s.popState()}}function Ye(e,t){return et(e,t,{never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519})}function Xe(e,t){return et(e,t,{keep:7680,zero:0,replace:7681,invert:5386,"increment-clamp":7682,"decrement-clamp":7683,"increment-wrap":34055,"decrement-wrap":34056})}function Ze(e,t){return et(e,t,{add:32774,subtract:32778,"reverse-subtract":32779,min:32775,max:32776})}function Je(e,t,r="color"){return et(e,t,{one:1,zero:0,src:768,"one-minus-src":769,dst:774,"one-minus-dst":775,"src-alpha":770,"one-minus-src-alpha":771,"dst-alpha":772,"one-minus-dst-alpha":773,"src-alpha-saturated":776,constant:"color"===r?32769:32771,"one-minus-constant":"color"===r?32770:32772,src1:768,"one-minus-src1":769,"src1-alpha":770,"one-minus-src1-alpha":771})}function et(e,t,r){if(!(t in r))throw new Error(function(e,t){return`Illegal parameter ${t} for ${e}`}(e,t));return r[t]}function tt(e){const t={};return e.addressModeU&&(t[10242]=rt(e.addressModeU)),e.addressModeV&&(t[10243]=rt(e.addressModeV)),e.addressModeW&&(t[32882]=rt(e.addressModeW)),e.magFilter&&(t[10240]=it(e.magFilter)),(e.minFilter||e.mipmapFilter)&&(t[10241]=function(e,t="none"){if(!t)return it(e);switch(t){case"none":return it(e);case"nearest":switch(e){case"nearest":return 9984;case"linear":return 9985}break;case"linear":switch(e){case"nearest":return 9986;case"linear":return 9987}}}(e.minFilter||"linear",e.mipmapFilter)),void 0!==e.lodMinClamp&&(t[33082]=e.lodMinClamp),void 0!==e.lodMaxClamp&&(t[33083]=e.lodMaxClamp),"comparison-sampler"===e.type&&(t[34892]=34894),e.compare&&(t[34893]=Ye("compare",e.compare)),e.maxAnisotropy&&(t[34046]=e.maxAnisotropy),t}function rt(e){switch(e){case"clamp-to-edge":return 33071;case"repeat":return 10497;case"mirror-repeat":return 33648}}function it(e){switch(e){case"nearest":return 9728;case"linear":return 9729}}var nt=class extends t.Sampler{device;handle;parameters;constructor(e,t){super(e,t),this.device=e,this.parameters=tt(t),this.handle=t.handle||this.device.gl.createSampler(),this._setSamplerParameters(this.parameters)}destroy(){this.handle&&(this.device.gl.deleteSampler(this.handle),this.handle=void 0)}toString(){return`Sampler(${this.id},${JSON.stringify(this.props)})`}_setSamplerParameters(e){for(const[t,r]of Object.entries(e)){const e=Number(t);switch(e){case 33082:case 33083:this.device.gl.samplerParameterf(this.handle,e,r);break;default:this.device.gl.samplerParameteri(this.handle,e,r)}}}};function st(e,t,r){if(function(e){for(const t in e)return!1;return!0}(t))return r(e);const{nocatch:i=!0}=t,n=de.get(e);let s;if(n.push(),le(e,t),i)s=r(e),n.pop();else try{s=r(e)}finally{n.pop()}return s}var ot=class extends d{device;gl;handle;texture;constructor(e,r){super(e,{...t.Texture.defaultProps,...r}),this.device=e,this.gl=this.device.gl,this.handle=null,this.texture=r.texture}};function at(e){return lt[e]}var lt={5124:"sint32",5125:"uint32",5122:"sint16",5123:"uint16",5120:"sint8",5121:"uint8",5126:"float32",5131:"float16",33635:"uint16",32819:"uint16",32820:"uint16",33640:"uint32",35899:"uint32",35902:"uint32",34042:"uint32",36269:"uint32"},ct=class extends t.Texture{device;gl;handle;sampler=void 0;view;glTarget;glFormat;glType;glInternalFormat;compressed;_textureUnit=0;_framebuffer=null;_framebufferAttachmentKey=null;constructor(e,t){super(e,t,{byteAlignment:1}),this.device=e,this.gl=this.device.gl;const r=Oe(this.props.format);if(this.glTarget=function(e){switch(e){case"1d":break;case"2d":return 3553;case"3d":return 32879;case"cube":return 34067;case"2d-array":return 35866}throw new Error(e)}(this.props.dimension),this.glInternalFormat=r.internalFormat,this.glFormat=r.format,this.glType=r.type,this.compressed=r.compressed,this.isHandleBorrowed&&void 0===this.props.handle)throw new Error("Borrowed WebGL textures require a texture handle");if(this.handle=this.props.handle||this.gl.createTexture(),this.device._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),!this.isHandleBorrowed){this.gl.bindTexture(this.glTarget,this.handle);const{dimension:e,width:r,height:i,depth:n,mipLevels:s,glTarget:o,glInternalFormat:a}=this;if(!this.compressed)switch(e){case"2d":case"cube":this.gl.texStorage2D(o,s,a,r,i);break;case"2d-array":case"3d":this.gl.texStorage3D(o,s,a,r,i,n);break;default:throw new Error(e)}this.gl.bindTexture(this.glTarget,null),this._initializeData(t.data)}this.ownsHandle?this.trackAllocatedMemory(this.getAllocatedByteLength(),"Texture"):this.trackReferencedMemory(this.getAllocatedByteLength(),"Texture"),this.isHandleBorrowed||this.setSampler(this.props.sampler),this.view=new ot(this.device,{...this.props,texture:this}),Object.seal(this)}destroy(){this.handle&&(this._framebuffer?.destroy(),this._framebuffer=null,this._framebufferAttachmentKey=null,this.removeStats(),this.ownsHandle?(this.gl.deleteTexture(this.handle),this.trackDeallocatedMemory("Texture")):this.trackDeallocatedReferencedMemory("Texture"),this.destroyed=!0)}createView(e){return new ot(this.device,{...e,texture:this})}clone(e){if(this.isHandleBorrowed&&e&&(e.width!==this.width||e.height!==this.height))throw new Error(`Cannot resize borrowed read-only ${this}`);return super.clone(e)}setSampler(e={}){this._assertWritable("set sampler parameters on"),super.setSampler(e);const t=tt(this.sampler.props);this._setSamplerParameters(t)}copyExternalImage(e){this._assertWritable("copy external image data into");const t=this._normalizeCopyExternalImageOptions(e);if(t.sourceX||t.sourceY)throw new Error("WebGL does not support sourceX/sourceY)");const{glFormat:r,glType:i}=this,{image:n,depth:s,mipLevel:o,x:a,y:l,z:c,width:u,height:h}=t,d=ut(this.glTarget,this.dimension,c),f=t.flipY?{37440:!0}:{};return this.gl.bindTexture(this.glTarget,this.handle),st(this.gl,f,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(d,o,a,l,u,h,r,i,n);break;case"2d-array":case"3d":this.gl.texSubImage3D(d,o,a,l,c,u,h,s,r,i,n)}}),this.gl.bindTexture(this.glTarget,null),{width:t.width,height:t.height}}copyElementImage(e){this._assertWritable("copy element image data into");const t=this._normalizeCopyElementImageOptions(e),{glFormat:r}=this,{element:i,depth:n,mipLevel:s,sourceX:o,sourceY:a,sourceWidth:l,sourceHeight:c,x:u,y:h,z:d,width:f,height:g}=t,m=ut(this.glTarget,this.dimension,d),p=t.flipY?{37440:!0}:{},b=this.gl;if(1!==n||"2d"!==this.dimension&&"cube"!==this.dimension)throw new Error(`${this} copyElementImage only supports 2d and cube textures on WebGL`);if(0!==s||0!==u||0!==h)throw new Error(`${this} copyElementImage only supports full base-level uploads on WebGL`);if("function"!=typeof b.texElementImage2D)throw new Error(`${this} copyElementImage is not supported by this WebGL implementation`);return this.gl.bindTexture(this.glTarget,this.handle),st(this.gl,p,()=>{b.texElementImage2D?.(m,r,i,{sx:o,sy:a,swidth:l??f,sheight:c??g,width:f,height:g})}),this.gl.bindTexture(this.glTarget,null),{width:t.width,height:t.height}}copyImageData(e){super.copyImageData(e)}readBuffer(e={},t){if(!t)throw new Error(`${this} readBuffer requires a destination buffer`);const r=this._getSupportedColorReadOptions(e),i=e.byteOffset??0,n=this.computeMemoryLayout(r);if(t.byteLength<i+n.byteLength)throw new Error(`${this} readBuffer target is too small (${t.byteLength} < ${i+n.byteLength})`);const s=t;this.gl.bindBuffer(35051,s.handle);try{this._readColorTextureLayers(r,n,e=>{this.gl.readPixels(r.x,r.y,r.width,r.height,this.glFormat,this.glType,i+e)})}finally{this.gl.bindBuffer(35051,null)}return t}async readDataAsync(e={}){throw new Error(`${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`)}writeBuffer(e,t={}){this._assertWritable("write buffer data into");const r=this._normalizeTextureWriteOptions(t),{width:i,height:n,depthOrArrayLayers:s,mipLevel:o,byteOffset:a,x:l,y:c,z:u}=r,{glFormat:h,glType:d,compressed:f}=this,g=ut(this.glTarget,this.dimension,u);if(f)throw new Error("writeBuffer for compressed textures is not implemented in WebGL");const{bytesPerPixel:m}=this.device.getTextureFormatInfo(this.format),p=m?r.bytesPerRow/m:void 0,b={3317:this.byteAlignment,...void 0!==p?{3314:p}:{},32878:r.rowsPerImage};this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,e.handle),st(this.gl,b,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(g,o,l,c,i,n,h,d,a);break;case"2d-array":case"3d":this.gl.texSubImage3D(g,o,l,c,u,i,n,s,h,d,a)}}),this.gl.bindBuffer(35052,null),this.gl.bindTexture(this.glTarget,null)}writeData(e,t={}){this._assertWritable("write data into");const r=this._normalizeTextureWriteOptions(t),i=ArrayBuffer.isView(e)?e:new Uint8Array(e),{width:n,height:s,depthOrArrayLayers:o,mipLevel:a,x:l,y:c,z:u,byteOffset:h}=r,{glFormat:d,glType:f,compressed:g}=this,m=ut(this.glTarget,this.dimension,u);let p;if(!g){const{bytesPerPixel:e}=this.device.getTextureFormatInfo(this.format);e&&(p=r.bytesPerRow/e)}const b=this.compressed?{}:{3317:this.byteAlignment,...void 0!==p?{3314:p}:{},32878:r.rowsPerImage},y=function(e,t){if(t%e.BYTES_PER_ELEMENT!==0)throw new Error(`Texture byteOffset ${t} must align to typed array element size ${e.BYTES_PER_ELEMENT}`);return t/e.BYTES_PER_ELEMENT}(i,h),v=g?function(e,t=0){return t?new e.constructor(e.buffer,e.byteOffset+t,(e.byteLength-t)/e.BYTES_PER_ELEMENT):e}(i,h):i,w=this._getMipLevelSize(a),x=0===l&&0===c&&0===u&&n===w.width&&s===w.height&&o===w.depthOrArrayLayers;this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,null),st(this.gl,b,()=>{switch(this.dimension){case"2d":case"cube":g?x?this.gl.compressedTexImage2D(m,a,d,n,s,0,v):this.gl.compressedTexSubImage2D(m,a,l,c,n,s,d,v):this.gl.texSubImage2D(m,a,l,c,n,s,d,f,i,y);break;case"2d-array":case"3d":g?x?this.gl.compressedTexImage3D(m,a,d,n,s,o,0,v):this.gl.compressedTexSubImage3D(m,a,l,c,u,n,s,o,d,v):this.gl.texSubImage3D(m,a,l,c,u,n,s,o,d,f,i,y)}}),this.gl.bindTexture(this.glTarget,null)}_getRowByteAlignment(e,t){return 1}_getFramebuffer(){return this._framebuffer||=this.device.createFramebuffer({id:`framebuffer-for-${this.id}`,width:this.width,height:this.height,colorAttachments:[this]}),this._framebuffer}readDataSyncWebGL(e={}){const t=this._getSupportedColorReadOptions(e),i=this.computeMemoryLayout(t),n=at(this.glType),s=r.getTypedArrayConstructor(n),o=new s(i.byteLength/s.BYTES_PER_ELEMENT);return this._readColorTextureLayers(t,i,e=>{const r=new s(o.buffer,o.byteOffset+e,i.bytesPerImage/s.BYTES_PER_ELEMENT);this.gl.readPixels(t.x,t.y,t.width,t.height,this.glFormat,this.glType,r)}),o.buffer}_readColorTextureLayers(e,t,r){const i=this._getFramebuffer(),n=t.bytesPerRow/t.bytesPerPixel,s={3333:this.byteAlignment,...n!==e.width?{3330:n}:{}},o=this.gl.getParameter(3074),a=this.gl.bindFramebuffer(36160,i.handle);try{this.gl.readBuffer(36064),st(this.gl,s,()=>{for(let n=0;n<e.depthOrArrayLayers;n++)this._attachReadSubresource(i,e.mipLevel,e.z+n),r(n*t.bytesPerImage)})}finally{this.gl.bindFramebuffer(36160,a||null),this.gl.readBuffer(o)}}_attachReadSubresource(e,t,r){const i=`${t}:${r}`;if(this._framebufferAttachmentKey!==i){switch(this.dimension){case"2d":this.gl.framebufferTexture2D(36160,36064,3553,this.handle,t);break;case"cube":this.gl.framebufferTexture2D(36160,36064,ut(this.glTarget,this.dimension,r),this.handle,t);break;case"2d-array":case"3d":this.gl.framebufferTextureLayer(36160,36064,this.handle,t,r);break;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}if(this.device.props.debug){const t=Number(this.gl.checkFramebufferStatus(36160));if(36053!==t)throw new Error(`${e} incomplete for ${this} readback (${t})`)}this._framebufferAttachmentKey=i}}generateMipmapsWebGL(e){if(this._assertWritable("generate mipmaps for"),this.device.isTextureFormatRenderable(this.props.format)&&this.device.isTextureFormatFilterable(this.props.format)||(r.log.warn(`${this} is not renderable or filterable, may not be able to generate mipmaps`)(),e?.force))try{this.gl.bindTexture(this.glTarget,this.handle),this.gl.generateMipmap(this.glTarget)}catch(t){r.log.warn(`Error generating mipmap for ${this}: ${t.message}`)()}finally{this.gl.bindTexture(this.glTarget,null)}}_setSamplerParameters(e){r.log.level>=2&&r.log.log(2,`${this.id} sampler parameters`,this.device.getGLKeys(e))(),this.gl.bindTexture(this.glTarget,this.handle);for(const[t,r]of Object.entries(e)){const e=Number(t),i=r;switch(e){case 33082:case 33083:this.gl.texParameterf(this.glTarget,e,i);break;case 10240:case 10241:case 10242:case 10243:case 32882:case 34892:case 34893:this.gl.texParameteri(this.glTarget,e,i);break;case 34046:this.device.features.has("texture-filterable-anisotropic-webgl")&&this.gl.texParameteri(this.glTarget,e,i)}}this.gl.bindTexture(this.glTarget,null)}_getActiveUnit(){return this.gl.getParameter(34016)-33984}_bind(e){const{gl:t}=this;return void 0!==e&&(this._textureUnit=e,t.activeTexture(33984+e)),t.bindTexture(this.glTarget,this.handle),e}_unbind(e){const{gl:t}=this;return void 0!==e&&(this._textureUnit=e,t.activeTexture(33984+e)),t.bindTexture(this.glTarget,null),e}_assertWritable(e){if(this.isHandleBorrowed)throw new Error(`Cannot ${e} borrowed read-only ${this}`)}};function ut(e,t,r){return"cube"===t?34069+r:e}function ht(e,t,r,i){const n=e;let s=i;!0===s&&(s=1),!1===s&&(s=0);const o="number"==typeof s?[s]:s;switch(r){case 35678:case 35680:case 35679:case 35682:case 36289:case 36292:case 36293:case 36298:case 36299:case 36300:case 36303:case 36306:case 36307:case 36308:case 36311:if("number"!=typeof i)throw new Error("samplers must be set to integers");return e.uniform1i(t,i);case 5126:return e.uniform1fv(t,o);case 35664:return e.uniform2fv(t,o);case 35665:return e.uniform3fv(t,o);case 35666:return e.uniform4fv(t,o);case 5124:case 35670:return e.uniform1iv(t,o);case 35667:case 35671:return e.uniform2iv(t,o);case 35668:case 35672:return e.uniform3iv(t,o);case 35669:case 35673:return e.uniform4iv(t,o);case 5125:return n.uniform1uiv(t,o,1);case 36294:return n.uniform2uiv(t,o,2);case 36295:return n.uniform3uiv(t,o,3);case 36296:return n.uniform4uiv(t,o,4);case 35674:return e.uniformMatrix2fv(t,!1,o);case 35675:return e.uniformMatrix3fv(t,!1,o);case 35676:return e.uniformMatrix4fv(t,!1,o);case 35685:return n.uniformMatrix2x3fv(t,!1,o);case 35686:return n.uniformMatrix2x4fv(t,!1,o);case 35687:return n.uniformMatrix3x2fv(t,!1,o);case 35688:return n.uniformMatrix3x4fv(t,!1,o);case 35689:return n.uniformMatrix4x2fv(t,!1,o);case 35690:return n.uniformMatrix4x3fv(t,!1,o)}throw new Error("Illegal uniform")}function dt(e){return mt[e]}function ft(e){return Boolean(pt[e])}function gt(e){return pt[e]}var mt={5126:"f32",35664:"vec2<f32>",35665:"vec3<f32>",35666:"vec4<f32>",5124:"i32",35667:"vec2<i32>",35668:"vec3<i32>",35669:"vec4<i32>",5125:"u32",36294:"vec2<u32>",36295:"vec3<u32>",36296:"vec4<u32>",35670:"f32",35671:"vec2<f32>",35672:"vec3<f32>",35673:"vec4<f32>",35674:"mat2x2<f32>",35685:"mat2x3<f32>",35686:"mat2x4<f32>",35687:"mat3x2<f32>",35675:"mat3x3<f32>",35688:"mat3x4<f32>",35689:"mat4x2<f32>",35690:"mat4x3<f32>",35676:"mat4x4<f32>"},pt={35678:{viewDimension:"2d",sampleType:"float"},35680:{viewDimension:"cube",sampleType:"float"},35679:{viewDimension:"3d",sampleType:"float"},35682:{viewDimension:"3d",sampleType:"depth"},36289:{viewDimension:"2d-array",sampleType:"float"},36292:{viewDimension:"2d-array",sampleType:"depth"},36293:{viewDimension:"cube",sampleType:"float"},36298:{viewDimension:"2d",sampleType:"sint"},36299:{viewDimension:"3d",sampleType:"sint"},36300:{viewDimension:"cube",sampleType:"sint"},36303:{viewDimension:"2d-array",sampleType:"uint"},36306:{viewDimension:"2d",sampleType:"uint"},36307:{viewDimension:"3d",sampleType:"uint"},36308:{viewDimension:"cube",sampleType:"uint"},36311:{viewDimension:"2d-array",sampleType:"uint"}},bt={uint8:5121,sint8:5120,unorm8:5121,snorm8:5120,uint16:5123,sint16:5122,unorm16:5123,snorm16:5122,uint32:5125,sint32:5124,float16:5131,float32:5126};function yt(e,t,i={}){const n={attributes:[],bindings:[]};n.attributes=function(e,t){const r=[],i=e.getProgramParameter(t,35721);for(let n=0;n<i;n++){const i=e.getActiveAttrib(t,n);if(!i)throw new Error("activeInfo");const{name:s,type:o}=i,a=e.getAttribLocation(t,s);if(a>=0){const e=dt(o),t=/instance/i.test(s)?"instance":"vertex";r.push({name:s,location:a,stepMode:t,type:e})}}return r.sort((e,t)=>e.location-t.location),r}(e,t);const s=function(e,t,i){const n=[],s=function(e,t,r){const i=new Map;for(const s of r.uniformBlockLayouts||[])i.set(s.name,Tt(s));for(const s of r.shaderLayout?.bindings||[])Bt(s)&&i.set(s.name,s);const n=new Map;for(const s of i.values()){const r=wt(e,t,s.name);if(!r)continue;const{blockIndex:i,blockName:o}=r;if(n.has(i))throw new Error(`Multiple supplied uniform block layouts resolve to active WebGL block "${o}"`);n.set(i,{name:o,location:i,byteLength:s.minBindingSize,vertex:Boolean(s.visibility&&1&s.visibility),fragment:Boolean(s.visibility&&2&s.visibility),uniformCount:s.uniforms.length,uniforms:s.uniforms.map(e=>({...e}))})}return n}(e,t,i);for(const[l,c]of s){n.push(c);try{vt(xt(e,t,l,c.name),c)}catch(a){const e=a instanceof Error?a.message:String(a);r.log.once(0,`WebGL uniform block reflection failed for "${c.name}"; using supplied std140 metadata. ${e}`)()}}const o=e.getProgramParameter(t,35382);if(!Number.isInteger(o)||o<0)throw new Error(`Failed to reflect WebGL uniform blocks: ACTIVE_UNIFORM_BLOCKS returned ${String(o)}`);for(let r=0;r<o;r++)s.has(r)||n.push(xt(e,t,r));return n.sort((e,t)=>e.location-t.location),n}(e,t,i);for(const r of s){const e=r.uniforms.map(e=>({name:e.name,format:e.format,byteOffset:e.byteOffset,byteStride:e.byteStride,arrayLength:e.arrayLength}));n.bindings.push({type:"uniform",name:r.name,group:0,location:r.location,visibility:(r.vertex?1:0)|(r.fragment?2:0),minBindingSize:r.byteLength,uniforms:e})}const o=function(e,t){const r=[],i=e.getProgramParameter(t,35718);for(let n=0;n<i;n++){const i=e.getActiveUniform(t,n);if(!i)throw new Error("activeInfo");const{name:s,size:o,type:a}=i,{name:l,isArray:c}=Et(s);let u=e.getUniformLocation(t,l);const h={location:u,name:l,size:o,type:a,isArray:c};if(r.push(h),h.size>1)for(let n=0;n<h.size;n++){const i=`${l}[${n}]`;u=e.getUniformLocation(t,i);const s={...h,name:i,location:u};r.push(s)}}return r}(e,t);let a=0;for(const r of o)if(ft(r.type)){const{viewDimension:e,sampleType:t}=gt(r.type);n.bindings.push({type:"texture",name:r.name,group:0,location:a,viewDimension:e,sampleType:t}),r.textureUnit=a,a+=1}o.length&&(n.uniforms=o);const l=function(e,t){const i=[],n=e.getProgramParameter(t,35971);for(let s=0;s<n;s++){const n=e.getTransformFeedbackVarying(t,s);if(!n)throw new Error("activeInfo");const{name:o,type:a,size:l}=n,c=dt(a),{type:u,components:h}=r.getVariableShaderTypeInfo(c);i.push({location:s,name:o,type:u,size:l*h})}return i.sort((e,t)=>e.location-t.location),i}(e,t);return l?.length&&(n.varyings=l),n}function vt(e,t){for(const r of e.uniforms){const e=t.uniforms.find(e=>r.name===e.name||r.name.endsWith(`.${e.name}`));if(!e)throw new Error(`Failed to validate WebGL uniform block "${t.name}": reflected unexpected member "${r.name}"`);if(r.format!==e.format||r.arrayLength!==e.arrayLength||r.byteOffset!==e.byteOffset||r.byteStride!==e.byteStride)throw new Error(`Failed to validate WebGL uniform block "${t.name}": reflected layout for "${r.name}" does not match supplied std140 metadata`)}}function wt(e,t,r){const i=r.endsWith("Uniforms")?[r,r.slice(0,-8)]:[r,`${r}Uniforms`];for(const n of i){const r=e.getUniformBlockIndex(t,n);if(4294967295!==r){if(!Number.isInteger(r)||r<0)throw new Error(`Failed to resolve WebGL uniform block "${n}": getUniformBlockIndex returned ${String(r)}`);return{blockIndex:r,blockName:n}}}return null}function xt(e,t,i,n){const s=n||e.getActiveUniformBlockName(t,i);if(!s)throw new Error(`Failed to reflect WebGL uniform block at index ${i}: missing block name`);const o=(r,n)=>{const o=e.getActiveUniformBlockParameter(t,i,r);if(null==o)throw new Error(`Failed to reflect WebGL uniform block "${s}": ${n} returned null`);return o},a=Pt(o(35391,"UNIFORM_BLOCK_BINDING"),s,"UNIFORM_BLOCK_BINDING",0),l=Pt(o(35392,"UNIFORM_BLOCK_DATA_SIZE"),s,"UNIFORM_BLOCK_DATA_SIZE",0),c=Pt(o(35394,"UNIFORM_BLOCK_ACTIVE_UNIFORMS"),s,"UNIFORM_BLOCK_ACTIVE_UNIFORMS",0),u=St(o(35395,"UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES"),s,"UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES",c),h=_t(e,t,u,35383,"UNIFORM_TYPE",s,c),d=_t(e,t,u,35384,"UNIFORM_SIZE",s,c),f=_t(e,t,u,35386,"UNIFORM_BLOCK_INDEX",s,c),g=_t(e,t,u,35387,"UNIFORM_OFFSET",s,c),m=_t(e,t,u,35388,"UNIFORM_ARRAY_STRIDE",s,c),p=[];for(let r=0;r<c;r++){if(f[r]!==i)throw new Error(`Failed to reflect WebGL uniform block "${s}": active uniform index ${u[r]} belongs to block ${f[r]}, expected ${i}`);const n=u[r],o=e.getActiveUniform(t,n);if(!o)throw new Error(`Failed to reflect WebGL uniform block "${s}": getActiveUniform(${n}) returned null`);const a=Pt(h[r],s,`UNIFORM_TYPE[${r}]`,1),l=Pt(d[r],s,`UNIFORM_SIZE[${r}]`,1),c=Pt(g[r],s,`UNIFORM_OFFSET[${r}]`,0),b=Pt(m[r],s,`UNIFORM_ARRAY_STRIDE[${r}]`,0);if(o.type!==a||o.size!==l)throw new Error(`Failed to reflect WebGL uniform block "${s}": getActiveUniform(${n}) disagrees with getActiveUniforms`);p.push({name:o.name,format:dt(a),arrayLength:l,byteOffset:c,byteStride:b})}const b={name:s,location:a,byteLength:l,vertex:Boolean(o(35396,"UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER")),fragment:Boolean(o(35398,"UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER")),uniformCount:c,uniforms:p},y=new Set(b.uniforms.map(e=>e.name.split(".")[0]).filter(e=>Boolean(e))),v=b.name.replace(/Uniforms$/,"");if(1===y.size&&!y.has(b.name)&&!y.has(v)){const[e]=y;r.log.warn(`Uniform block "${b.name}" uses GLSL instance "${e}". luma.gl binds uniform buffers by block name ("${b.name}") and alias ("${v}"). Prefer matching the instance name to one of those to avoid confusing silent mismatches.`)()}return b}function _t(e,t,r,i,n,s,o){const a=e.getActiveUniforms(t,r,i);if(null===a)throw new Error(`Failed to reflect WebGL uniform block "${s}": ${n} returned null`);return St(a,s,n,o)}function St(e,t,r,i){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))throw new Error(`Failed to reflect WebGL uniform block "${t}": ${r} returned a non-array value`);const n=Array.from(e);if(n.length!==i||n.some(e=>!Number.isInteger(e)))throw new Error(`Failed to reflect WebGL uniform block "${t}": ${r} returned ${n.length} invalid values, expected ${i}`);return n}function Pt(e,t,r,i){if(!Number.isInteger(e)||e<i)throw new Error(`Failed to reflect WebGL uniform block "${t}": ${r} returned ${String(e)}`);return e}function Tt(e){const t=F(e.uniformTypes,{layout:"std140"}),r=function(e,t){const r=[],i=(e,s)=>{if("string"==typeof s){const i=t[e];if(!i)throw new Error(`Missing std140 layout field ${e}`);return void r.push({name:e,format:i.shaderType,arrayLength:1,byteOffset:4*i.offset,byteStride:0})}if(Array.isArray(s))n(e,s[0],s[1]);else for(const[t,r]of Object.entries(s))i(`${e}.${t}`,r)},n=(e,i,n)=>{if("string"==typeof i){const i=t[`${e}[0]`],s=n>1?t[`${e}[1]`]:void 0;if(!i)throw new Error(`Missing std140 array layout field ${e}[0]`);return void r.push({name:`${e}[0]`,format:i.shaderType,arrayLength:n,byteOffset:4*i.offset,byteStride:s?4*(s.offset-i.offset):0})}if(Array.isArray(i))throw new Error(`Nested uniform arrays are not supported for ${e}`);for(const[s,o]of Object.entries(i)){if("string"!=typeof o)throw new Error(`Composite uniform array members are not supported for ${e}`);const i=`${e}[0].${s}`,a=`${e}[1].${s}`,l=t[i],c=n>1?t[a]:void 0;if(!l)throw new Error(`Missing std140 array layout field ${i}`);r.push({name:i,format:l.shaderType,arrayLength:n,byteOffset:4*l.offset,byteStride:c?4*(c.offset-l.offset):0})}};for(const[s,o]of Object.entries(e))i(s,o);return r}(e.uniformTypes,t.fields);return{type:"uniform",name:e.name,group:0,location:0,minBindingSize:t.byteLength,uniforms:r}}function Bt(e){return"uniform"===e.type&&Number.isInteger(e.minBindingSize)&&e.minBindingSize>=0&&Array.isArray(e.uniforms)&&e.uniforms.every(e=>"string"==typeof e.name&&"string"==typeof e.format&&Number.isInteger(e.arrayLength)&&e.arrayLength>0&&Number.isInteger(e.byteOffset)&&e.byteOffset>=0&&Number.isInteger(e.byteStride)&&e.byteStride>=0)}function Et(e){if("]"!==e[e.length-1])return{name:e,length:1,isArray:!1};const t=/([^[]*)(\[[0-9]+\])?/.exec(e);return{name:s(t?.[1],`Failed to parse GLSL uniform name ${e}`),length:t?.[2]?1:0,isArray:Boolean(t?.[2])}}var Lt=class extends y{device;handle;vs;fs;introspectedLayout;bindings={};uniforms={};varyings=null;_uniformCount=0;_uniformSetters={};get[Symbol.toStringTag](){return"WEBGLRenderPipeline"}constructor(e,t){super(e,t),this.device=e;const i=this.sharedRenderPipeline||this.device._createSharedRenderPipelineWebGL(t);this.sharedRenderPipeline=i,this.handle=i.handle,this.vs=i.vs,this.fs=i.fs,this.linkStatus=i.linkStatus,this.introspectedLayout=yt(this.device.gl,this.handle,{uniformBlockLayouts:t._uniformBlockLayouts,shaderLayout:t.shaderLayout}),this.device._setWebGLDebugMetadata(this.handle,this,{spector:{id:this.props.id}}),this.shaderLayout=t.shaderLayout?function(e,t){const i={...e,attributes:e.attributes.map(e=>({...e})),bindings:e.bindings.map(e=>({...e}))};for(const n of t?.attributes||[]){const e=i.attributes.find(e=>e.name===n.name);e?(e.type=n.type||e.type,e.stepMode=n.stepMode||e.stepMode):r.log.warn(`shader layout attribute ${n.name} not present in shader`)}for(const n of t?.bindings||[]){const e=At(i,n.name);e?Object.assign(e,n):r.log.warn(`shader layout binding ${n.name} not present in shader`)}return i}(this.introspectedLayout,t.shaderLayout):this.introspectedLayout}destroy(){this.destroyed||(this.sharedRenderPipeline&&!this.props._sharedRenderPipeline&&this.sharedRenderPipeline.destroy(),this.destroyResource())}setBindings(e,t){const i=_(x(this.shaderLayout,e));for(const[n,s]of Object.entries(i)){const e=At(this.shaderLayout,n);if(e){switch(s||r.log.warn(`Unsetting binding "${n}" in render pipeline "${this.id}"`)(),e.type){case"uniform":if(!(s instanceof je||s.buffer instanceof je))throw new Error("buffer value");break;case"texture":if(!(s instanceof ot||s instanceof ct||s instanceof Ge))throw new Error(`${this} Bad texture binding for ${n}`);break;case"sampler":r.log.warn(`Ignoring sampler ${n}`)();break;default:throw new Error(e.type)}this.bindings[n]=s}else{const e=this.shaderLayout.bindings.map(e=>`"${e.name}"`).join(", ");t?.disableWarnings||r.log.warn(`No binding "${n}" in render pipeline "${this.id}", expected one of ${e}`,s)()}}}draw(e){const t=e.renderPass,r=e.bindGroups?_(e.bindGroups):e.bindings||this.bindings;return t.setPipeline(this),t.setBindings(r),t.setVertexArray(e.vertexArray),t.draw({parameters:e.parameters,topology:e.topology,isInstanced:e.isInstanced,vertexCount:e.vertexCount,indexCount:e.indexCount,instanceCount:e.instanceCount,firstVertex:e.firstVertex,firstIndex:e.firstIndex,firstInstance:e.firstInstance,baseVertex:e.baseVertex,transformFeedback:e.transformFeedback,uniforms:e.uniforms})}_areTexturesRenderable(e){let t=!0;for(const i of this.shaderLayout.bindings)Ct(e,i.name)||(r.log.warn(`Binding ${i.name} not found in ${this.id}`)(),t=!1);return t}_applyBindings(e,t){if(this._syncLinkStatus(),"success"!==this.linkStatus)return;const{gl:i}=this.device;i.useProgram(this.handle);let n=0,s=0;for(const o of this.shaderLayout.bindings){const t=Ct(e,o.name);if(!t)throw new Error(`No value for binding ${o.name} in ${this.id}`);switch(o.type){case"uniform":const{name:e}=o,a=i.getUniformBlockIndex(this.handle,e);if(4294967295===a)throw new Error(`Invalid uniform block name ${e}`);if(i.uniformBlockBinding(this.handle,a,s),t instanceof je)i.bindBufferBase(35345,s,t.handle);else{const e=t;i.bindBufferRange(35345,s,e.buffer.handle,e.offset||0,e.size||e.buffer.byteLength-(e.offset||0))}s+=1;break;case"texture":if(!(t instanceof ot||t instanceof ct||t instanceof Ge))throw new Error("texture");let l;if(t instanceof ot)l=t.texture;else if(t instanceof ct)l=t;else{if(!(t instanceof Ge&&t.colorAttachments[0]instanceof ot))throw new Error("No texture");r.log.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(),l=t.colorAttachments[0].texture}i.activeTexture(33984+n),i.bindTexture(l.glTarget,l.handle),n+=1;break;case"sampler":break;case"storage":case"read-only-storage":throw new Error(`binding type '${o.type}' not supported in WebGL`)}}}_applyUniforms(e){for(const t of this.shaderLayout.uniforms||[]){const{name:r,location:i,type:n,textureUnit:s}=t,o=e[r]??s;void 0!==o&&ht(this.device.gl,i,n,o)}}_syncLinkStatus(){this.linkStatus=this.sharedRenderPipeline.linkStatus}};function At(e,t){return e.bindings.find(e=>e.name===t||e.name===`${t}Uniforms`||`${e.name}Uniforms`===t)}function Ct(e,t){return e[t]||e[`${t}Uniforms`]||e[t.replace(/Uniforms$/,"")]}var Ft=class extends v{device;handle;vs;fs;linkStatus="pending";constructor(e,t){super(e,t),this.device=e,this.handle=t.handle||this.device.gl.createProgram(),this.vs=t.vs,this.fs=t.fs,t.varyings&&t.varyings.length>0&&this.device.gl.transformFeedbackVaryings(this.handle,t.varyings,t.bufferMode||35981),this._linkShaders()}destroy(){this.destroyed||(this.device.gl.useProgram(null),this.device.gl.deleteProgram(this.handle),this.handle.destroyed=!0,this.destroyResource())}async _linkShaders(){const{gl:e}=this.device;if(e.attachShader(this.handle,this.vs.handle),e.attachShader(this.handle,this.fs.handle),r.log.time(4,`linkProgram for ${this.id}`)(),e.linkProgram(this.handle),r.log.timeEnd(4,`linkProgram for ${this.id}`)(),!this.device.features.has("compilation-status-async-webgl")){const e=this._getLinkStatus();return void this._reportLinkStatus(e)}r.log.once(1,"RenderPipeline linking is asynchronous")(),await this._waitForLinkComplete(),r.log.info(2,`RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();const t=this._getLinkStatus();this._reportLinkStatus(t)}async _reportLinkStatus(e){if("success"!==e){const t="link-error"===e?"Link error":"Validation error";switch(this.vs.compilationStatus){case"error":throw this.vs.debugShader(),new Error(`${this} ${t} during compilation of ${this.vs}`);case"pending":await this.vs.asyncCompilationStatus,this.vs.debugShader()}switch(this.fs?.compilationStatus){case"error":throw this.fs.debugShader(),new Error(`${this} ${t} during compilation of ${this.fs}`);case"pending":await this.fs.asyncCompilationStatus,this.fs.debugShader()}const r=this.device.gl.getProgramInfoLog(this.handle);this.device.reportError(new Error(`${t} during ${e}: ${r}`),this)(),this.device.debug()}}_getLinkStatus(){const{gl:e}=this.device;return e.getProgramParameter(this.handle,35714)?(this._initializeSamplerUniforms(),e.validateProgram(this.handle),e.getProgramParameter(this.handle,35715)?(this.linkStatus="success","success"):(this.linkStatus="error","validation-error")):(this.linkStatus="error","link-error")}_initializeSamplerUniforms(){const{gl:e}=this.device;e.useProgram(this.handle);let t=0;const r=e.getProgramParameter(this.handle,35718);for(let i=0;i<r;i++){const r=e.getActiveUniform(this.handle,i);if(r&&ft(r.type)){const i=r.name.endsWith("[0]"),n=i?r.name.slice(0,-3):r.name,s=e.getUniformLocation(this.handle,n);null!==s&&(t=this._assignSamplerUniform(s,r,i,t))}}}_assignSamplerUniform(e,t,r,i){const{gl:n}=this.device;if(r&&t.size>1){const r=Int32Array.from({length:t.size},(e,t)=>i+t);return n.uniform1iv(e,r),i+t.size}return n.uniform1i(e,i),i+1}async _waitForLinkComplete(){const e=async e=>await new Promise(t=>setTimeout(t,e));if(!this.device.features.has("compilation-status-async-webgl"))return void(await e(10));const{gl:t}=this.device;for(;;){if(t.getProgramParameter(this.handle,37297))return;await e(10)}}},Dt=class extends B{device;handle=null;commands=[];constructor(e,t={}){super(e,t),this.device=e}_executeCommands(e=this.commands){for(const t of e)switch(t.name){case"copy-buffer-to-buffer":Rt(this.device,t.options);break;case"copy-buffer-to-texture":It(this.device,t.options);break;case"copy-texture-to-buffer":kt(this.device,t.options);break;case"copy-texture-to-texture":Ot(this.device,t.options);break;default:throw new Error(t.name)}}};function Rt(e,t){const r=t.sourceBuffer,i=t.destinationBuffer;e.gl.bindBuffer(36662,r.handle),e.gl.bindBuffer(36663,i.handle),e.gl.copyBufferSubData(36662,36663,t.sourceOffset??0,t.destinationOffset??0,t.size),e.gl.bindBuffer(36662,null),e.gl.bindBuffer(36663,null)}function It(e,t){const{sourceBuffer:r,byteOffset:i=0,destinationTexture:n,mipLevel:s=0,origin:o=[0,0,0],aspect:a="all",bytesPerRow:l,rowsPerImage:c,size:u}=t;if("all"!==a)throw new Error("copyBufferToTexture aspect is not supported in WebGL");n.writeBuffer(r,{byteOffset:i,bytesPerRow:l,rowsPerImage:c,mipLevel:s,x:o[0]??0,y:o[1]??0,z:o[2]??0,width:u[0],height:u[1],depthOrArrayLayers:u[2]})}function kt(e,r){const{sourceTexture:i,mipLevel:n=0,aspect:o="all",width:a=r.sourceTexture.width,height:l=r.sourceTexture.height,depthOrArrayLayers:c,origin:u=[0,0,0],destinationBuffer:h,byteOffset:d=0,bytesPerRow:f,rowsPerImage:g}=r;if(i instanceof t.Texture)return void i.readBuffer({x:u[0]??0,y:u[1]??0,z:u[2]??0,width:a,height:l,depthOrArrayLayers:c,mipLevel:n,aspect:o,byteOffset:d},h);if("all"!==o)throw new Error("aspect not supported in WebGL");if(0!==n||void 0!==c||f||g)throw new Error("not implemented");const{framebuffer:m,destroyFramebuffer:p}=$t(i);let b;try{const t=h,r=a||m.width,i=l||m.height,n=Oe(s(m.colorAttachments[0]).texture.props.format),o=n.format,c=n.type;e.gl.bindBuffer(35051,t.handle),b=e.gl.bindFramebuffer(36160,m.handle),e.gl.readPixels(u[0],u[1],r,i,o,c,d)}finally{e.gl.bindBuffer(35051,null),void 0!==b&&e.gl.bindFramebuffer(36160,b),p&&m.destroy()}}function Ot(e,t){const{sourceTexture:r,destinationMipLevel:i=0,origin:n=[0,0],destinationOrigin:s=[0,0,0],destinationTexture:o}=t;let{width:a=t.destinationTexture.width,height:l=t.destinationTexture.height}=t;const{framebuffer:c,destroyFramebuffer:u}=$t(r),[h=0,d=0]=n,[f,g,m]=s,p=e.gl.bindFramebuffer(36160,c.handle);let b,y;if(!(o instanceof ct))throw new Error("invalid destination");switch(b=o,a=Number.isFinite(a)?a:b.width,l=Number.isFinite(l)?l:b.height,b._bind(0),y=b.glTarget,y){case 3553:case 34067:e.gl.copyTexSubImage2D(y,i,f,g,h,d,a,l);break;case 35866:case 32879:e.gl.copyTexSubImage3D(y,i,f,g,m,h,d,a,l)}b&&b._unbind(),e.gl.bindFramebuffer(36160,p),u&&c.destroy()}function $t(e){if(e instanceof t.Texture){const{width:t,height:r,id:i}=e;return{framebuffer:e.device.createFramebuffer({id:`framebuffer-for-${i}`,width:t,height:r,colorAttachments:[e]}),destroyFramebuffer:!0}}return{framebuffer:e,destroyFramebuffer:!1}}var Mt=[1,2,4,8],Wt=class extends P{device;handle=null;glParameters={};pipeline=null;bindings={};bindingsPipeline=null;vertexArray=null;constructor(e,t){super(e,t),this.device=e;const r=this.props.framebuffer,i=!r||null===r.handle;let n;if(i&&e.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded(),!t?.parameters?.viewport)if(!i&&r){const{width:e,height:t}=r;n=[0,0,e,t]}else{const[t,r]=e.getDefaultCanvasContext().getDrawingBufferSize();n=[0,0,t,r]}if(this.device.pushState(),this.setParameters({viewport:n,...this.props.parameters}),!i&&r?.colorAttachments.length){const e=r.colorAttachments.map((e,t)=>36064+t);this.device.gl.drawBuffers(e)}else i&&this.device.gl.drawBuffers([1029]);this.clear(),this.props.timestampQuerySet&&void 0!==this.props.beginTimestampIndex&&this.props.timestampQuerySet.writeTimestamp(this.props.beginTimestampIndex)}end(){this.destroyed||(this.props.timestampQuerySet&&void 0!==this.props.endTimestampIndex&&this.props.timestampQuerySet.writeTimestamp(this.props.endTimestampIndex),this.device.popState(),this.destroy())}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}executeBundles(e){throw new Error("Render bundles are only supported in WebGPU")}setParameters(e={}){const t={...this.glParameters};t.framebuffer=this.props.framebuffer||null,this.props.depthReadOnly&&(t.depthMask=!this.props.depthReadOnly),t.stencilMask=this.props.stencilReadOnly?0:1,t[35977]=this.props.discard,e.viewport&&(e.viewport.length>=6?(t.viewport=e.viewport.slice(0,4),t.depthRange=[e.viewport[4],e.viewport[5]]):t.viewport=e.viewport),e.scissorRect&&(t.scissorTest=!0,t.scissor=e.scissorRect),e.blendConstant&&(t.blendColor=e.blendConstant),void 0!==e.stencilReference&&(t[2967]=e.stencilReference,t[36003]=e.stencilReference),"colorMask"in e&&(t.colorMask=Mt.map(t=>Boolean(t&e.colorMask))),this.glParameters=t,le(this.device.gl,t)}setPipeline(e){this.pipeline=e}setBindings(e,t){if(!this.pipeline)throw new Error("RenderPass.setPipeline() must be called before setBindings()");this.bindings=_(x(this.pipeline.shaderLayout,e)),this.bindingsPipeline=this.pipeline}setVertexArray(e){this.vertexArray=e}draw(e){const t=this.pipeline,i=this.vertexArray;if(!t)throw new Error("RenderPass.setPipeline() must be called before draw()");if(!i)throw new Error("RenderPass.setVertexArray() must be called before draw()");if(t.shaderLayout.bindings.length>0&&this.bindingsPipeline!==t)throw new Error("RenderPass.setBindings() must be called after setPipeline() before draw()");t._syncLinkStatus();const{parameters:n=t.props.parameters,topology:s=t.props.topology,vertexCount:o,indexCount:a,instanceCount:l,isInstanced:c=!1,firstVertex:u=0,transformFeedback:h,uniforms:d=t.uniforms}=e,f=function(e){switch(e){case"point-list":return 0;case"line-list":return 1;case"line-strip":return 3;case"triangle-list":return 4;case"triangle-strip":return 5;default:throw new Error(e)}}(s),g=Boolean(i.indexBuffer),m=i.indexBuffer?.glIndexType,p=a??o??0;if("success"!==t.linkStatus)return r.log.info(2,`RenderPipeline:${t.id}.draw() aborted - waiting for shader linking`)(),!1;if(!t._areTexturesRenderable(this.bindings))return r.log.info(2,`RenderPipeline:${t.id}.draw() aborted - textures not yet loaded`)(),!1;this.device.gl.useProgram(t.handle),i.bindBeforeRender(this);const b=h;return b&&b.begin(t.props.topology),t._applyBindings(this.bindings,{disableWarnings:t.props.disableWarnings}),t._applyUniforms(d),Ke(this.device,n,this.glParameters,()=>{g&&c?this.device.gl.drawElementsInstanced(f,p,m,u,l||0):g?this.device.gl.drawElements(f,p,m,u):c?this.device.gl.drawArraysInstanced(f,u,o||0,l||0):this.device.gl.drawArrays(f,u,o||0),b&&b.end()}),i.unbindAfterRender(this),!0}drawIndirect(e,t=0){throw new Error("Indirect drawing is only supported in WebGPU")}drawIndexedIndirect(e,t=0){throw new Error("Indirect drawing is only supported in WebGPU")}beginOcclusionQuery(e){this.props.occlusionQuerySet?.beginOcclusionQuery()}endOcclusionQuery(){this.props.occlusionQuerySet?.endOcclusionQuery()}clear(){const e={...this.glParameters};let t=0;this.props.clearColors&&this.props.clearColors.forEach((e,t)=>{e&&this.clearColorBuffer(t,e)}),!1!==this.props.clearColor&&void 0===this.props.clearColors&&(t|=16384,e.clearColor=this.props.clearColor),!1!==this.props.clearDepth&&(t|=256,e.clearDepth=this.props.clearDepth),!1!==this.props.clearStencil&&(t|=1024,e.clearStencil=this.props.clearStencil),0!==t&&st(this.device.gl,e,()=>{this.device.gl.clear(t)})}clearColorBuffer(e=0,t=[0,0,0,0]){st(this.device.gl,{framebuffer:this.props.framebuffer},()=>{switch(t.constructor){case Int8Array:case Int16Array:case Int32Array:this.device.gl.clearBufferiv(6144,e,t);break;case Uint8Array:case Uint8ClampedArray:case Uint16Array:case Uint32Array:this.device.gl.clearBufferuiv(6144,e,t);break;case Float32Array:this.device.gl.clearBufferfv(6144,e,t);break;default:throw new Error("clearColorBuffer: color must be typed array")}})}},zt=class extends T{device;handle=null;commandBuffer;constructor(e,t){super(e,t),this.device=e,this.commandBuffer=new Dt(e,{id:this.id,userData:this.userData})}destroy(){this.destroyResource()}finish(){return this.destroy(),this.commandBuffer}beginRenderPass(e={}){return new Wt(this.device,this._applyTimeProfilingToPassProps(e))}beginComputePass(e={}){throw new Error("ComputePass not supported in WebGL")}copyBufferToBuffer(e){this.commandBuffer.commands.push({name:"copy-buffer-to-buffer",options:e})}copyBufferToTexture(e){this.commandBuffer.commands.push({name:"copy-buffer-to-texture",options:e})}copyTextureToBuffer(e){this.commandBuffer.commands.push({name:"copy-texture-to-buffer",options:e})}copyTextureToTexture(e){this.commandBuffer.commands.push({name:"copy-texture-to-texture",options:e})}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}resolveQuerySet(e,t,r){throw new Error("resolveQuerySet is not supported in WebGL")}writeTimestamp(e,t){e.writeTimestamp(t)}};var Gt=class e extends E{get[Symbol.toStringTag](){return"VertexArray"}device;handle;attributeInfosByLocation;buffer=null;bufferValue=null;static isConstantAttributeZeroSupported(e){return"Chrome"==(t||r.isBrowser()?r.isElectron(t)?"Electron":(t||r.navigator_.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown":"Node");var t}constructor(e,t){super(e,t),this.device=e,this.handle=this.device.gl.createVertexArray(),this.attributeInfosByLocation=new Array(this.maxVertexAttributes).fill(null);for(const r of Object.values(j(t.shaderLayout,t.bufferLayout)))this.attributeInfosByLocation[r.location]=r}destroy(){super.destroy(),this.buffer&&this.buffer?.destroy(),this.handle&&(this.device.gl.deleteVertexArray(this.handle),this.handle=void 0)}setIndexBuffer(e){const t=e;if(t&&34963!==t.glTarget)throw new Error("Use .setBuffer()");this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34963,t?t.handle:null),this.indexBuffer=t,this.device.gl.bindVertexArray(null)}setBuffer(e,t){const r=t;if(34963===r.glTarget)throw new Error("Use .setIndexBuffer()");const{size:i,type:n,stride:s,offset:o,normalized:a,integer:l,divisor:c}=this._getAccessor(e);this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34962,r.handle),l?this.device.gl.vertexAttribIPointer(e,i,n,s,o):this.device.gl.vertexAttribPointer(e,i,n,a,s,o),this.device.gl.bindBuffer(34962,null),this.device.gl.enableVertexAttribArray(e),this.device.gl.vertexAttribDivisor(e,c||0),this.attributes[e]=r,this.device.gl.bindVertexArray(null)}setConstantWebGL(e,t){this._enable(e,!1),this.attributes[e]=t}bindBeforeRender(){this.device.gl.bindVertexArray(this.handle),this._applyConstantAttributes()}unbindAfterRender(){this.device.gl.bindVertexArray(null)}_applyConstantAttributes(){for(let e=0;e<this.maxVertexAttributes;++e){const t=this.attributes[e];ArrayBuffer.isView(t)&&this.device.setConstantAttributeWebGL(e,t)}}_getAccessor(e){const t=this.attributeInfosByLocation[e];if(!t)throw new Error(`Unknown attribute location ${e}`);const r=ve(t.bufferDataType);return{size:t.bufferComponents,type:r,stride:t.byteStride,offset:t.byteOffset,normalized:t.normalized,integer:t.integer,divisor:"instance"===t.stepMode?1:0}}_enable(t,r=!0){const i=e.isConstantAttributeZeroSupported(this.device)||0!==t;(r||i)&&(t=Number(t),this.device.gl.bindVertexArray(this.handle),r?this.device.gl.enableVertexAttribArray(t):this.device.gl.disableVertexAttribArray(t),this.device.gl.bindVertexArray(null))}getConstantBuffer(e,t){const r=(i=t,Array.isArray(i)?new Float32Array(i):i);var i;const n=r.byteLength*e,s=r.length*e;if(this.buffer&&n!==this.buffer.byteLength)throw new Error(`Buffer size is immutable, byte length ${n} !== ${this.buffer.byteLength}.`);let o=!this.buffer;if(this.buffer=this.buffer||this.device.createBuffer({byteLength:n}),o||=!function(e,t){if(!e||!t||e.length!==t.length||e.constructor!==t.constructor)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}(r,this.bufferValue),o){const e=function(e,t){return new e(z(e.BYTES_PER_ELEMENT*t),0,t)}(t.constructor,s);!function(e){const{target:t,source:r,start:i=0,count:n=1}=e,s=r.length,o=n*s;let a=0;for(let l=i;a<s;a++)t[l++]=r[a]??0;for(;a<o;)a<o-a?(t.copyWithin(i+a,i,i+a),a*=2):(t.copyWithin(i+a,i,i+o-a),a=o);e.target}({target:e,source:r,start:0,count:s}),this.buffer.write(e),this.bufferValue=t}return this.buffer}};var Nt=class extends L{device;gl;handle;layout;buffers={};unusedBuffers={};bindOnUse=!0;_bound=!1;constructor(e,t){super(e,t),this.device=e,this.gl=e.gl,this.handle=this.props.handle||this.gl.createTransformFeedback(),this.layout=this.props.layout,t.buffers&&this.setBuffers(t.buffers),Object.seal(this)}destroy(){this.gl.deleteTransformFeedback(this.handle),super.destroy()}begin(e="point-list"){this.gl.bindTransformFeedback(36386,this.handle),this.bindOnUse&&this._bindBuffers(),this.gl.beginTransformFeedback(function(e){switch(e){case"point-list":return 0;case"line-list":case"line-strip":return 1;case"triangle-list":case"triangle-strip":return 4;default:throw new Error(e)}}(e))}end(){this.gl.endTransformFeedback(),this.bindOnUse&&this._unbindBuffers(),this.gl.bindTransformFeedback(36386,null)}setBuffers(e){this.buffers={},this.unusedBuffers={},this.bind(()=>{for(const[t,r]of Object.entries(e))this.setBuffer(t,r)})}setBuffer(e,t){const i=this._getVaryingIndex(e),{buffer:n,byteLength:s,byteOffset:o}=this._getBufferRange(t);if(i<0)return this.unusedBuffers[e]=n,void r.log.warn(`${this.id} unusedBuffers varying buffer ${e}`)();this.buffers[i]={buffer:n,byteLength:s,byteOffset:o},this.bindOnUse||this._bindBuffer(i,n,o,s)}getBuffer(e){if(Ut(e))return this.buffers[e]||null;const t=this._getVaryingIndex(e);return this.buffers[t]??null}bind(e=this.handle){if("function"!=typeof e)return this.gl.bindTransformFeedback(36386,e),this;let t;return this._bound?t=e():(this.gl.bindTransformFeedback(36386,this.handle),this._bound=!0,t=e(),this._bound=!1,this.gl.bindTransformFeedback(36386,null)),t}unbind(){this.bind(null)}_getBufferRange(e){if(e instanceof je)return{buffer:e,byteOffset:0,byteLength:e.byteLength};const{buffer:t,byteOffset:r=0,byteLength:i=e.buffer.byteLength}=e;return{buffer:t,byteOffset:r,byteLength:i}}_getVaryingIndex(e){if(Ut(e))return Number(e);for(const t of this.layout.varyings||[])if(e===t.name)return t.location;return-1}_bindBuffers(){for(const[e,t]of Object.entries(this.buffers)){const{buffer:r,byteLength:i,byteOffset:n}=this._getBufferRange(t);this._bindBuffer(Number(e),r,n,i)}}_unbindBuffers(){for(const e in this.buffers)this.gl.bindBufferBase(35982,Number(e),null)}_bindBuffer(e,t,r=0,i){const n=t&&t.handle;n&&void 0!==i?this.gl.bindBufferRange(35982,e,n,r,i):this.gl.bindBufferBase(35982,e,n)}};function Ut(e){return"number"==typeof e?Number.isInteger(e):/^\d+$/.test(e)}var Qt=class extends A{device;handle;_timestampPairs=[];_pendingReads=new Set;_occlusionQuery=null;_occlusionActive=!1;get[Symbol.toStringTag](){return"QuerySet"}constructor(e,t){if(super(e,t),this.device=e,"timestamp"===t.type){if(t.count<2)throw new Error("Timestamp QuerySet requires at least two query slots");this._timestampPairs=new Array(Math.ceil(t.count/2)).fill(null).map(()=>({activeQuery:null,completedQueries:[]})),this.handle=null}else{if(t.count>1)throw new Error("WebGL occlusion QuerySet can only have one value");const e=this.device.gl.createQuery();if(!e)throw new Error("WebGL query not supported");this.handle=e}Object.seal(this)}destroy(){if(!this.destroyed){this.handle&&this.device.gl.deleteQuery(this.handle);for(const e of this._timestampPairs){e.activeQuery&&(this._cancelPendingQuery(e.activeQuery),this.device.gl.deleteQuery(e.activeQuery.handle));for(const t of e.completedQueries)this._cancelPendingQuery(t),this.device.gl.deleteQuery(t.handle)}this._occlusionQuery&&(this._cancelPendingQuery(this._occlusionQuery),this.device.gl.deleteQuery(this._occlusionQuery.handle));for(const e of Array.from(this._pendingReads))this._cancelPendingQuery(e);this.destroyResource()}}isResultAvailable(e){return"timestamp"===this.props.type?void 0===e?this._timestampPairs.some((e,t)=>this._isTimestampPairAvailable(t)):this._isTimestampPairAvailable(this._getTimestampPairIndex(e)):!!this._occlusionQuery&&this._pollQueryAvailability(this._occlusionQuery)}async readResults(e){const t=e?.firstQuery||0,r=e?.queryCount||this.props.count-t;if(this._validateRange(t,r),"timestamp"===this.props.type){const e=new Array(r).fill(0n),i=Math.floor(t/2),n=Math.floor((t+r-1)/2);for(let s=i;s<=n;s++){const i=await this._consumeTimestampPairResult(s),n=2*s,o=n+1;n>=t&&n<t+r&&(e[n-t]=0n),o>=t&&o<t+r&&(e[o-t]=i)}return e}if(!this._occlusionQuery)throw new Error("Occlusion query has not been started");return[await this._consumeQueryResult(this._occlusionQuery)]}async readTimestampDuration(e,t){if("timestamp"!==this.props.type)throw new Error("Timestamp durations require a timestamp QuerySet");if(e<0||t>=this.props.count||t<=e)throw new Error("Timestamp duration range is out of bounds");if(e%2!=0||t!==e+1)throw new Error("WebGL timestamp durations require adjacent even/odd query indices");const r=await this._consumeTimestampPairResult(this._getTimestampPairIndex(e));return Number(r)/1e6}beginOcclusionQuery(){if("occlusion"!==this.props.type)throw new Error("Occlusion queries require an occlusion QuerySet");if(!this.handle)throw new Error("WebGL occlusion query is not available");if(this._occlusionActive)throw new Error("Occlusion query is already active");this.device.gl.beginQuery(35887,this.handle),this._occlusionQuery={handle:this.handle,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null},this._occlusionActive=!0}endOcclusionQuery(){if(!this._occlusionActive)throw new Error("Occlusion query is not active");this.device.gl.endQuery(35887),this._occlusionActive=!1}writeTimestamp(e){if("timestamp"!==this.props.type)throw new Error("Timestamp writes require a timestamp QuerySet");const t=this._getTimestampPairIndex(e),r=this._timestampPairs[t];if(e%2==0){if(r.activeQuery)throw new Error("Timestamp query pair is already active");const e=this.device.gl.createQuery();if(!e)throw new Error("WebGL query not supported");const t={handle:e,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null};return this.device.gl.beginQuery(35007,e),void(r.activeQuery=t)}if(!r.activeQuery)throw new Error("Timestamp query pair was ended before it was started");this.device.gl.endQuery(35007),r.completedQueries.push(r.activeQuery),r.activeQuery=null}_validateRange(e,t){if(e<0||t<0||e+t>this.props.count)throw new Error("Query read range is out of bounds")}_getTimestampPairIndex(e){if(e<0||e>=this.props.count)throw new Error("Query index is out of bounds");return Math.floor(e/2)}_isTimestampPairAvailable(e){const t=this._timestampPairs[e];return!(!t||0===t.completedQueries.length)&&this._pollQueryAvailability(t.completedQueries[0])}_pollQueryAvailability(e){if(e.cancelled||this.destroyed)return e.result=0n,!0;if(null!==e.result||e.disjoint)return!0;if(!this.device.gl.getQueryParameter(e.handle,34919))return!1;const t=Boolean(this.device.gl.getParameter(36795));return e.disjoint=t,e.result=t?0n:BigInt(this.device.gl.getQueryParameter(e.handle,34918)),!0}async _consumeTimestampPairResult(e){const t=this._timestampPairs[e];if(!t||0===t.completedQueries.length)throw new Error("Timestamp query pair has no completed result");const r=t.completedQueries.shift();try{return await this._consumeQueryResult(r)}finally{this.device.gl.deleteQuery(r.handle)}}_consumeQueryResult(e){return e.promise||(this._pendingReads.add(e),e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r;const i=()=>{if(e.pollRequestId=null,e.cancelled||this.destroyed)return this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,void t(0n);this._pollQueryAvailability(e)?(this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,e.disjoint?r(new Error("GPU timestamp query was invalidated by a disjoint event")):t(e.result||0n)):e.pollRequestId=this._requestAnimationFrame(i)};i()})),e.promise}_cancelPendingQuery(e){if(this._pendingReads.delete(e),e.cancelled=!0,null!==e.pollRequestId&&(this._cancelAnimationFrame(e.pollRequestId),e.pollRequestId=null),e.resolve){const t=e.resolve;e.promise=null,e.resolve=null,e.reject=null,t(0n)}}_requestAnimationFrame(e){return requestAnimationFrame(e)}_cancelAnimationFrame(e){cancelAnimationFrame(e)}},Vt=class extends C{device;gl;handle;signaled;_signaled=!1;constructor(e,t={}){super(e,{}),this.device=e,this.gl=e.gl;const r=this.props.handle||this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE,0);if(!r)throw new Error("Failed to create WebGL fence");this.handle=r,this.signaled=new Promise(e=>{const t=()=>{const r=this.gl.clientWaitSync(this.handle,0,0);r===this.gl.ALREADY_SIGNALED||r===this.gl.CONDITION_SATISFIED?(this._signaled=!0,e()):setTimeout(t,1)};t()})}isSignaled(){if(this._signaled)return!0;const e=this.gl.getSyncParameter(this.handle,this.gl.SYNC_STATUS);return this._signaled=e===this.gl.SIGNALED,this._signaled}destroy(){this.destroyed||this.gl.deleteSync(this.handle)}};function jt(e){switch(e){case 6406:case 33326:case 6403:case 36244:return 1;case 33339:case 33340:case 33328:case 33320:case 33319:return 2;case 6407:case 36248:case 34837:return 3;case 6408:case 36249:case 34836:return 4;default:return 0}}function Ht(e,t){const{sourceX:i=0,sourceY:n=0,sourceAttachment:s=0}=t||{};let{target:o=null,sourceWidth:a,sourceHeight:l,sourceDepth:c,sourceFormat:u,sourceType:h}=t||{};const{framebuffer:d,deleteFramebuffer:f}=qt(e),{gl:g,handle:m}=d;a||=d.width,l||=d.height;const p=d.colorAttachments[s]?.texture;if(!p)throw new Error(`Invalid framebuffer attachment ${s}`);c=p?.depth||1,u||=p?.glFormat||6408,h||=p?.glType||5121,o=function(e,t,i,n,s){if(e)return e;t||=5121;const o=at(t),a=r.dataTypeDecoder.getTypedArrayConstructor(o),l=jt(i);return new a(n*s*l)}(o,h,u,a,l);const b=r.dataTypeDecoder.getDataType(o);h=h||bt[b];const y=g.bindFramebuffer(36160,m);return g.readBuffer(36064+s),g.readPixels(i,n,a,l,u,h,o),g.readBuffer(36064),g.bindFramebuffer(36160,y||null),f&&d.destroy(),o}function qt(e){return e instanceof b?{framebuffer:e,deleteFramebuffer:!1}:{framebuffer:Kt(e),deleteFramebuffer:!0}}function Kt(e,t){const{device:r,width:i,height:n,id:s}=e;return r.createFramebuffer({...t,id:`framebuffer-for-${s}`,width:i,height:n,colorAttachments:[e]})}var Yt=e.__exportAll({WebGLDevice:()=>Xt}),Xt=class e extends t.Device{static getDeviceFromContext(e){return e?e.luma?.device??null:null}type="webgl";handle;features;limits;info;canvasContext;preferredColorFormat="rgba8unorm";preferredDepthFormat="depth24plus";commandEncoder;lost;_resolveContextLost;_isLost=!1;gl;_glKeyByValue=null;_constants;extensions;_polyfilled=!1;spectorJS;get[Symbol.toStringTag](){return"WebGLDevice"}toString(){return`${this[Symbol.toStringTag]}(${this.id})`}isVertexFormatSupported(e){return"unorm8x4-bgra"!==e}constructor(i){super({...i,id:i.id||Ve("webgl-device")});const n=t.Device._getCanvasContextProps(i);if(!n)throw new Error("WebGLDevice requires props.createCanvasContext to be set");const s=n.canvas?.gl??null;let o=e.getDeviceFromContext(s);if(o)throw new Error(`WebGL context already attached to device ${o.id}`);this.canvasContext=new Ne(this,n),this.lost=new Promise(e=>{this._resolveContextLost=e});const a={...i.webgl};"premultiplied"===n.alphaMode&&(a.premultipliedAlpha=!0),void 0!==i.powerPreference&&(a.powerPreference=i.powerPreference),void 0!==i.failIfMajorPerformanceCaveat&&(a.failIfMajorPerformanceCaveat=i.failIfMajorPerformanceCaveat);const l=this.props._handle||function(e,t,r){let i="";const n=e=>{const t=e.statusMessage;t&&(i||=t)};e.addEventListener("webglcontextcreationerror",n,!1);const s=!0!==r.failIfMajorPerformanceCaveat,o={preserveDrawingBuffer:!0,...r,failIfMajorPerformanceCaveat:!0};let a=null;try{a||=e.getContext("webgl2",o),!a&&o.failIfMajorPerformanceCaveat&&(i||="Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.");let r=!1;if(!a&&s&&(o.failIfMajorPerformanceCaveat=!1,a=e.getContext("webgl2",o),r=!0),a||(a=e.getContext("webgl",{}),a&&(a=null,i||="Your browser only supports WebGL1")),!a)throw i||="Your browser does not support WebGL",new Error(`Failed to create WebGL context: ${i}`);me(a).softwareRenderer=r;const{onContextLost:n,onContextRestored:l}=t;return e.addEventListener("webglcontextlost",e=>n(e),!1),e.addEventListener("webglcontextrestored",e=>l(e),!1),a}finally{e.removeEventListener("webglcontextcreationerror",n,!1)}}(this.canvasContext.canvas,{onContextLost:e=>this._resolveContextLost?.({reason:"destroyed",message:"Entered sleep mode, or too many apps or browser tabs are using the GPU."}),onContextRestored:e=>{console.log("WebGL context restored")}},a);if(!l)throw new Error("WebGL context creation failed");if(o=e.getDeviceFromContext(l),o){if(i._reuseDevices)return r.log.log(1,`Not creating a new Device, instead returning a reference to Device ${o.id} already attached to WebGL context`,o)(),this.canvasContext.destroy(),o._reused=!0,o;throw new Error(`WebGL context already attached to device ${o.id}`)}this.handle=l,this.gl=l,this.spectorJS=t.initializeRegisteredSpectorJS({...this.props,gl:this.handle});const c=me(this.handle);c.device=this,c.extensions||(c.extensions={}),this.extensions=c.extensions,this.info=function(e,t){const r=e.getParameter(7936),i=e.getParameter(7937);pe(e,"WEBGL_debug_renderer_info",t);const n=t.WEBGL_debug_renderer_info,s=e.getParameter(n?n.UNMASKED_VENDOR_WEBGL:7936)||r,o=e.getParameter(n?n.UNMASKED_RENDERER_WEBGL:7937)||i,a=e.getParameter(7938),l=be(s,o),c=function(e,t){return/Metal/i.exec(e)||/Metal/i.exec(t)?"metal":/ANGLE/i.exec(e)||/ANGLE/i.exec(t)?"opengl":"unknown"}(s,o);return{type:"webgl",gpu:l,gpuType:ye(s,o),gpuBackend:c,vendor:s,renderer:o,version:a,shadingLanguage:"glsl",shadingLanguageVersion:300}}(this.gl,this.extensions),this.limits=new ze(this.gl),this.features=new We(this.gl,this.extensions,this.props._disabledFeatures),this.props._initializeFeatures&&this.features.initializeFeatures(),new de(this.gl,{log:(...e)=>r.log.log(1,...e)()}).trackState(this.gl,{copyState:!1}),(i.debug||i.debugWebGL)&&(this.gl=t.makeRegisteredDebugContext(this.gl,{debugWebGL:!0,traceWebGL:i.debugWebGL}),r.log.warn("WebGL debug mode activated. Performance reduced.")()),i.debugWebGL&&(r.log.level=Math.max(r.log.level,1)),this.commandEncoder=new zt(this,{id:`${this}-command-encoder`}),this.canvasContext._startObservers()}destroy(){if(!this.props._reuseDevices&&!this._reused){this._isLost=!0,this.commandEncoder?.destroy();me(this.handle).device=null}}get isLost(){return this._isLost||this.gl.isContextLost()}createCanvasContext(e){throw new Error("WebGL only supports a single canvas")}createPresentationContext(e){return new Ue(this,e||{})}createBuffer(e){const t=this._normalizeBufferProps(e);return new je(this,t)}createTexture(e){return new ct(this,e)}createExternalTexture(e){throw new Error("ExternalTexture is not available on WebGL")}createSampler(e){return new nt(this,e)}createShader(e){return new qe(this,e)}createFramebuffer(e){return new Ge(this,e)}createVertexArray(e){return new Gt(this,e)}createTransformFeedback(e){return new Nt(this,e)}createQuerySet(e){return new Qt(this,e)}createFence(){return new Vt(this)}createRenderPipeline(e){return new Lt(this,e)}_createSharedRenderPipelineWebGL(e){return new Ft(this,e)}createComputePipeline(e){throw new Error("ComputePipeline not supported in WebGL")}createRenderBundleEncoder(e){throw new Error("Render bundles are only supported in WebGPU")}createCommandEncoder(e={}){return new zt(this,e)}submit(e){let t=null;e||({submittedCommandEncoder:t,commandBuffer:e}=this._finalizeDefaultCommandEncoderForSubmit());try{e._executeCommands(),t&&t.resolveTimeProfilingQuerySet().then(()=>{this.commandEncoder._gpuTimeMs=t._gpuTimeMs}).catch(()=>{})}finally{e.destroy()}}writeBufferViaCommandEncoder(e,t,r,i=0){t.write(r,i)}_finalizeDefaultCommandEncoderForSubmit(){const e=this.commandEncoder,t=e.finish();return this.commandEncoder.destroy(),this.commandEncoder=this.createCommandEncoder({id:e.props.id,timeProfilingQuerySet:e.getTimeProfilingQuerySet()}),{submittedCommandEncoder:e,commandBuffer:t}}readPixelsToArrayWebGL(e,t){return Ht(e,t)}readPixelsToBufferWebGL(e,t){return function(e,t){const{target:r,sourceX:i=0,sourceY:n=0,sourceFormat:s=6408,targetByteOffset:o=0}=t||{};let{sourceWidth:a,sourceHeight:l,sourceType:c}=t||{};const{framebuffer:u,deleteFramebuffer:h}=qt(e);a=a||u.width,l=l||u.height;const d=u;c=c||5121;let f=r;if(!f){const e=o+a*l*jt(s)*function(e){switch(e){case 5121:return 1;case 33635:case 32819:case 32820:return 2;case 5126:return 4;default:return 0}}(c);f=d.device.createBuffer({byteLength:e})}const g=e.device.createCommandEncoder();return g.copyTextureToBuffer({sourceTexture:e,width:a,height:l,origin:[i,n],destinationBuffer:f,byteOffset:o}),g.destroy(),h&&u.destroy(),f}(e,t)}setParametersWebGL(e){le(this.gl,e)}getParametersWebGL(e){return ce(this.gl,e)}withParametersWebGL(e,t){return st(this.gl,e,t)}resetWebGL(){r.log.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(),le(this.gl,q)}_getDeviceSpecificTextureFormatCapabilities(e){return ke(this.gl,e,this.extensions)}loseDevice(){let e=!1;const t=this.getExtension("WEBGL_lose_context").WEBGL_lose_context;return t&&(e=!0,t.loseContext()),this._resolveContextLost?.({reason:"destroyed",message:"Application triggered context loss"}),e}pushState(){de.get(this.gl).push()}popState(){de.get(this.gl).pop()}getGLKey(e,t){const r=this._getGLKeyByValue().get(Number(e));return r||(t?.emptyIfUnknown?"":String(e))}getGLKeys(e){const t={emptyIfUnknown:!0};return Object.entries(e).reduce((e,[r,i])=>(e[`${r}:${this.getGLKey(r,t)}`]=`${i}:${this.getGLKey(i,t)}`,e),{})}_getGLKeyByValue(){return this._glKeyByValue??=function(e){const t=new Map;for(const r in e){const i=e[r];if(r<"a"){const e=t.get(i);t.set(i,e?`${e}, GL.${r}`:`GL.${r}`)}}return t}(this.gl),this._glKeyByValue}setConstantAttributeWebGL(e,t){const i=this.limits.maxVertexAttributes;this._constants=this._constants||new Array(i).fill(null);const n=this._constants[e];switch(n&&function(e,t){if(!e||!t||e.length!==t.length||e.constructor!==t.constructor)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}(n,t)&&r.log.info(1,`setConstantAttributeWebGL(${e}) could have been skipped, value unchanged`)(),this._constants[e]=t,t.constructor){case Float32Array:!function(e,t,r){switch(r.length){case 1:e.gl.vertexAttrib1fv(t,r);break;case 2:e.gl.vertexAttrib2fv(t,r);break;case 3:e.gl.vertexAttrib3fv(t,r);break;case 4:e.gl.vertexAttrib4fv(t,r)}}(this,e,t);break;case Int32Array:!function(e,t,r){e.gl.vertexAttribI4iv(t,r)}(this,e,t);break;case Uint32Array:!function(e,t,r){e.gl.vertexAttribI4uiv(t,r)}(this,e,t);break;default:throw new Error("constant")}}getExtension(e){return pe(this.gl,e,this.extensions),this.extensions}_setWebGLDebugMetadata(e,t,r){e.luma=t,e.__SPECTOR_Metadata={props:r.spector,id:r.spector.id}}};Object.defineProperty(exports,"RenderPipeline",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"Shader",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"TextureView",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"WebGLDevice",{enumerable:!0,get:function(){return Xt}}),Object.defineProperty(exports,"assert",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"getAttributeInfosFromLayouts",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"getBufferLayoutAttributeNames",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"getLeafLayoutInfo",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"getMinimumAttributeLocation",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"getScratchArrayBuffer",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"getShaderAttributeLocationMap",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"getShaderLayoutBinding",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"isCompositeShaderTypeStruct",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"makeShaderBlockLayout",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"normalizeBindingsByGroup",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"webgl_device_exports",{enumerable:!0,get:function(){return Yt}});
|