typegpu 0.4.4 → 0.4.6

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/index.js CHANGED
@@ -1,19 +1,21 @@
1
- import{A as we,Ca as dr,Ea as Pe,Fa as _e,a as N,b as Be,c as B,k as Zt,l as er,m as tr,n as de,o as rr,p as me,pa as D,q as nr,qa as O,r as j,s as z,sa as x,t as rt,u as _,v as L,w as d,y as nt,z as M,za as lr}from"./chunk-ZJMGYM7L.js";import{A as ur,B as pr,a as v,b as R,c as u,d as ce,e as le,f as Ze,g as et,h as tt,i as ee,j as xe,k as Xt,l as te,m as G,n as K,o as ar,p as be,q as he,r as at,s as or,t as ot,u as it,v as F,w as ir,x as C,y as V,z as sr}from"./chunk-ZHXAQ2YE.js";function q(e){return(e==null?void 0:e.resourceType)==="slot"}function J(e){return(e==null?void 0:e.resourceType)==="derived"}function Se(e){return(e==null?void 0:e["~providing"])!==void 0}function re(e){return(e==null?void 0:e.resourceType)==="accessor"}var A=Symbol("Unknown data type");function st(e){return typeof(e==null?void 0:e["~resolve"])=="function"}function ne(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||st(e)||N(e)||q(e)||J(e)||Se(e)}function mr(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function Le(e){return(e==null?void 0:e.resourceType)==="buffer-usage"}var k={get(e,t){if(t in e)return Reflect.get(e,t);if(t!=="~providing")return new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>{var r;return`.value(...).${String(t)}:${(r=e.label)!=null?r:"<unnamed>"}`}},k)}};function Fe(e){let t=e;for(;q(t)||J(t)||re(t)||Le(t);)t=t.value;return t}function gr(e,t){return new ut(e,t)}var ut=class{constructor(t,r){this.dataType=t;this._value=r;u(this,"_label")}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label),n=t.resolveValue(this._value,this.dataType);return t.addDeclaration(`const ${r} = ${n};`),r}toString(){var t;return`const:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){return G()?new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},k):this._value}};function $(e){return!!e&&(typeof e=="object"||typeof e=="function")&&"$name"in e}function ae(e,t){for(let[r,n]of Object.entries(t))e[r]=n,$(n)&&(!("label"in n)||n.label===void 0)&&n.$name(r)}function fr(e,t,r){let n=[...e.matchAll(new RegExp(":\\s*(?<arg>.*?)\\s*[,)]","g"))].map(a=>a?a[1]:void 0);r(Object.fromEntries(t.flatMap((a,o)=>{let i=n?n[o]:void 0;return B(a)&&i!==void 0?[[i,a]]:[]})))}function ge(e,t,r){var o;let n=e.match(new RegExp("->(?<output>.*?){","s")),a=n?(o=n[1])==null?void 0:o.trim():void 0;B(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function pn(e){return new RegExp(`(?<![\\w_.])${e.replaceAll(".","\\.")}(?![\\w_])`,"g")}function oe(e,t,r){return Object.entries(t).reduce((n,[a,o])=>{var i;return ne(o)||de(o)?n.replaceAll(pn(a),e.resolve(o)):o!==null&&typeof o=="object"?((i=[...r.matchAll(new RegExp(`${a.replaceAll(".","\\.")}\\.(?<prop>.*?)(?![\\w_])`,"g"))].map(l=>l[1]))!=null?i:[]).reduce((l,s)=>s&&s in o?oe(e,{[`${a}.${s}`]:o[s]},l):l,n):n},r)}function Tr(e){return new pt(e)}var pt=class{constructor(t){this.declaration=t;u(this,"externalsToApply",[])}$uses(t){return this.externalsToApply.push(t),this}"~resolve"(t){let r={};for(let a of this.externalsToApply)ae(r,a);let n=oe(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var yr=new WeakMap;function cr(e){return yr.get(e)}function xr(e,t,r){return yr.set(e,{ast:t,externals:r}),e}function H(e,t){let r=[];return typeof t=="string"&&(fr(t,e.argTypes,n=>r.push(n)),ge(t,e.returnType,n=>r.push(n))),{label:void 0,applyExternals(n){r.push(n)},resolve(n,a=""){var p;let o={};for(let l of r)ae(o,l);let i=n.names.makeUnique(this.label);if(typeof t=="string"){let l=oe(n,o,t.trim());n.addDeclaration(`${a}fn ${i}${l}`)}else{let l=cr(t);if(l!=null&&l.externals){let c=Object.fromEntries(Object.entries(l.externals).filter(([T])=>!(T in o)));ae(o,c)}let s=(p=l==null?void 0:l.ast)!=null?p:n.transpileFn(String(t)),m=s.externalNames.filter(c=>!(c in o));if(m.length>0)throw new tt(this.label,m);let g=s.argNames.map((c,T)=>({value:c,dataType:e.argTypes[T]})),{head:f,body:w}=n.fnToWgsl({args:g,returnType:e.returnType,body:s.body,externalMap:o});n.addDeclaration(`${a}fn ${i}${n.resolve(f)}${n.resolve(w)}`)}return i}}}function br(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(Pe(n))return[r,n];let a=j(n);return a!==void 0?(t=a+1,[r,n]):[r,lr(n,{type:"@location",value:t++})]}))}function Ce(e){return z(e)?j(e)!==void 0?e:dr(0,e):nt(br(e))}function fe(e){return nt(br(e))}function hr(e){var t,r,n,a;return{argTypes:[fe((t=e.in)!=null?t:{})],returnType:void 0,workgroupSize:[(r=e.workgroupSize[0])!=null?r:1,(n=e.workgroupSize[1])!=null?n:1,(a=e.workgroupSize[2])!=null?a:1],does(o){return ln(this,e.workgroupSize,o)}}}function ln(e,t,r){let n=H(e,r),a=e.argTypes[0];return{shell:e,get label(){return n.label},$uses(o){return n.applyExternals(o),this},$name(o){return n.label=o,$(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){return n.resolve(o,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){var o;return`computeFn:${(o=this.label)!=null?o:"<unnamed>"}`}}}function wr(e,t){return{argTypes:e,returnType:t,does(r){return mn(this,r)}}}function lt(e){return(e==null?void 0:e.resourceType)==="function"}function dn([e,t]){var r;return`${(r=e.label)!=null?r:"<unnamed>"}=${t}`}function mn(e,t){let r=H(e,t),o=Object.assign((...i)=>{if(G())return new Ve(o,i);if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...i)},{shell:e,resourceType:"function",$uses(i){return r.applyExternals(i),this},$name(i){return r.label=i,this},with(i,p){return Sr(o,[[re(i)?i.slot:i,p]])},"~resolve"(i){return r.resolve(i)}});return Object.defineProperty(o,"label",{get:()=>r.label}),Object.defineProperty(o,"toString",{value:()=>{var i;return`fn:${(i=r.label)!=null?i:"<unnamed>"}`}}),o}function Sr(e,t){let r={resourceType:"function",shell:e.shell,"~providing":{inner:e,pairs:t},$uses(o){return e.$uses(o),this},$name(o){return e.$name(o),this},with(o,i){return Sr(a,[...t,[re(o)?o.slot:o,i]])}},a=Object.assign((...o)=>G()?new Ve(a,o):e(...o),r);return Object.defineProperty(a,"label",{get:()=>e.label}),Object.defineProperty(a,"toString",{value(){var i;return`fn:${(i=e.label)!=null?i:"<unnamed>"}[${t.map(dn).join(", ")}]`}}),a}var Ve=class{constructor(t,r){this._fn=t;this._params=r}get label(){return this._fn.label}"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){var t;return`call:${(t=this.label)!=null?t:"<unnamed>"}`}};function Fr(e){var t;return{argTypes:[fe((t=e.in)!=null?t:{})],targets:e.out,returnType:Ce(e.out),does(r){return gn(this,r)}}}function gn(e,t){let r=H(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&ge(t,n,i=>r.applyExternals(i)),{shell:e,outputType:n,get label(){return r.label},$uses(i){return r.applyExternals(i),this},$name(i){return r.label=i,$(n)&&n.$name(`${i}_Output`),$(a)&&a.$name(`${i}_Input`),this},"~resolve"(i){if(typeof t=="string")return r.resolve(i,"@fragment ");let p=i;if(p.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return p.callStack.push(n),r.resolve(i,"@fragment ")}finally{p.callStack.pop()}},toString(){var i;return`fragmentFn:${(i=this.label)!=null?i:"<unnamed>"}`}}}function Dr(e){var t,r;return{attributes:[(t=e.in)!=null?t:{}],returnType:Ce(e.out),argTypes:[fe((r=e.in)!=null?r:{})],does(n){return fn(this,n)}}}function fn(e,t){let r=H(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&ge(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,inputType:a,get label(){return r.label},$uses(o){return r.applyExternals(o),this},$name(o){return r.label=o,$(n)&&n.$name(`${o}_Output`),$(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){if(typeof t=="string")return r.resolve(o,"@vertex ");let i=o;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(n),r.resolve(o,"@vertex ")}finally{i.callStack.pop()}},toString(){var o;return`vertexFn:${(o=this.label)!=null?o:"<unnamed>"}`}}}var Y=class{constructor(){u(this,"lastUniqueId",0)}makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},Q=class{constructor(){u(this,"_usedNames",new Set)}makeUnique(t){if(t===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=t;for(;this._usedNames.has(n);)r++,n=`${t}_${r}`;return this._usedNames.add(n),n}};function Ur(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}function De(e){return typeof(e==null?void 0:e.format)=="string"}function vr(e,t){var i,p;let r=[];if(z(e)){if(!De(t))throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");return r.push(t._layout),{usedVertexLayouts:r,bufferDefinitions:[{arrayStride:t._layout.stride,stepMode:t._layout.stepMode,attributes:[{format:t.format,offset:t.offset,shaderLocation:(i=j(e))!=null?i:0}]}]}}let n=[],a=new WeakMap,o=0;for(let[l,s]of Object.entries(e)){if(Pe(s))continue;let m=t[l];if(!m)throw new Error(`An attribute by the name of '${l}' was not provided to the shader.`);let g=m._layout,f=a.get(g);f||(r.push(g),f=[],n.push({arrayStride:g.stride,stepMode:g.stepMode,attributes:f}),a.set(g,f)),o=(p=j(s))!=null?p:o,f.push({format:m.format,offset:m.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var Tn=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2f","mat3x3f","mat4x4f"];function yn(e){return Tn.includes(e.type)}function dt(e,[t,r]){return` ${_e(r)}${t}: ${e.resolve(r)},
2
- `}function cn(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
1
+ import{A as st,B as W,C as we,Ga as Tr,Ja as cr,La as Ce,Ma as Ee,a as de,b as Be,c as I,k as ar,l as or,m as ir,n as Pe,o as sr,p as me,q as ur,r as j,ra as v,s as k,sa as O,t as _e,u as it,ua as b,v as Le,w as _,x as L,y as d}from"./chunk-JSF3RDCP.js";import{A as C,B as E,C as mr,D as gr,E as fr,a as U,b as R,c as p,d as ye,e as le,f as rt,g as nt,h as at,i as Z,j as xe,k as ot,l as tr,m as ee,n as rr,o as nr,p as G,q as z,r as pr,s as be,t as he,u as ut,v as lr,w as pt,x as lt,y as D,z as dr}from"./chunk-7S2KQX6O.js";function K(e){return(e==null?void 0:e.resourceType)==="slot"}function q(e){return(e==null?void 0:e.resourceType)==="derived"}function Se(e){return(e==null?void 0:e["~providing"])!==void 0}function te(e){return(e==null?void 0:e.resourceType)==="accessor"}var P={type:"unknown"};function dt(e){return typeof(e==null?void 0:e["~resolve"])=="function"}function re(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||dt(e)||de(e)||K(e)||q(e)||Se(e)}function yr(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function Ve(e){return(e==null?void 0:e.resourceType)==="buffer-usage"}var $={get(e,t){if(t in e)return Reflect.get(e,t);if(t!=="~providing")return new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>{var r;return`.value(...).${String(t)}:${(r=e.label)!=null?r:"<unnamed>"}`}},$)}};function Fe(e){let t=e;for(;K(t)||q(t)||te(t)||Ve(t);)t=t.value;return t}function xr(e,t){return new mt(e,t)}var mt=class{constructor(t,r){this.dataType=t;this._value=r;p(this,"_label")}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label),n=t.resolveValue(this._value,this.dataType);return t.addDeclaration(`const ${r} = ${n};`),r}toString(){var t;return`const:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){return G()?new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},$):this._value}};function M(e){return!!e&&(typeof e=="object"||typeof e=="function")&&"$name"in e}function ne(e,t){for(let[r,n]of Object.entries(t))e[r]=n,M(n)&&(!("label"in n)||n.label===void 0)&&n.$name(r)}function br(e,t,r){let n=[...e.matchAll(new RegExp(":\\s*(?<arg>.*?)\\s*[,)]","g"))].map(a=>a?a[1]:void 0);r(Object.fromEntries(t.flatMap((a,o)=>{let i=n?n[o]:void 0;return I(a)&&i!==void 0?[[i,a]]:[]})))}function ge(e,t,r){var o;let n=e.match(new RegExp("->(?<output>.*?){","s")),a=n?(o=n[1])==null?void 0:o.trim():void 0;I(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function fn(e){return new RegExp(`(?<![\\w_.])${e.replaceAll(".","\\.")}(?![\\w_])`,"g")}function ae(e,t,r){return Object.entries(t).reduce((n,[a,o])=>{var i;return re(o)||Pe(o)?n.replaceAll(fn(a),e.resolve(o)):o!==null&&typeof o=="object"?((i=[...r.matchAll(new RegExp(`${a.replaceAll(".","\\.")}\\.(?<prop>.*?)(?![\\w_])`,"g"))].map(l=>l[1]))!=null?i:[]).reduce((l,s)=>s&&s in o?ae(e,{[`${a}.${s}`]:o[s]},l):l,n):n},r)}function hr(e){return new gt(e)}var gt=class{constructor(t){this.declaration=t;p(this,"externalsToApply",[])}$uses(t){return this.externalsToApply.push(t),this}"~resolve"(t){let r={};for(let a of this.externalsToApply)ne(r,a);let n=ae(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var wr=new WeakMap;function Sr(e){return wr.get(e)}function Fr(e,t,r){return wr.set(e,{ast:t,externals:r}),e}function J(e,t){let r=[];return typeof t=="string"&&(br(t,e.argTypes,n=>r.push(n)),ge(t,e.returnType,n=>r.push(n))),{label:void 0,applyExternals(n){r.push(n)},resolve(n,a=""){var u;let o={};for(let l of r)ne(o,l);let i=n.names.makeUnique(this.label);if(typeof t=="string"){let l=ae(n,o,t.trim());n.addDeclaration(`${a}fn ${i}${l}`)}else{let l=Sr(t);if(l!=null&&l.externals){let y=Object.fromEntries(Object.entries(l.externals).filter(([T])=>!(T in o)));ne(o,y)}let s=(u=l==null?void 0:l.ast)!=null?u:n.transpileFn(String(t)),m=s.externalNames.filter(y=>!(y in o));if(m.length>0)throw new at(this.label,m);let g=s.argNames.map((y,T)=>({value:y,dataType:e.argTypes[T]})),{head:f,body:w}=n.fnToWgsl({args:g,returnType:e.returnType,body:s.body,externalMap:o});n.addDeclaration(`${a}fn ${i}${n.resolve(f)}${n.resolve(w)}`)}return i}}}function Dr(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(Ce(n))return[r,n];let a=j(n);return a!==void 0?(t=a+1,[r,n]):[r,Tr(n,{type:"@location",value:t++})]}))}function Ge(e){return k(e)?j(e)!==void 0?e:cr(0,e):st(Dr(e))}function fe(e){return st(Dr(e))}function Ur(e){var t,r,n,a;return{argTypes:[fe((t=e.in)!=null?t:{})],returnType:void 0,workgroupSize:[(r=e.workgroupSize[0])!=null?r:1,(n=e.workgroupSize[1])!=null?n:1,(a=e.workgroupSize[2])!=null?a:1],does(o){return Tn(this,e.workgroupSize,o)}}}function Tn(e,t,r){let n=J(e,r),a=e.argTypes[0];return{shell:e,get label(){return n.label},$uses(o){return n.applyExternals(o),this},$name(o){return n.label=o,M(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){return n.resolve(o,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){var o;return`computeFn:${(o=this.label)!=null?o:"<unnamed>"}`}}}function vr(e,t){return{argTypes:e,returnType:t,does(r){return yn(this,r)}}}function ft(e){return(e==null?void 0:e.resourceType)==="function"}function cn([e,t]){var r;return`${(r=e.label)!=null?r:"<unnamed>"}=${t}`}function yn(e,t){let r=J(e,t),o=Object.assign((...i)=>{if(G())return new ke(o,i);if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...i)},{shell:e,resourceType:"function",$uses(i){return r.applyExternals(i),this},$name(i){return r.label=i,this},with(i,u){return Ar(o,[[te(i)?i.slot:i,u]])},"~resolve"(i){return r.resolve(i)}});return Object.defineProperty(o,"label",{get:()=>r.label}),Object.defineProperty(o,"toString",{value:()=>{var i;return`fn:${(i=r.label)!=null?i:"<unnamed>"}`}}),o}function Ar(e,t){let r={resourceType:"function",shell:e.shell,"~providing":{inner:e,pairs:t},$uses(o){return e.$uses(o),this},$name(o){return e.$name(o),this},with(o,i){return Ar(a,[...t,[te(o)?o.slot:o,i]])}},a=Object.assign((...o)=>G()?new ke(a,o):e(...o),r);return Object.defineProperty(a,"label",{get:()=>e.label}),Object.defineProperty(a,"toString",{value(){var i;return`fn:${(i=e.label)!=null?i:"<unnamed>"}[${t.map(cn).join(", ")}]`}}),a}var ke=class{constructor(t,r){this._fn=t;this._params=r}get label(){return this._fn.label}"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){var t;return`call:${(t=this.label)!=null?t:"<unnamed>"}`}};function Rr(e){var t;return{argTypes:[fe((t=e.in)!=null?t:{})],targets:e.out,returnType:Ge(e.out),does(r){return xn(this,r)}}}function xn(e,t){let r=J(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&ge(t,n,i=>r.applyExternals(i)),{shell:e,outputType:n,get label(){return r.label},$uses(i){return r.applyExternals(i),this},$name(i){return r.label=i,M(n)&&n.$name(`${i}_Output`),M(a)&&a.$name(`${i}_Input`),this},"~resolve"(i){if(typeof t=="string")return r.resolve(i,"@fragment ");let u=i;if(u.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return u.callStack.push(n),r.resolve(i,"@fragment ")}finally{u.callStack.pop()}},toString(){var i;return`fragmentFn:${(i=this.label)!=null?i:"<unnamed>"}`}}}function Ir(e){var t,r;return{attributes:[(t=e.in)!=null?t:{}],returnType:Ge(e.out),argTypes:[fe((r=e.in)!=null?r:{})],does(n){return bn(this,n)}}}function bn(e,t){let r=J(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&ge(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,inputType:a,get label(){return r.label},$uses(o){return r.applyExternals(o),this},$name(o){return r.label=o,M(n)&&n.$name(`${o}_Output`),M(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){if(typeof t=="string")return r.resolve(o,"@vertex ");let i=o;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(n),r.resolve(o,"@vertex ")}finally{i.callStack.pop()}},toString(){var o;return`vertexFn:${(o=this.label)!=null?o:"<unnamed>"}`}}}var H=class{constructor(){p(this,"lastUniqueId",0)}makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},Y=class{constructor(){p(this,"_usedNames",new Set)}makeUnique(t){if(t===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=t;for(;this._usedNames.has(n);)r++,n=`${t}_${r}`;return this._usedNames.add(n),n}};function Br(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}function De(e){return typeof(e==null?void 0:e.format)=="string"}function Pr(e,t){var i,u;let r=[];if(k(e)){if(!De(t))throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");return r.push(t._layout),{usedVertexLayouts:r,bufferDefinitions:[{arrayStride:t._layout.stride,stepMode:t._layout.stepMode,attributes:[{format:t.format,offset:t.offset,shaderLocation:(i=j(e))!=null?i:0}]}]}}let n=[],a=new WeakMap,o=0;for(let[l,s]of Object.entries(e)){if(Ce(s))continue;let m=t[l];if(!m)throw new Error(`An attribute by the name of '${l}' was not provided to the shader.`);let g=m._layout,f=a.get(g);f||(r.push(g),f=[],n.push({arrayStride:g.stride,stepMode:g.stepMode,attributes:f}),a.set(g,f)),o=(u=j(s))!=null?u:o,f.push({format:m.format,offset:m.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var hn=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2f","mat3x3f","mat4x4f"];function wn(e){return hn.includes(e.type)}function Tt(e,[t,r]){return` ${Ee(r)}${t}: ${e.resolve(r)},
2
+ `}function Sn(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
3
3
  struct ${r} {
4
- ${Object.entries(t.propTypes).map(n=>dt(e,n)).join("")}}
5
- `),r}function xn(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
4
+ ${Object.entries(t.propTypes).map(n=>Tt(e,n)).join("")}}
5
+ `),r}function Fn(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
6
6
  struct ${r} {
7
- ${Object.entries(t.propTypes).map(n=>De(n[1])?dt(e,[n[0],we[n[1].format]]):dt(e,n)).join("")}
7
+ ${Object.entries(t.propTypes).map(n=>De(n[1])?Tt(e,[n[0],we[n[1].format]]):Tt(e,n)).join("")}
8
8
  }
9
- `),r}function bn(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function hn(e,t){let r=e.resolve(De(t.elementType)?we[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function mt(e,t){if(de(t))return t.type==="unstruct"?xn(e,t):t.type==="disarray"?hn(e,t):t.type==="loose-decorated"?e.resolve(De(t.inner)?we[t.inner.format]:t.inner):e.resolve(we[t.type]);if(yn(t))return t.type;if(t.type==="struct")return cn(e,t);if(t.type==="array")return bn(e,t);if(t.type==="atomic")return`atomic<${mt(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptrFn")return`ptr<function, ${e.resolve(t.inner)}>`;Ur(t,"resolveData")}function*Ar(e){let t=0;for(;;)e.has(t)||(yield t),t++}var wn=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"];function U(e,t){return ne(t.value)||N(t.value)?e.resolve(t.value):String(t.value)}function Sn(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function Ir(e,t){return t?{value:"true",dataType:rt}:{value:"false",dataType:rt}}function Rr(e,t){return`${e.indent()}{
10
- ${t.b.map(r=>ft(e,r)).join(`
9
+ `),r}function Dn(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Un(e,t){let r=e.resolve(De(t.elementType)?we[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function ct(e,t){if(Pe(t))return t.type==="unstruct"?Fn(e,t):t.type==="disarray"?Un(e,t):t.type==="loose-decorated"?e.resolve(De(t.inner)?we[t.inner.format]:t.inner):e.resolve(we[t.type]);if(wn(t))return t.type;if(t.type==="struct")return Sn(e,t);if(t.type==="array")return Dn(e,t);if(t.type==="atomic")return`atomic<${ct(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner)}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner)}>`;if(t.type==="abstractInt"||t.type==="abstractFloat")throw new Error("Abstract types have no concrete representation in WGSL");Br(t,"resolveData")}function*_r(e){let t=0;for(;;)e.has(t)||(yield t),t++}var vn=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"];function An(e,t,r){return t==="=="||t==="!="||t==="<"||t==="<="||t===">"||t===">="||t==="&&"||t==="||"?Le:t==="="?r:e}function F(e,t){return re(t.value)||de(t.value)?e.resolve(t.value):String(t.value)}function Rn(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function Lr(e,t){return t?{value:"true",dataType:Le}:{value:"false",dataType:Le}}function Cr(e,t){e.pushBlockScope();try{return`${e.indent()}{
10
+ ${t.b.map(r=>oe(e,r)).join(`
11
11
  `)}
12
- ${e.dedent()}}`}function gt(e,t){return e.getById(t)}function I(e,t){if(typeof t=="string")return gt(e,t);if(typeof t=="boolean")return Ir(e,t);if("x"in t){let[r,n,a]=t.x,o=U(e,I(e,r)),i=U(e,I(e,a));return{value:wn.includes(n)?`(${o} ${n} ${i})`:`${o} ${n} ${i}`,dataType:A}}if("u"in t){let[r,n]=t.u,a=U(e,I(e,n));return{value:`${r}${a}`,dataType:A}}if("a"in t){let[r,n]=t.a,a=I(e,r),o=U(e,I(e,n));if(typeof a.value=="string")return{value:`${a.value}.${o}`,dataType:A};if(ne(a.value))return{value:a.value[o],dataType:A};if(typeof a.value=="object")return{value:a.value[o],dataType:A};throw new Error(`Cannot access member ${o} of ${a.value}`)}if("i"in t){let[r,n]=t.i,a=U(e,I(e,r)),o=U(e,I(e,n));return{value:`${a}[${o}]`,dataType:A}}if("n"in t)return{value:t.n,dataType:A};if("f"in t){let[r,n]=t.f,o=I(e,r).value;e.callStack.push(o);let p=n.map(s=>I(e,s)).map(s=>U(e,s));return e.callStack.pop(),typeof o=="string"?{value:`${o}(${p.join(", ")})`,dataType:A}:B(o)?{value:`${e.resolve(o)}(${p.join(", ")})`,dataType:A}:{value:o(...p),dataType:A}}if("o"in t){let r=t.o,n=e.callStack[e.callStack.length-1],a=o=>o.map(i=>{let p=I(e,i);return U(e,p)}).join(", ");if(B(n)){let i=Object.keys(n.propTypes).map(p=>{let l=r[p];if(l===void 0)throw new Error(`Missing property ${p} in object literal for struct ${n}`);return l});return{value:a(i),dataType:n}}return{value:a(Object.values(r)),dataType:A}}Sn(t)}function ft(e,t){if(typeof t=="string")return`${e.pre}${U(e,gt(e,t))};`;if(typeof t=="boolean")return`${e.pre}${U(e,Ir(e,t))};`;if("r"in t){if(B(e.callStack[e.callStack.length-1])&&t.r!==null&&typeof t.r=="object"&&"o"in t.r){let r=U(e,I(e,t.r)),n=e.resolve(e.callStack[e.callStack.length-1]);return`${e.pre}return ${n}(${r});`}return t.r===null?`${e.pre}return;`:`${e.pre}return ${U(e,I(e,t.r))};`}if("q"in t){let[r,n,a]=t.q,o=U(e,I(e,r));e.indent();let i=ft(e,n);e.dedent(),e.indent();let p=a?ft(e,a):void 0;return e.dedent(),p?`${e.pre}if (${o})
12
+ ${e.dedent()}}`}finally{e.popBlockScope()}}function In(e,t,r){return e.defineVariable(t,r)}function yt(e,t){let r=e.getById(t);if(!r)throw new Error(`Identifier ${t} not found`);return r}function A(e,t){if(typeof t=="string")return yt(e,t);if(typeof t=="boolean")return Lr(e,t);if("x"in t){let[r,n,a]=t.x,o=A(e,r),i=F(e,o),u=A(e,a),l=F(e,u),s=An(o.dataType,n,u.dataType);return{value:vn.includes(n)?`(${i} ${n} ${l})`:`${i} ${n} ${l}`,dataType:s}}if("u"in t){let[r,n]=t.u,a=F(e,A(e,n));return{value:`${r}${a}`,dataType:P}}if("a"in t){let[r,n]=t.a,a=A(e,r),o=F(e,A(e,n));if(typeof a.value=="string")return{value:`${a.value}.${o}`,dataType:P};if(re(a.value))return{value:a.value[o],dataType:P};if(typeof a.value=="object")return{value:a.value[o],dataType:P};throw new Error(`Cannot access member ${o} of ${a.value}`)}if("i"in t){let[r,n]=t.i,a=F(e,A(e,r)),o=F(e,A(e,n));return{value:`${a}[${o}]`,dataType:P}}if("n"in t){let r=t.n;if(/^0x[0-9a-f]+$/i.test(r))return{value:r,dataType:_e};if(/^0b[01]+$/i.test(r))return{value:`${Number.parseInt(r.slice(2),2)}`,dataType:_e};if(/^-?(?:\d+\.\d*|\d*\.\d+)$/.test(r))return{value:r,dataType:it};if(/^-?\d+\.\d+e-?\d+$/.test(r))return{value:r,dataType:it};if(/^-?\d+$/.test(r))return{value:r,dataType:_e};throw new Error(`Invalid numeric literal ${r}`)}if("f"in t){let[r,n]=t.f,o=A(e,r).value;e.callStack.push(o);let u=n.map(s=>A(e,s)).map(s=>F(e,s));return e.callStack.pop(),typeof o=="string"?{value:`${o}(${u.join(", ")})`,dataType:P}:I(o)?{value:`${e.resolve(o)}(${u.join(", ")})`,dataType:P}:{value:o(...u),dataType:P}}if("o"in t){let r=t.o,n=e.callStack[e.callStack.length-1],a=o=>o.map(i=>{let u=A(e,i);return F(e,u)}).join(", ");if(I(n)){let i=Object.keys(n.propTypes).map(u=>{let l=r[u];if(l===void 0)throw new Error(`Missing property ${u} in object literal for struct ${n}`);return l});return{value:a(i),dataType:n}}return{value:a(Object.values(r)),dataType:P}}if("s"in t)throw new Error("Cannot use string literals in TGSL.");Rn(t)}function oe(e,t){if(typeof t=="string")return`${e.pre}${F(e,yt(e,t))};`;if(typeof t=="boolean")return`${e.pre}${F(e,Lr(e,t))};`;if("r"in t){if(I(e.callStack[e.callStack.length-1])&&t.r!==null&&typeof t.r=="object"&&"o"in t.r){let r=F(e,A(e,t.r)),n=e.resolve(e.callStack[e.callStack.length-1]);return`${e.pre}return ${n}(${r});`}return t.r===null?`${e.pre}return;`:`${e.pre}return ${F(e,A(e,t.r))};`}if("q"in t){let[r,n,a]=t.q,o=F(e,A(e,r));e.indent();let i=oe(e,n);e.dedent(),e.indent();let u=a?oe(e,a):void 0;return e.dedent(),u?`${e.pre}if (${o})
13
13
  ${i}
14
14
  ${e.pre}else
15
- ${p}`:`${e.pre}if (${o})
16
- ${i}`}if("l"in t||"c"in t){let[r,n]="l"in t?t.l:t.c,a=U(e,gt(e,r)),o=n?I(e,n):void 0;if(!o||!n)throw new Error("Cannot create variable without an initial value.");if(typeof n=="object"&&"o"in n&&B(e.callStack[e.callStack.length-1])){let i=e.resolve(e.callStack[e.callStack.length-1]);return`${e.pre}var ${a} = ${i}(${U(e,o)});`}return`${e.pre}var ${a} = ${U(e,o)};`}return"b"in t?Rr(e,t):`${e.pre}${U(e,I(e,t))};`}function Tt(e,t){return Rr(e,t)}import{BufferReader as bt,BufferWriter as ht}from"typed-binary";function Fn(e,t){let r="size"in e?e.size:e.currentByteOffset,n=t-1,a=r&n;"skipBytes"in e?e.skipBytes(t-a&n):e.add(t-a&n)}var h=Fn;var P={bool(e,t,r){e.writeBool(r)},f32(e,t,r){e.writeFloat32(r)},f16(e,t,r){e.writeFloat16(r)},i32(e,t,r){e.writeInt32(r)},u32(e,t,r){e.writeUint32(r)},vec2f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},vec2h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},vec2i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},vec2u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},vec3f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},vec3h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z)},vec3i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},vec3u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},vec4f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},vec4h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},vec4i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},vec4u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},mat2x2f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat3x3f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat4x4f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},struct(e,t,r){let n=D(t);h(e,n);for(let[a,o]of Object.entries(t.propTypes))h(e,D(o)),X(e,o,r[a]);h(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=D(t);h(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)h(e,n),X(e,t.elementType,r[o]);e.seekTo(a+x(t))},ptrFn(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){var n;(n=P[t.inner.type])==null||n.call(P,e,t,r)},decorated(e,t,r){var o,i;let n=O(t);h(e,n);let a=e.currentByteOffset;(i=P[(o=t.inner)==null?void 0:o.type])==null||i.call(P,e,t.inner,r),e.seekTo(a+x(t))},uint8(e,t,r){e.writeUint8(r)},uint8x2(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y)},uint8x4(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y),e.writeUint8(r.z),e.writeUint8(r.w)},sint8(e,t,r){e.writeInt8(r)},sint8x2(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y)},sint8x4(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y),e.writeInt8(r.z),e.writeInt8(r.w)},unorm8(e,t,r){e.writeUint8(r*255)},unorm8x2(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255)},unorm8x4(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255),e.writeUint8(r.z*255),e.writeUint8(r.w*255)},snorm8(e,t,r){e.writeUint8(r*127+128)},snorm8x2(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128)},snorm8x4(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128),e.writeUint8(r.z*127+128),e.writeUint8(r.w*127+128)},uint16(e,t,r){e.writeUint16(r)},uint16x2(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y)},uint16x4(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y),e.writeUint16(r.z),e.writeUint16(r.w)},sint16(e,t,r){e.writeInt16(r)},sint16x2(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y)},sint16x4(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y),e.writeInt16(r.z),e.writeInt16(r.w)},unorm16(e,t,r){e.writeUint16(r*65535)},unorm16x2(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535)},unorm16x4(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535),e.writeUint16(r.z*65535),e.writeUint16(r.w*65535)},snorm16(e,t,r){e.writeUint16(r*32767+32768)},snorm16x2(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768)},snorm16x4(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768),e.writeUint16(r.z*32767+32768),e.writeUint16(r.w*32767+32768)},float16(e,t,r){e.writeFloat16(r)},float16x2(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},float16x4(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},float32(e,t,r){e.writeFloat32(r)},float32x2(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},float32x3(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},float32x4(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},uint32(e,t,r){e.writeUint32(r)},uint32x2(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},uint32x3(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},uint32x4(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},sint32(e,t,r){e.writeInt32(r)},sint32x2(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},sint32x3(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},sint32x4(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},"unorm10-10-10-2"(e,t,r){let n=0;n|=(r.x*1023&1023)<<22,n|=(r.x*1023&1023)<<12,n|=(r.y*1023&1023)<<2,n|=r.z*3&3,e.writeUint32(n)},"unorm8x4-bgra"(e,t,r){e.writeUint8(r.z*255),e.writeUint8(r.y*255),e.writeUint8(r.x*255),e.writeUint8(r.w*255)},disarray(e,t,r){var o,i;let n=D(t);h(e,n);let a=e.currentByteOffset;for(let p=0;p<Math.min(t.elementCount,r.length);p++)h(e,n),(i=P[(o=t.elementType)==null?void 0:o.type])==null||i.call(P,e,t.elementType,r[p]);e.seekTo(a+x(t))},unstruct(e,t,r){var n;for(let[a,o]of Object.entries(t.propTypes))(n=P[o.type])==null||n.call(P,e,o,r[a])},"loose-decorated"(e,t,r){var i;let n=O(t);h(e,n);let a=e.currentByteOffset,o=P[(i=t.inner)==null?void 0:i.type];return o==null||o(e,t.inner,r),e.seekTo(a+x(t)),r}};function X(e,t,r){let n=P[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var ie={bool(e){return e.readBool()},f32(e){return e.readFloat32()},f16(e){return e.readFloat16()},i32(e){return e.readInt32()},u32(e){return e.readUint32()},vec2f(e){return K(e.readFloat32(),e.readFloat32())},vec3f(e){return at(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return ar(e.readFloat16(),e.readFloat16())},vec3h(e){return or(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return ir(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return be(e.readInt32(),e.readInt32())},vec3i(e){return ot(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return C(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return he(e.readUint32(),e.readUint32())},vec3u(e){return it(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return V(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},mat2x2f(e){return sr(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return ur(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return pr(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},struct(e,t){let r=D(t);h(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))h(e,D(o)),n[a]=E(e,o);return h(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=D(t),n=[];for(let a=0;a<t.elementCount;a++){h(e,r);let o=t.elementType,i=E(e,o);n.push(i)}return h(e,r),n},ptrFn(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return E(e,t.inner)},decorated(e,t){let r=O(t);h(e,r);let n=e.currentByteOffset,a=E(e,t.inner);return e.seekTo(n+x(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>he(e.readUint8(),e.readUint8()),uint8x4:e=>V(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>be(e.readInt8(),e.readInt8()),sint8x4:e=>C(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>K(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>F(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>(e.readUint8()-128)/127,snorm8x2:e=>K((e.readUint8()-128)/127,(e.readUint8()-128)/127),snorm8x4:e=>F((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>he(e.readUint16(),e.readUint16()),uint16x4:e=>V(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>be(e.readInt16(),e.readInt16()),sint16x4:e=>C(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>K(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>F(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>K(ie.snorm16(e),ie.snorm16(e)),snorm16x4:e=>F(ie.snorm16(e),ie.snorm16(e),ie.snorm16(e),ie.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>K(e.readFloat16(),e.readFloat16()),float16x4:e=>F(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>K(e.readFloat32(),e.readFloat32()),float32x3:e=>at(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>he(e.readUint32(),e.readUint32()),uint32x3:e=>it(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>V(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>be(e.readInt32(),e.readInt32()),sint32x3:e=>ot(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>C(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32()),"unorm10-10-10-2"(e){let t=e.readUint32(),r=(t>>22)/1023,n=(t>>12&1023)/1023,a=(t>>2&1023)/1023,o=(t&3)/3;return F(r,n,a,o)},"unorm8x4-bgra"(e){let t=e.readByte()/255,r=e.readByte()/255,n=e.readByte()/255,a=e.readByte()/255;return F(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=E(e,a);return r},disarray(e,t){let r=D(t),n=[];for(let a=0;a<t.elementCount;a++)h(e,r),n.push(E(e,t.elementType));return h(e,r),n},"loose-decorated"(e,t){h(e,O(t));let r=e.currentByteOffset,n=E(e,t.inner);return e.seekTo(r+x(t)),n}};function E(e,t){let r=ie[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as Un}from"typed-binary";import{Measurer as Dn}from"typed-binary";var Br=new WeakMap;function Pr(e){let t=Br.get(e);if(t)return t;let r=new Dn,n={},a;for(let o in e.propTypes){let i=e.propTypes[o];if(i===void 0)throw new Error(`Property ${o} is undefined in struct`);let p=r.size;h(r,me(e)?O(i):D(i)),a&&(a.padding=r.size-p);let l=x(i);n[o]={offset:r.size,size:l},a=n[o],r.add(l)}return a&&(a.padding=M(x(e),D(e))-r.size),Br.set(e,n),n}function _r(e,t){var s;let r=x(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new Un(n),o=[];function i(m,g,f,w){var c;if(g!=null)if(B(m)||me(m)){let T=Pr(m);for(let[b,y]of Object.entries(T)){let S=m.propTypes[b];if(!S)continue;let pe=g[b];pe!==void 0&&i(S,pe,f+y.offset,(c=y.padding)!=null?c:w)}}else if(Be(m)||rr(m)){let T=m,b=M(x(T.elementType),D(T.elementType));if(!Array.isArray(g))throw new Error("Partial value for array must be an array");let y=g;y.sort((S,pe)=>S.idx-pe.idx);for(let{idx:S,value:pe}of y)i(T.elementType,pe,f+S*b,b-x(T.elementType))}else{let T=x(m);a.seekTo(f),X(a,m,g),o.push({start:f,end:f+T,padding:w})}}if(i(e,t,0),o.length===0)return[];let p=[],l=o[0];for(let m=1;m<o.length;m++){let g=o[m];if(!g||!l)throw new Error("Internal error: missing segment");g.start===l.end+((s=l.padding)!=null?s:0)?(l.end=g.end,l.padding=g.padding):(p.push({data:new Uint8Array(n,l.start,l.end-l.start)}),l=g)}if(!l)throw new Error("Internal error: missing segment");return p.push({data:new Uint8Array(n,l.start,l.end-l.start)}),p}function se(e){return!!(e!=null&&e.usableAsStorage)}var Ue=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Ee(e){return!!e.usableAsUniform}var Er={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},ve=class{constructor(t,r){this.usage=t;this.buffer=r;u(this,"~repr");u(this,"resourceType","buffer-usage")}get label(){return this.buffer.label}$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Er[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}write(t){this.buffer.write(t)}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},k)}},Ae=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;u(this,"~repr");u(this,"resourceType","buffer-usage")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=Er[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},k)}},Lr=new WeakMap;function yt(e){if(!se(e))throw new Error(`Cannot pass ${e} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Lr.get(e);return t||(t=new ve("mutable",e),Lr.set(e,t)),t}var Cr=new WeakMap;function ct(e){if(!se(e))throw new Error(`Cannot pass ${e} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Cr.get(e);return t||(t=new ve("readonly",e),Cr.set(e,t)),t}var Vr=new WeakMap;function xt(e){if(!Ee(e))throw new Error(`Cannot pass ${e} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`);let t=Vr.get(e);return t||(t=new ve("uniform",e),Vr.set(e,t)),t}var wt={uniform:xt,mutable:yt,readonly:ct};function Gr(e,t,r){return N(t)?new Ge(e,t,r):new Ge(e,t,r,["storage","uniform"])}function Z(e){return e.resourceType==="buffer"}function vn(e){return!!e.usableAsVertex}var Ge=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;u(this,"resourceType","buffer");u(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);u(this,"_buffer",null);u(this,"_ownBuffer");u(this,"_destroyed",!1);u(this,"_label");u(this,"initial");u(this,"usableAsUniform",!1);u(this,"usableAsStorage",!1);u(this,"usableAsVertex",!1);mr(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}get label(){return this._label}get buffer(){var r;let t=this._group.device;if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=t.createBuffer({size:x(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:(r=this.label)!=null?r:"<unnamed>"}),this.initial)){let n=new ht(this._buffer.getMappedRange());X(n,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(t){return this._label=t,this._buffer&&(this._buffer.label=t),this}$usage(...t){var r;for(let n of t){if((r=this._disallowedUsages)!=null&&r.includes(n))throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${n}`);this.flags|=n==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=n==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=n==="vertex"?GPUBufferUsage.VERTEX:0,this.usableAsUniform=this.usableAsUniform||n==="uniform",this.usableAsStorage=this.usableAsStorage||n==="storage",this.usableAsVertex=this.usableAsVertex||n==="vertex"}return this}$addFlags(t){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return t&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):t&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=t,this)}write(t){let r=this.buffer,n=this._group.device;if(r.mapState==="mapped"){let i=r.getMappedRange();X(new ht(i),this.dataType,t);return}let a=x(this.dataType);this._group.flush();let o=new ArrayBuffer(a);X(new ht(o),this.dataType,t),n.queue.writeBuffer(r,0,o,0,a)}writePartial(t){let r=this.buffer,n=this._group.device,a=_r(this.dataType,t);if(r.mapState==="mapped"){let o=r.getMappedRange(),i=new Uint8Array(o);for(let p of a)i.set(p.data,p.data.byteOffset)}else for(let o of a)n.queue.writeBuffer(r,o.data.byteOffset,o.data,0,o.data.byteLength)}copyFrom(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=x(this.dataType);this._group.commandEncoder.copyBufferToBuffer(t.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let t=this.buffer,r=this._group.device;if(t.mapState==="mapped"){let i=t.getMappedRange();return E(new bt(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),p=E(new bt(i),this.dataType);return t.unmap(),p}let n=r.createBuffer({size:x(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,x(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,x(this.dataType));let o=E(new bt(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){var r;return(r=wt[t])==null?void 0:r.call(wt,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,this._ownBuffer&&((t=this._buffer)==null||t.destroy()))}toString(){var t;return`buffer:${(t=this._label)!=null?t:"<unnamed>"}`}};function Or(e){return new St(e)}function kr(e){return new Ft(e)}function Dt(e){return(e==null?void 0:e.resourceType)==="sampler"}function Ut(e){return(e==null?void 0:e.resourceType)==="sampler-comparison"}var Oe=class{constructor(t){this._membership=t;u(this,"resourceType","sampler")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},ke=class{constructor(t){this._membership=t;u(this,"resourceType","sampler-comparison")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},St=class{constructor(t){this._props=t;u(this,"resourceType","sampler");u(this,"_label");u(this,"_filtering");u(this,"_sampler",null);this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}unwrap(t){var r;return this._sampler||(this._sampler=t.device.createSampler(R(v({},this._props),{label:(r=this._label)!=null?r:"<unnamed>"}))),this._sampler}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label),{group:n,binding:a}=t.allocateFixedEntry({sampler:this._filtering?"filtering":"non-filtering"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},Ft=class{constructor(t){this._props=t;u(this,"resourceType","sampler-comparison");u(this,"_label");u(this,"_sampler",null)}unwrap(t){var r;return this._sampler||(this._sampler=t.device.createSampler(R(v({},this._props),{label:(r=this._label)!=null?r:"<unnamed>"}))),this._sampler}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry({sampler:"comparison"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler_comparison;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};var $e=class{constructor(t){this._membership=t;u(this,"resourceType","external-texture")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};var $r={r8unorm:d,r8snorm:d,r8uint:_,r8sint:L,r16uint:_,r16sint:L,r16float:d,rg8unorm:d,rg8snorm:d,rg8uint:_,rg8sint:L,r32uint:_,r32sint:L,r32float:d,rg16uint:_,rg16sint:L,rg16float:d,rgba8unorm:d,"rgba8unorm-srgb":d,rgba8snorm:d,rgba8uint:_,rgba8sint:L,bgra8unorm:d,"bgra8unorm-srgb":d,rgb9e5ufloat:d,rgb10a2uint:_,rgb10a2unorm:d,rg11b10ufloat:d,rg32uint:_,rg32sint:L,rg32float:d,rgba16uint:_,rgba16sint:L,rgba16float:d,rgba32uint:_,rgba32sint:L,rgba32float:d,stencil8:d,depth16unorm:d,depth24plus:d,"depth24plus-stencil8":d,depth32float:d,"depth32float-stencil8":d,"bc1-rgba-unorm":d,"bc1-rgba-unorm-srgb":d,"bc2-rgba-unorm":d,"bc2-rgba-unorm-srgb":d,"bc3-rgba-unorm":d,"bc3-rgba-unorm-srgb":d,"bc4-r-unorm":d,"bc4-r-snorm":d,"bc5-rg-unorm":d,"bc5-rg-snorm":d,"bc6h-rgb-ufloat":d,"bc6h-rgb-float":d,"bc7-rgba-unorm":d,"bc7-rgba-unorm-srgb":d,"etc2-rgb8unorm":d,"etc2-rgb8unorm-srgb":d,"etc2-rgb8a1unorm":d,"etc2-rgb8a1unorm-srgb":d,"etc2-rgba8unorm":d,"etc2-rgba8unorm-srgb":d,"eac-r11unorm":d,"eac-r11snorm":d,"eac-rg11unorm":d,"eac-rg11snorm":d,"astc-4x4-unorm":d,"astc-4x4-unorm-srgb":d,"astc-5x4-unorm":d,"astc-5x4-unorm-srgb":d,"astc-5x5-unorm":d,"astc-5x5-unorm-srgb":d,"astc-6x5-unorm":d,"astc-6x5-unorm-srgb":d,"astc-6x6-unorm":d,"astc-6x6-unorm-srgb":d,"astc-8x5-unorm":d,"astc-8x5-unorm-srgb":d,"astc-8x6-unorm":d,"astc-8x6-unorm-srgb":d,"astc-8x8-unorm":d,"astc-8x8-unorm-srgb":d,"astc-10x5-unorm":d,"astc-10x5-unorm-srgb":d,"astc-10x6-unorm":d,"astc-10x6-unorm-srgb":d,"astc-10x8-unorm":d,"astc-10x8-unorm-srgb":d,"astc-10x10-unorm":d,"astc-10x10-unorm-srgb":d,"astc-12x10-unorm":d,"astc-12x10-unorm-srgb":d,"astc-12x12-unorm":d,"astc-12x12-unorm-srgb":d},Ie={rgba8unorm:F,rgba8snorm:F,rgba8uint:V,rgba8sint:C,rgba16uint:V,rgba16sint:C,rgba16float:F,r32uint:V,r32sint:C,r32float:F,rg32uint:V,rg32sint:C,rg32float:F,rgba32uint:V,rgba32sint:C,rgba32float:F,bgra8unorm:F},Mr={f32:"float",u32:"uint",i32:"sint"},Wr={float:d,"unfilterable-float":d,uint:_,sint:L,depth:d};function Nr(e,t){return new vt(e,t)}function W(e){return(e==null?void 0:e.resourceType)==="texture"}function Rt(e){return(e==null?void 0:e.resourceType)==="texture-storage-view"}function Bt(e){return(e==null?void 0:e.resourceType)==="texture-sampled-view"}var jr={mutable:"read_write",readonly:"read",writeonly:"write"},vt=class{constructor(t,r){this.props=t;this._branch=r;u(this,"resourceType","texture");u(this,"usableAsSampled",!1);u(this,"usableAsStorage",!1);u(this,"usableAsRender",!1);u(this,"_destroyed",!1);u(this,"_label");u(this,"_flags",GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC);u(this,"_texture",null)}get label(){return this._label}$name(t){return this._label=t,this}unwrap(){var t,r,n,a,o;if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:(t=this._label)!=null?t:"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:(r=this.props.dimension)!=null?r:"2d",viewFormats:(n=this.props.viewFormats)!=null?n:[],mipLevelCount:(a=this.props.mipLevelCount)!=null?a:1,sampleCount:(o=this.props.sampleCount)!=null?o:1})),this._texture}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||(this.usableAsStorage=r),this.usableAsSampled||(this.usableAsSampled=n),this.usableAsRender||(this.usableAsRender=a),this}createView(t,r){if(t==="sampled")return this._asSampled(r);let n=r;switch(t){case"mutable":return this._asMutable(n);case"readonly":return this._asReadonly(n);case"writeonly":return this._asWriteonly(n)}}_asStorage(t,r){var o;if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=(o=t==null?void 0:t.format)!=null?o:this.props.format,a=Ie[n];return ce(!!a,`Unsupported storage texture format: ${n}`),new At(t!=null?t:{},r,this)}_asReadonly(t){return this._asStorage(t,"readonly")}_asWriteonly(t){return this._asStorage(t,"writeonly")}_asMutable(t){return this._asStorage(t,"mutable")}_asSampled(t){var a;if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=(a=t==null?void 0:t.format)!=null?a:this.props.format;if(!Ie[r])throw new Error(`Unsupported storage texture format: ${r}`);return new It(t,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,(t=this._texture)==null||t.destroy())}},Ne={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},At=class{constructor(t,r,n){this.access=r;this._texture=n;u(this,"resourceType","texture-storage-view");u(this,"texelDataType");u(this,"dimension");u(this,"_view");u(this,"_format");var a,o,i;this.dimension=(o=(a=t==null?void 0:t.dimension)!=null?a:n.props.dimension)!=null?o:"2d",this._format=(i=t==null?void 0:t.format)!=null?i:n.props.format,this.texelDataType=Ie[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Ne[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${jr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},Me=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;u(this,"resourceType","texture-storage-view");u(this,"texelDataType");this.texelDataType=Ie[this._format]}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Ne[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${jr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},It=class{constructor(t,r){this._props=t;this._texture=r;u(this,"resourceType","texture-sampled-view");u(this,"channelDataType");u(this,"dimension");u(this,"_format");u(this,"_view");var n,a,o;this.dimension=(a=(n=t==null?void 0:t.dimension)!=null?n:r.props.dimension)!=null?a:"2d",this._format=(o=t==null?void 0:t.format)!=null?o:r.props.format,this.channelDataType=$r[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView(v({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`},this._props))),this._view}"~resolve"(t){var p;let r=t.names.makeUnique(this.label),n=((p=this._texture.props.sampleCount)!=null?p:1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:Mr[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${Ne[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},We=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;u(this,"resourceType","texture-sampled-view");u(this,"channelDataType");this.channelDataType=Wr[t]}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Ne[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};function Pt(e){return!!(e!=null&&e.usableAsSampled)}function An(e){return!!(e!=null&&e.usableAsRender)}var je=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function ze(e){return new Lt(e)}function Ke(e){return!!e&&e.resourceType==="bind-group-layout"}function Ct(e){return!!e&&e.resourceType==="bind-group"}var _t=class e extends Error{constructor(t,r){super(`Bind group '${t!=null?t:"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},zr=["compute"],Te=["compute","vertex","fragment"],Lt=class{constructor(t){this.entries=t;u(this,"_label");u(this,"_index");u(this,"resourceType","bind-group-layout");u(this,"bound",{});var n,a,o,i,p;let r=0;for(let[l,s]of Object.entries(t)){if(s===null){r++;continue}let m={idx:r,key:l,layout:this};if("uniform"in s&&(this.bound[l]=new Ae("uniform",s.uniform,m)),"storage"in s){let g="type"in s.storage?s.storage:s.storage(0);this.bound[l]=new Ae((n=s.access)!=null?n:"readonly",g,m)}"texture"in s&&(this.bound[l]=new We(s.texture,(a=s.viewDimension)!=null?a:"2d",(o=s.multisampled)!=null?o:!1,m)),"storageTexture"in s&&(this.bound[l]=new Me(s.storageTexture,(i=s.viewDimension)!=null?i:"2d",(p=s.access)!=null?p:"writeonly",m)),"externalTexture"in s&&(this.bound[l]=new $e(m)),"sampler"in s&&(s.sampler==="comparison"?this.bound[l]=new ke(m):this.bound[l]=new Oe(m)),r++}}get label(){return this._label}get index(){return this._index}$name(t){return this._label=t,this}$idx(t){return this._index=t,this}unwrap(t){var n;return t.device.createBindGroupLayout({label:(n=this.label)!=null?n:"<unnamed>",entries:Object.values(this.entries).map((a,o)=>{var l,s,m,g;if(a===null)return null;let i=a.visibility,p={binding:o,visibility:0};if("uniform"in a)i=i!=null?i:Te,p.buffer={type:"uniform"};else if("storage"in a)i=i!=null?i:a.access==="mutable"?zr:Te,p.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)i=i!=null?i:Te,p.sampler={type:a.sampler};else if("texture"in a)i=i!=null?i:Te,p.texture={sampleType:a.texture,viewDimension:(l=a.viewDimension)!=null?l:"2d",multisampled:(s=a.multisampled)!=null?s:!1};else if("storageTexture"in a){let f=(m=a.access)!=null?m:"writeonly";i=i!=null?i:f==="readonly"?Te:zr,p.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[f],viewDimension:(g=a.viewDimension)!=null?g:"2d"}}else"externalTexture"in a&&(i=i!=null?i:Te,p.externalTexture={});return i!=null&&i.includes("compute")&&(p.visibility|=GPUShaderStage.COMPUTE),i!=null&&i.includes("vertex")&&(p.visibility|=GPUShaderStage.VERTEX),i!=null&&i.includes("fragment")&&(p.visibility|=GPUShaderStage.FRAGMENT),p}).filter(a=>a!==null)})}populate(t){return new ue(this,t)}},ue=class{constructor(t,r){this.layout=t;this.entries=r;u(this,"resourceType","bind-group");for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new _t(t.label,n)}unwrap(t){var n;return t.device.createBindGroup({label:(n=this.layout.label)!=null?n:"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([a,o],i)=>{var l;if(o===null)return null;let p=this.entries[a];if(p===void 0)throw new Error(`'${a}' is a resource required to populate bind group layout '${(l=this.layout.label)!=null?l:"<unnamed>"}'.`);if("uniform"in o){let s;if(Z(p)){if(!Ee(p))throw new et(p);s={buffer:t.unwrap(p)}}else s={buffer:p};return{binding:i,resource:s}}if("storage"in o){let s;if(Z(p)){if(!se(p))throw new Ue(p);s={buffer:t.unwrap(p)}}else s={buffer:p};return{binding:i,resource:s}}if("texture"in o){let s;if(W(p)){if(!Pt(p))throw new je(p);s=t.unwrap(p.createView("sampled"))}else s=p;return{binding:i,resource:s}}if("storageTexture"in o){let s;if(W(p)){if(!se(p))throw new Ue(p);o.access==="readonly"?s=t.unwrap(p.createView("readonly")):o.access==="mutable"?s=t.unwrap(p.createView("mutable")):s=t.unwrap(p.createView("writeonly"))}else s=p;return{binding:i,resource:s}}if("externalTexture"in o||"sampler"in o)return{binding:i,resource:p};throw new Error(`Malformed bind group entry: ${p} (${JSON.stringify(p)})`)}).filter(a=>a!==null)})}};var Kr="#CATCHALL#",Et=class{constructor(){u(this,"_stack",[]);u(this,"_itemDepth",0)}get itemDepth(){return this._itemDepth}get topItem(){let t=this._stack[this._stack.length-1];if(!t||t.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return t}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}pushSlotBindings(t){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(t)})}pushFunctionScope(t,r,n){this._stack.push({type:"functionScope",args:t,returnType:r,externalMap:n})}pop(){let t=this._stack.pop();(t==null?void 0:t.type)==="item"&&this._itemDepth--}readSlot(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="item")n.usedSlots.add(t);else if((n==null?void 0:n.type)==="slotBinding"){let a=n.bindingMap.get(t);if(a!==void 0)return a}else if(!((n==null?void 0:n.type)==="functionScope"||(n==null?void 0:n.type)==="blockScope"))throw new Error("Unknown layer type.")}return t.defaultValue}getResourceById(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="functionScope"){let a=n.args.find(i=>i.value===t);if(a!==void 0)return a;let o=n.externalMap[t];return o!==void 0?{value:o,dataType:A}:void 0}if((n==null?void 0:n.type)==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return{value:t,dataType:a}}}}},qe=[""," "," "," "," "," "," "," "," "],Vt=qe.length-1,Gt=class{constructor(){u(this,"identLevel",0)}get pre(){var t;return(t=qe[this.identLevel])!=null?t:qe[Vt].repeat(this.identLevel/Vt)+qe[this.identLevel%Vt]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Ot=class{constructor(t){u(this,"_memoizedResolves",new WeakMap);u(this,"_memoizedDerived",new WeakMap);u(this,"_indentController",new Gt);u(this,"_jitTranspiler");u(this,"_itemStateStack",new Et);u(this,"_declarations",[]);u(this,"bindGroupLayoutsToPlaceholderMap",new Map);u(this,"_nextFreeLayoutPlaceholderIdx",0);u(this,"fixedBindings",[]);u(this,"callStack",[]);u(this,"names");this.names=t.names,this._jitTranspiler=t.jitTranspiler}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){var r;return(r=this._itemStateStack.getResourceById(t))!=null?r:{value:t,dataType:A}}transpileFn(t){if(!this._jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._jitTranspiler.transpileFn(t)}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.returnType,t.externalMap);let r=Tt(this,t.body);this._itemStateStack.pop();let n=t.args.map(a=>`${a.value}: ${this.resolve(a.dataType)}`).join(", ");return{head:t.returnType!==void 0?`(${n}) -> ${_e(t.returnType)} ${this.resolve(t.returnType)}`:`(${n})`,body:r}}addDeclaration(t){this._declarations.push(t)}allocateLayoutEntry(t){let r=this.bindGroupLayoutsToPlaceholderMap,n=r.get(t);return n||(n=`#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`,r.set(t,n)),n}allocateFixedEntry(t,r){let n=this.fixedBindings.length;return this.fixedBindings.push({layoutEntry:t,resource:r}),{group:Kr,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new Ze(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.pop()}}unwrap(t){if(Se(t))return this.withSlots(t["~providing"].pairs,()=>this.unwrap(t["~providing"].inner));let r=t;for(;;)if(q(r))r=this.readSlot(r);else if(J(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(t){var n;let r=(n=this._memoizedDerived.get(t))!=null?n:[];this._itemStateStack.pushItem();try{for(let i of r)if([...i.slotToValueMap.entries()].every(([l,s])=>l.areEqual(this._itemStateStack.readSlot(l),s)))return i.result;let a=t["~compute"](),o=new Map;for(let i of this._itemStateStack.topItem.usedSlots)o.set(i,this._itemStateStack.readSlot(i));return r.push({slotToValueMap:o,result:a}),this._memoizedDerived.set(t,r),a}catch(a){throw a instanceof le?a.appendToTrace(t):new le(a,[t])}finally{this._itemStateStack.pop()}}_getOrInstantiate(t){var n;let r=(n=this._memoizedResolves.get(t))!=null?n:[];this._itemStateStack.pushItem();try{for(let i of r)if([...i.slotToValueMap.entries()].every(([l,s])=>l.areEqual(this._itemStateStack.readSlot(l),s)))return i.result;let a;N(t)||de(t)?a=mt(this,t):J(t)||q(t)?a=this.resolve(this.unwrap(t)):st(t)?a=t["~resolve"](this):a=this.resolveValue(t);let o=new Map;for(let i of this._itemStateStack.topItem.usedSlots)o.set(i,this._itemStateStack.readSlot(i));return r.push({slotToValueMap:o,result:a}),this._memoizedResolves.set(t,r),a}catch(a){throw a instanceof le?a.appendToTrace(t):new le(a,[t])}finally{this._itemStateStack.pop()}}resolve(t){if(Se(t))return this.withSlots(t["~providing"].pairs,()=>this.resolve(t["~providing"].inner));if(t&&typeof t=="object"||typeof t=="function"){if(this._itemStateStack.itemDepth===0){let r=Xt(this,()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
15
+ ${u}`:`${e.pre}if (${o})
16
+ ${i}`}if("l"in t||"c"in t){let[r,n]="l"in t?t.l:t.c,a=n?A(e,n):void 0;if(!a||!n)throw new Error("Cannot create variable without an initial value.");In(e,r,a.dataType);let o=F(e,yt(e,r));if(typeof n=="object"&&"o"in n&&I(e.callStack[e.callStack.length-1])){let i=e.resolve(e.callStack[e.callStack.length-1]);return`${e.pre}var ${o} = ${i}(${F(e,a)});`}return`${e.pre}var ${o} = ${F(e,a)};`}if("b"in t){e.pushBlockScope();try{return Cr(e,t)}finally{e.popBlockScope()}}if("j"in t){let[r,n,a,o]=t.j,i=r?oe(e,r):void 0,u=i?i.slice(0,-1):"",l=n?A(e,n):void 0,s=l?F(e,l):"",m=a?oe(e,a):void 0,g=m?m.slice(0,-1):"";e.indent();let f=oe(e,o);return e.dedent(),`${e.pre}for (${u}; ${s}; ${g})
17
+ ${f}`}if("w"in t){let[r,n]=t.w,a=F(e,A(e,r));e.indent();let o=oe(e,n);return e.dedent(),`${e.pre}while (${a})
18
+ ${o}`}return"k"in t?`${e.pre}continue;`:"d"in t?`${e.pre}break;`:`${e.pre}${F(e,A(e,t))};`}function xt(e,t){return Cr(e,t)}import{BufferReader as St,BufferWriter as Ft}from"typed-binary";function Bn(e,t){let r="size"in e?e.size:e.currentByteOffset,n=t-1,a=r&n;"skipBytes"in e?e.skipBytes(t-a&n):e.add(t-a&n)}var h=Bn;var B={bool(e,t,r){e.writeBool(r)},f32(e,t,r){e.writeFloat32(r)},f16(e,t,r){e.writeFloat16(r)},i32(e,t,r){e.writeInt32(r)},u32(e,t,r){e.writeUint32(r)},vec2f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},vec2h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},vec2i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},vec2u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},vec3f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},vec3h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z)},vec3i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},vec3u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},vec4f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},vec4h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},vec4i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},vec4u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},mat2x2f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat3x3f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat4x4f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},struct(e,t,r){let n=v(t);h(e,n);for(let[a,o]of Object.entries(t.propTypes))h(e,v(o)),Q(e,o,r[a]);h(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=v(t);h(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)h(e,n),Q(e,t.elementType,r[o]);e.seekTo(a+b(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){var n;(n=B[t.inner.type])==null||n.call(B,e,t,r)},decorated(e,t,r){var o,i;let n=O(t);h(e,n);let a=e.currentByteOffset;(i=B[(o=t.inner)==null?void 0:o.type])==null||i.call(B,e,t.inner,r),e.seekTo(a+b(t))},uint8(e,t,r){e.writeUint8(r)},uint8x2(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y)},uint8x4(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y),e.writeUint8(r.z),e.writeUint8(r.w)},sint8(e,t,r){e.writeInt8(r)},sint8x2(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y)},sint8x4(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y),e.writeInt8(r.z),e.writeInt8(r.w)},unorm8(e,t,r){e.writeUint8(r*255)},unorm8x2(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255)},unorm8x4(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255),e.writeUint8(r.z*255),e.writeUint8(r.w*255)},snorm8(e,t,r){e.writeUint8(r*127+128)},snorm8x2(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128)},snorm8x4(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128),e.writeUint8(r.z*127+128),e.writeUint8(r.w*127+128)},uint16(e,t,r){e.writeUint16(r)},uint16x2(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y)},uint16x4(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y),e.writeUint16(r.z),e.writeUint16(r.w)},sint16(e,t,r){e.writeInt16(r)},sint16x2(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y)},sint16x4(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y),e.writeInt16(r.z),e.writeInt16(r.w)},unorm16(e,t,r){e.writeUint16(r*65535)},unorm16x2(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535)},unorm16x4(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535),e.writeUint16(r.z*65535),e.writeUint16(r.w*65535)},snorm16(e,t,r){e.writeUint16(r*32767+32768)},snorm16x2(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768)},snorm16x4(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768),e.writeUint16(r.z*32767+32768),e.writeUint16(r.w*32767+32768)},float16(e,t,r){e.writeFloat16(r)},float16x2(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},float16x4(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},float32(e,t,r){e.writeFloat32(r)},float32x2(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},float32x3(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},float32x4(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},uint32(e,t,r){e.writeUint32(r)},uint32x2(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},uint32x3(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},uint32x4(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},sint32(e,t,r){e.writeInt32(r)},sint32x2(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},sint32x3(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},sint32x4(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},"unorm10-10-10-2"(e,t,r){let n=0;n|=(r.x*1023&1023)<<22,n|=(r.x*1023&1023)<<12,n|=(r.y*1023&1023)<<2,n|=r.z*3&3,e.writeUint32(n)},"unorm8x4-bgra"(e,t,r){e.writeUint8(r.z*255),e.writeUint8(r.y*255),e.writeUint8(r.x*255),e.writeUint8(r.w*255)},disarray(e,t,r){var o,i;let n=v(t);h(e,n);let a=e.currentByteOffset;for(let u=0;u<Math.min(t.elementCount,r.length);u++)h(e,n),(i=B[(o=t.elementType)==null?void 0:o.type])==null||i.call(B,e,t.elementType,r[u]);e.seekTo(a+b(t))},unstruct(e,t,r){var n;for(let[a,o]of Object.entries(t.propTypes))(n=B[o.type])==null||n.call(B,e,o,r[a])},"loose-decorated"(e,t,r){var i;let n=O(t);h(e,n);let a=e.currentByteOffset,o=B[(i=t.inner)==null?void 0:i.type];return o==null||o(e,t.inner,r),e.seekTo(a+b(t)),r}};function Q(e,t,r){let n=B[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var ie={bool(e){return e.readBool()},f32(e){return e.readFloat32()},f16(e){return e.readFloat16()},i32(e){return e.readInt32()},u32(e){return e.readUint32()},vec2f(e){return z(e.readFloat32(),e.readFloat32())},vec3f(e){return ut(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return D(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return pr(e.readFloat16(),e.readFloat16())},vec3h(e){return lr(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return dr(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return be(e.readInt32(),e.readInt32())},vec3i(e){return pt(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return C(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return he(e.readUint32(),e.readUint32())},vec3u(e){return lt(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return E(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},mat2x2f(e){return mr(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return gr(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return fr(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},struct(e,t){let r=v(t);h(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))h(e,v(o)),n[a]=V(e,o);return h(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=v(t),n=[];for(let a=0;a<t.elementCount;a++){h(e,r);let o=t.elementType,i=V(e,o);n.push(i)}return h(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return V(e,t.inner)},decorated(e,t){let r=O(t);h(e,r);let n=e.currentByteOffset,a=V(e,t.inner);return e.seekTo(n+b(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>he(e.readUint8(),e.readUint8()),uint8x4:e=>E(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>be(e.readInt8(),e.readInt8()),sint8x4:e=>C(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>z(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>D(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>(e.readUint8()-128)/127,snorm8x2:e=>z((e.readUint8()-128)/127,(e.readUint8()-128)/127),snorm8x4:e=>D((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>he(e.readUint16(),e.readUint16()),uint16x4:e=>E(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>be(e.readInt16(),e.readInt16()),sint16x4:e=>C(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>z(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>D(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>z(ie.snorm16(e),ie.snorm16(e)),snorm16x4:e=>D(ie.snorm16(e),ie.snorm16(e),ie.snorm16(e),ie.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>z(e.readFloat16(),e.readFloat16()),float16x4:e=>D(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>z(e.readFloat32(),e.readFloat32()),float32x3:e=>ut(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>D(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>he(e.readUint32(),e.readUint32()),uint32x3:e=>lt(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>E(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>be(e.readInt32(),e.readInt32()),sint32x3:e=>pt(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>C(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32()),"unorm10-10-10-2"(e){let t=e.readUint32(),r=(t>>22)/1023,n=(t>>12&1023)/1023,a=(t>>2&1023)/1023,o=(t&3)/3;return D(r,n,a,o)},"unorm8x4-bgra"(e){let t=e.readByte()/255,r=e.readByte()/255,n=e.readByte()/255,a=e.readByte()/255;return D(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=V(e,a);return r},disarray(e,t){let r=v(t),n=[];for(let a=0;a<t.elementCount;a++)h(e,r),n.push(V(e,t.elementType));return h(e,r),n},"loose-decorated"(e,t){h(e,O(t));let r=e.currentByteOffset,n=V(e,t.inner);return e.seekTo(r+b(t)),n}};function V(e,t){let r=ie[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as _n}from"typed-binary";import{Measurer as Pn}from"typed-binary";var Er=new WeakMap;function Vr(e){let t=Er.get(e);if(t)return t;let r=new Pn,n={},a;for(let o in e.propTypes){let i=e.propTypes[o];if(i===void 0)throw new Error(`Property ${o} is undefined in struct`);let u=r.size;h(r,me(e)?O(i):v(i)),a&&(a.padding=r.size-u);let l=b(i);n[o]={offset:r.size,size:l},a=n[o],r.add(l)}return a&&(a.padding=W(b(e),v(e))-r.size),Er.set(e,n),n}function Gr(e,t){var s;let r=b(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new _n(n),o=[];function i(m,g,f,w){var y;if(g!=null)if(I(m)||me(m)){let T=Vr(m);for(let[S,c]of Object.entries(T)){let x=m.propTypes[S];if(!x)continue;let pe=g[S];pe!==void 0&&i(x,pe,f+c.offset,(y=c.padding)!=null?y:w)}}else if(Be(m)||sr(m)){let T=m,S=W(b(T.elementType),v(T.elementType));if(!Array.isArray(g))throw new Error("Partial value for array must be an array");let c=g;c.sort((x,pe)=>x.idx-pe.idx);for(let{idx:x,value:pe}of c)i(T.elementType,pe,f+x*S,S-b(T.elementType))}else{let T=b(m);a.seekTo(f),Q(a,m,g),o.push({start:f,end:f+T,padding:w})}}if(i(e,t,0),o.length===0)return[];let u=[],l=o[0];for(let m=1;m<o.length;m++){let g=o[m];if(!g||!l)throw new Error("Internal error: missing segment");g.start===l.end+((s=l.padding)!=null?s:0)?(l.end=g.end,l.padding=g.padding):(u.push({data:new Uint8Array(n,l.start,l.end-l.start)}),l=g)}if(!l)throw new Error("Internal error: missing segment");return u.push({data:new Uint8Array(n,l.start,l.end-l.start)}),u}function se(e){return!!(e!=null&&e.usableAsStorage)}var Ue=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Oe(e){return!!e.usableAsUniform}var Mr={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},ve=class{constructor(t,r){this.usage=t;this.buffer=r;p(this,"~repr");p(this,"resourceType","buffer-usage")}get label(){return this.buffer.label}$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Mr[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}write(t){this.buffer.write(t)}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},$)}},Ae=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;p(this,"~repr");p(this,"resourceType","buffer-usage")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=Mr[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},$)}},kr=new WeakMap;function bt(e){if(!se(e))throw new Error(`Cannot pass ${e} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=kr.get(e);return t||(t=new ve("mutable",e),kr.set(e,t)),t}var Or=new WeakMap;function ht(e){if(!se(e))throw new Error(`Cannot pass ${e} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Or.get(e);return t||(t=new ve("readonly",e),Or.set(e,t)),t}var $r=new WeakMap;function wt(e){if(!Oe(e))throw new Error(`Cannot pass ${e} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`);let t=$r.get(e);return t||(t=new ve("uniform",e),$r.set(e,t)),t}var Dt={uniform:wt,mutable:bt,readonly:ht};function Wr(e,t,r){return de(t)?new $e(e,t,r):new $e(e,t,r,["storage","uniform"])}function X(e){return e.resourceType==="buffer"}function Ln(e){return!!e.usableAsVertex}var $e=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;p(this,"resourceType","buffer");p(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);p(this,"_buffer",null);p(this,"_ownBuffer");p(this,"_destroyed",!1);p(this,"_label");p(this,"initial");p(this,"usableAsUniform",!1);p(this,"usableAsStorage",!1);p(this,"usableAsVertex",!1);yr(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}get label(){return this._label}get buffer(){var r;let t=this._group.device;if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=t.createBuffer({size:b(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:(r=this.label)!=null?r:"<unnamed>"}),this.initial)){let n=new Ft(this._buffer.getMappedRange());Q(n,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(t){return this._label=t,this._buffer&&(this._buffer.label=t),this}$usage(...t){var r;for(let n of t){if((r=this._disallowedUsages)!=null&&r.includes(n))throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${n}`);this.flags|=n==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=n==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=n==="vertex"?GPUBufferUsage.VERTEX:0,this.usableAsUniform=this.usableAsUniform||n==="uniform",this.usableAsStorage=this.usableAsStorage||n==="storage",this.usableAsVertex=this.usableAsVertex||n==="vertex"}return this}$addFlags(t){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return t&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):t&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=t,this)}write(t){let r=this.buffer,n=this._group.device;if(r.mapState==="mapped"){let i=r.getMappedRange();Q(new Ft(i),this.dataType,t);return}let a=b(this.dataType);this._group.flush();let o=new ArrayBuffer(a);Q(new Ft(o),this.dataType,t),n.queue.writeBuffer(r,0,o,0,a)}writePartial(t){let r=this.buffer,n=this._group.device,a=Gr(this.dataType,t);if(r.mapState==="mapped"){let o=r.getMappedRange(),i=new Uint8Array(o);for(let u of a)i.set(u.data,u.data.byteOffset)}else for(let o of a)n.queue.writeBuffer(r,o.data.byteOffset,o.data,0,o.data.byteLength)}copyFrom(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=b(this.dataType);this._group.commandEncoder.copyBufferToBuffer(t.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let t=this.buffer,r=this._group.device;if(t.mapState==="mapped"){let i=t.getMappedRange();return V(new St(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),u=V(new St(i),this.dataType);return t.unmap(),u}let n=r.createBuffer({size:b(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,b(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,b(this.dataType));let o=V(new St(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){var r;return(r=Dt[t])==null?void 0:r.call(Dt,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,this._ownBuffer&&((t=this._buffer)==null||t.destroy()))}toString(){var t;return`buffer:${(t=this._label)!=null?t:"<unnamed>"}`}};function Nr(e){return new Ut(e)}function jr(e){return new vt(e)}function At(e){return(e==null?void 0:e.resourceType)==="sampler"}function Rt(e){return(e==null?void 0:e.resourceType)==="sampler-comparison"}var Me=class{constructor(t){this._membership=t;p(this,"resourceType","sampler")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},We=class{constructor(t){this._membership=t;p(this,"resourceType","sampler-comparison")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},Ut=class{constructor(t){this._props=t;p(this,"resourceType","sampler");p(this,"_label");p(this,"_filtering");p(this,"_sampler",null);this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}unwrap(t){var r;return this._sampler||(this._sampler=t.device.createSampler(R(U({},this._props),{label:(r=this._label)!=null?r:"<unnamed>"}))),this._sampler}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label),{group:n,binding:a}=t.allocateFixedEntry({sampler:this._filtering?"filtering":"non-filtering"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},vt=class{constructor(t){this._props=t;p(this,"resourceType","sampler-comparison");p(this,"_label");p(this,"_sampler",null)}unwrap(t){var r;return this._sampler||(this._sampler=t.device.createSampler(R(U({},this._props),{label:(r=this._label)!=null?r:"<unnamed>"}))),this._sampler}get label(){return this._label}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry({sampler:"comparison"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler_comparison;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};var Ne=class{constructor(t){this._membership=t;p(this,"resourceType","external-texture")}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};var zr={r8unorm:d,r8snorm:d,r8uint:_,r8sint:L,r16uint:_,r16sint:L,r16float:d,rg8unorm:d,rg8snorm:d,rg8uint:_,rg8sint:L,r32uint:_,r32sint:L,r32float:d,rg16uint:_,rg16sint:L,rg16float:d,rgba8unorm:d,"rgba8unorm-srgb":d,rgba8snorm:d,rgba8uint:_,rgba8sint:L,bgra8unorm:d,"bgra8unorm-srgb":d,rgb9e5ufloat:d,rgb10a2uint:_,rgb10a2unorm:d,rg11b10ufloat:d,rg32uint:_,rg32sint:L,rg32float:d,rgba16uint:_,rgba16sint:L,rgba16float:d,rgba32uint:_,rgba32sint:L,rgba32float:d,stencil8:d,depth16unorm:d,depth24plus:d,"depth24plus-stencil8":d,depth32float:d,"depth32float-stencil8":d,"bc1-rgba-unorm":d,"bc1-rgba-unorm-srgb":d,"bc2-rgba-unorm":d,"bc2-rgba-unorm-srgb":d,"bc3-rgba-unorm":d,"bc3-rgba-unorm-srgb":d,"bc4-r-unorm":d,"bc4-r-snorm":d,"bc5-rg-unorm":d,"bc5-rg-snorm":d,"bc6h-rgb-ufloat":d,"bc6h-rgb-float":d,"bc7-rgba-unorm":d,"bc7-rgba-unorm-srgb":d,"etc2-rgb8unorm":d,"etc2-rgb8unorm-srgb":d,"etc2-rgb8a1unorm":d,"etc2-rgb8a1unorm-srgb":d,"etc2-rgba8unorm":d,"etc2-rgba8unorm-srgb":d,"eac-r11unorm":d,"eac-r11snorm":d,"eac-rg11unorm":d,"eac-rg11snorm":d,"astc-4x4-unorm":d,"astc-4x4-unorm-srgb":d,"astc-5x4-unorm":d,"astc-5x4-unorm-srgb":d,"astc-5x5-unorm":d,"astc-5x5-unorm-srgb":d,"astc-6x5-unorm":d,"astc-6x5-unorm-srgb":d,"astc-6x6-unorm":d,"astc-6x6-unorm-srgb":d,"astc-8x5-unorm":d,"astc-8x5-unorm-srgb":d,"astc-8x6-unorm":d,"astc-8x6-unorm-srgb":d,"astc-8x8-unorm":d,"astc-8x8-unorm-srgb":d,"astc-10x5-unorm":d,"astc-10x5-unorm-srgb":d,"astc-10x6-unorm":d,"astc-10x6-unorm-srgb":d,"astc-10x8-unorm":d,"astc-10x8-unorm-srgb":d,"astc-10x10-unorm":d,"astc-10x10-unorm-srgb":d,"astc-12x10-unorm":d,"astc-12x10-unorm-srgb":d,"astc-12x12-unorm":d,"astc-12x12-unorm-srgb":d},Re={rgba8unorm:D,rgba8snorm:D,rgba8uint:E,rgba8sint:C,rgba16uint:E,rgba16sint:C,rgba16float:D,r32uint:E,r32sint:C,r32float:D,rg32uint:E,rg32sint:C,rg32float:D,rgba32uint:E,rgba32sint:C,rgba32float:D,bgra8unorm:D},Kr={f32:"float",u32:"uint",i32:"sint"},qr={float:d,"unfilterable-float":d,uint:_,sint:L,depth:d};function Jr(e,t){return new It(e,t)}function N(e){return(e==null?void 0:e.resourceType)==="texture"}function _t(e){return(e==null?void 0:e.resourceType)==="texture-storage-view"}function Lt(e){return(e==null?void 0:e.resourceType)==="texture-sampled-view"}var Hr={mutable:"read_write",readonly:"read",writeonly:"write"},It=class{constructor(t,r){this.props=t;this._branch=r;p(this,"resourceType","texture");p(this,"usableAsSampled",!1);p(this,"usableAsStorage",!1);p(this,"usableAsRender",!1);p(this,"_destroyed",!1);p(this,"_label");p(this,"_flags",GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC);p(this,"_texture",null)}get label(){return this._label}$name(t){return this._label=t,this}unwrap(){var t,r,n,a,o;if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:(t=this._label)!=null?t:"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:(r=this.props.dimension)!=null?r:"2d",viewFormats:(n=this.props.viewFormats)!=null?n:[],mipLevelCount:(a=this.props.mipLevelCount)!=null?a:1,sampleCount:(o=this.props.sampleCount)!=null?o:1})),this._texture}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||(this.usableAsStorage=r),this.usableAsSampled||(this.usableAsSampled=n),this.usableAsRender||(this.usableAsRender=a),this}createView(t,r){if(t==="sampled")return this._asSampled(r);let n=r;switch(t){case"mutable":return this._asMutable(n);case"readonly":return this._asReadonly(n);case"writeonly":return this._asWriteonly(n)}}_asStorage(t,r){var o;if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=(o=t==null?void 0:t.format)!=null?o:this.props.format,a=Re[n];return ye(!!a,`Unsupported storage texture format: ${n}`),new Bt(t!=null?t:{},r,this)}_asReadonly(t){return this._asStorage(t,"readonly")}_asWriteonly(t){return this._asStorage(t,"writeonly")}_asMutable(t){return this._asStorage(t,"mutable")}_asSampled(t){var a;if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=(a=t==null?void 0:t.format)!=null?a:this.props.format;if(!Re[r])throw new Error(`Unsupported storage texture format: ${r}`);return new Pt(t,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,(t=this._texture)==null||t.destroy())}},Ke={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},Bt=class{constructor(t,r,n){this.access=r;this._texture=n;p(this,"resourceType","texture-storage-view");p(this,"texelDataType");p(this,"dimension");p(this,"_view");p(this,"_format");var a,o,i;this.dimension=(o=(a=t==null?void 0:t.dimension)!=null?a:n.props.dimension)!=null?o:"2d",this._format=(i=t==null?void 0:t.format)!=null?i:n.props.format,this.texelDataType=Re[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view}"~resolve"(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Ke[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${Hr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},je=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;p(this,"resourceType","texture-storage-view");p(this,"texelDataType");this.texelDataType=Re[this._format]}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Ke[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${Hr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},Pt=class{constructor(t,r){this._props=t;this._texture=r;p(this,"resourceType","texture-sampled-view");p(this,"channelDataType");p(this,"dimension");p(this,"_format");p(this,"_view");var n,a,o;this.dimension=(a=(n=t==null?void 0:t.dimension)!=null?n:r.props.dimension)!=null?a:"2d",this._format=(o=t==null?void 0:t.format)!=null?o:r.props.format,this.channelDataType=zr[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView(U({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`},this._props))),this._view}"~resolve"(t){var u;let r=t.names.makeUnique(this.label),n=((u=this._texture.props.sampleCount)!=null?u:1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:Kr[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${Ke[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},ze=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;p(this,"resourceType","texture-sampled-view");p(this,"channelDataType");this.channelDataType=qr[t]}get label(){return this._membership.key}"~resolve"(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Ke[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}};function Ct(e){return!!(e!=null&&e.usableAsSampled)}function Cn(e){return!!(e!=null&&e.usableAsRender)}var qe=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Je(e){return new Vt(e)}function He(e){return!!e&&e.resourceType==="bind-group-layout"}function Gt(e){return!!e&&e.resourceType==="bind-group"}var Et=class e extends Error{constructor(t,r){super(`Bind group '${t!=null?t:"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},Yr=["compute"],Te=["compute","vertex","fragment"],Vt=class{constructor(t){this.entries=t;p(this,"_label");p(this,"_index");p(this,"resourceType","bind-group-layout");p(this,"bound",{});var n,a,o,i,u;let r=0;for(let[l,s]of Object.entries(t)){if(s===null){r++;continue}let m={idx:r,key:l,layout:this};if("uniform"in s&&(this.bound[l]=new Ae("uniform",s.uniform,m)),"storage"in s){let g="type"in s.storage?s.storage:s.storage(0);this.bound[l]=new Ae((n=s.access)!=null?n:"readonly",g,m)}"texture"in s&&(this.bound[l]=new ze(s.texture,(a=s.viewDimension)!=null?a:"2d",(o=s.multisampled)!=null?o:!1,m)),"storageTexture"in s&&(this.bound[l]=new je(s.storageTexture,(i=s.viewDimension)!=null?i:"2d",(u=s.access)!=null?u:"writeonly",m)),"externalTexture"in s&&(this.bound[l]=new Ne(m)),"sampler"in s&&(s.sampler==="comparison"?this.bound[l]=new We(m):this.bound[l]=new Me(m)),r++}}get label(){return this._label}get index(){return this._index}$name(t){return this._label=t,this}$idx(t){return this._index=t,this}unwrap(t){var n;return t.device.createBindGroupLayout({label:(n=this.label)!=null?n:"<unnamed>",entries:Object.values(this.entries).map((a,o)=>{var l,s,m,g;if(a===null)return null;let i=a.visibility,u={binding:o,visibility:0};if("uniform"in a)i=i!=null?i:Te,u.buffer={type:"uniform"};else if("storage"in a)i=i!=null?i:a.access==="mutable"?Yr:Te,u.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)i=i!=null?i:Te,u.sampler={type:a.sampler};else if("texture"in a)i=i!=null?i:Te,u.texture={sampleType:a.texture,viewDimension:(l=a.viewDimension)!=null?l:"2d",multisampled:(s=a.multisampled)!=null?s:!1};else if("storageTexture"in a){let f=(m=a.access)!=null?m:"writeonly";i=i!=null?i:f==="readonly"?Te:Yr,u.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[f],viewDimension:(g=a.viewDimension)!=null?g:"2d"}}else"externalTexture"in a&&(i=i!=null?i:Te,u.externalTexture={});return i!=null&&i.includes("compute")&&(u.visibility|=GPUShaderStage.COMPUTE),i!=null&&i.includes("vertex")&&(u.visibility|=GPUShaderStage.VERTEX),i!=null&&i.includes("fragment")&&(u.visibility|=GPUShaderStage.FRAGMENT),u}).filter(a=>a!==null)})}populate(t){return new ue(this,t)}},ue=class{constructor(t,r){this.layout=t;this.entries=r;p(this,"resourceType","bind-group");for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new Et(t.label,n)}unwrap(t){var n;return t.device.createBindGroup({label:(n=this.layout.label)!=null?n:"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([a,o],i)=>{var l;if(o===null)return null;let u=this.entries[a];if(u===void 0)throw new Error(`'${a}' is a resource required to populate bind group layout '${(l=this.layout.label)!=null?l:"<unnamed>"}'.`);if("uniform"in o){let s;if(X(u)){if(!Oe(u))throw new nt(u);s={buffer:t.unwrap(u)}}else s={buffer:u};return{binding:i,resource:s}}if("storage"in o){let s;if(X(u)){if(!se(u))throw new Ue(u);s={buffer:t.unwrap(u)}}else s={buffer:u};return{binding:i,resource:s}}if("texture"in o){let s;if(N(u)){if(!Ct(u))throw new qe(u);s=t.unwrap(u.createView("sampled"))}else s=u;return{binding:i,resource:s}}if("storageTexture"in o){let s;if(N(u)){if(!se(u))throw new Ue(u);o.access==="readonly"?s=t.unwrap(u.createView("readonly")):o.access==="mutable"?s=t.unwrap(u.createView("mutable")):s=t.unwrap(u.createView("writeonly"))}else s=u;return{binding:i,resource:s}}if("externalTexture"in o||"sampler"in o)return{binding:i,resource:u};throw new Error(`Malformed bind group entry: ${u} (${JSON.stringify(u)})`)}).filter(a=>a!==null)})}};var Qr="#CATCHALL#",Ot=class{constructor(){p(this,"_stack",[]);p(this,"_itemDepth",0)}get itemDepth(){return this._itemDepth}get topItem(){let t=this._stack[this._stack.length-1];if(!t||t.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return t}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}pushSlotBindings(t){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(t)})}pushFunctionScope(t,r,n){this._stack.push({type:"functionScope",args:t,returnType:r,externalMap:n})}pushBlockScope(){this._stack.push({type:"blockScope",declarations:new Map})}popBlockScope(){let t=this._stack.pop();if((t==null?void 0:t.type)!=="blockScope")throw new Error("Expected block scope layer to be on top.")}pop(){let t=this._stack.pop();(t==null?void 0:t.type)==="item"&&this._itemDepth--}readSlot(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="item")n.usedSlots.add(t);else if((n==null?void 0:n.type)==="slotBinding"){let a=n.bindingMap.get(t);if(a!==void 0)return a}else if(!((n==null?void 0:n.type)==="functionScope"||(n==null?void 0:n.type)==="blockScope"))throw new Error("Unknown layer type.")}return t.defaultValue}getResourceById(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="functionScope"){let a=n.args.find(i=>i.value===t);if(a!==void 0)return a;let o=n.externalMap[t];return o!==void 0?{value:o,dataType:P}:void 0}if((n==null?void 0:n.type)==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return{value:t,dataType:a}}}}defineBlockVariable(t,r){for(let n=this._stack.length-1;n>=0;--n){let a=this._stack[n];if((a==null?void 0:a.type)==="blockScope")return a.declarations.set(t,r),{value:t,dataType:r}}throw new Error("No block scope found to define a variable in.")}},Ye=[""," "," "," "," "," "," "," "," "],kt=Ye.length-1,$t=class{constructor(){p(this,"identLevel",0)}get pre(){var t;return(t=Ye[this.identLevel])!=null?t:Ye[kt].repeat(this.identLevel/kt)+Ye[this.identLevel%kt]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Mt=class{constructor(t){p(this,"_memoizedResolves",new WeakMap);p(this,"_memoizedDerived",new WeakMap);p(this,"_indentController",new $t);p(this,"_jitTranspiler");p(this,"_itemStateStack",new Ot);p(this,"_declarations",[]);p(this,"bindGroupLayoutsToPlaceholderMap",new Map);p(this,"_nextFreeLayoutPlaceholderIdx",0);p(this,"fixedBindings",[]);p(this,"callStack",[]);p(this,"names");this.names=t.names,this._jitTranspiler=t.jitTranspiler}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){var r;return(r=this._itemStateStack.getResourceById(t))!=null?r:{value:t,dataType:P}}defineVariable(t,r){return this._itemStateStack.defineBlockVariable(t,r)}pushBlockScope(){this._itemStateStack.pushBlockScope()}popBlockScope(){this._itemStateStack.popBlockScope()}transpileFn(t){if(!this._jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._jitTranspiler.transpileFn(t)}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.returnType,t.externalMap);let r=xt(this,t.body);this._itemStateStack.pop();let n=t.args.map(a=>`${a.value}: ${this.resolve(a.dataType)}`).join(", ");return{head:t.returnType!==void 0?`(${n}) -> ${Ee(t.returnType)} ${this.resolve(t.returnType)}`:`(${n})`,body:r}}addDeclaration(t){this._declarations.push(t)}allocateLayoutEntry(t){let r=this.bindGroupLayoutsToPlaceholderMap,n=r.get(t);return n||(n=`#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`,r.set(t,n)),n}allocateFixedEntry(t,r){let n=this.fixedBindings.length;return this.fixedBindings.push({layoutEntry:t,resource:r}),{group:Qr,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new rt(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.pop()}}unwrap(t){if(Se(t))return this.withSlots(t["~providing"].pairs,()=>this.unwrap(t["~providing"].inner));let r=t;for(;;)if(K(r))r=this.readSlot(r);else if(q(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(t){var n;let r=(n=this._memoizedDerived.get(t))!=null?n:[];this._itemStateStack.pushItem();try{for(let i of r)if([...i.slotToValueMap.entries()].every(([l,s])=>l.areEqual(this._itemStateStack.readSlot(l),s)))return i.result;let a=t["~compute"](),o=new Map;for(let i of this._itemStateStack.topItem.usedSlots)o.set(i,this._itemStateStack.readSlot(i));return r.push({slotToValueMap:o,result:a}),this._memoizedDerived.set(t,r),a}catch(a){throw a instanceof le?a.appendToTrace(t):new le(a,[t])}finally{this._itemStateStack.pop()}}_getOrInstantiate(t){var n;let r=(n=this._memoizedResolves.get(t))!=null?n:[];this._itemStateStack.pushItem();try{for(let i of r)if([...i.slotToValueMap.entries()].every(([l,s])=>l.areEqual(this._itemStateStack.readSlot(l),s)))return i.result;let a;k(t)?a=ct(this,t):q(t)||K(t)?a=this.resolve(this.unwrap(t)):dt(t)?a=t["~resolve"](this):a=this.resolveValue(t);let o=new Map;for(let i of this._itemStateStack.topItem.usedSlots)o.set(i,this._itemStateStack.readSlot(i));return r.push({slotToValueMap:o,result:a}),this._memoizedResolves.set(t,r),a}catch(a){throw a instanceof le?a.appendToTrace(t):new le(a,[t])}finally{this._itemStateStack.pop()}}resolve(t){if(Se(t))return this.withSlots(t["~providing"].pairs,()=>this.resolve(t["~providing"].inner));if(t&&typeof t=="object"||typeof t=="function"){if(this._itemStateStack.itemDepth===0)try{rr(ot.GPU);let r=tr(this,()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
17
19
 
18
- `)}${r}`}return this._getOrInstantiate(t)}return String(t)}resolveValue(t,r){if(ne(t))return this.resolve(t);if(r&&Be(r))return`array(${t.map(n=>this.resolveValue(n,r.elementType))})`;if(Array.isArray(t))return`array(${t.map(n=>this.resolveValue(n))})`;if(r&&B(r))return`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>this.resolveValue(t[n],a))})`;throw new Error(`Value ${t} (as json: ${JSON.stringify(t)}) of schema ${r} is not resolvable to WGSL`)}};function ye(e,t){var g;let r=new Ot(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],i=new Set([...a.keys()].map(f=>f.index).filter(f=>f!==void 0)),p=Ar(i),l=r.fixedBindings.map((f,w)=>[String(w),f.layoutEntry]),s=()=>{let f=p.next().value,w=ze(Object.fromEntries(l));return o[f]=w,n=n.replaceAll(Kr,String(f)),[f,new ue(w,Object.fromEntries(r.fixedBindings.map((c,T)=>[String(T),c.resource])))]},m=l.length>0?s():null;for(let[f,w]of a.entries()){let c=(g=f.index)!=null?g:p.next().value;o[c]=f,n=n.replaceAll(w,String(c))}return{code:n,bindGroupLayouts:o,catchall:m}}function qr(e){let{externals:t,template:r,names:n,unstable_jitTranspiler:a}=e,o={};ae(o,t!=null?t:{});let i={"~resolve"(l){return oe(l,o,r!=null?r:"")},toString:()=>"<root>"},{code:p}=ye(i,{names:n==="strict"?new Q:new Y,jitTranspiler:a});return p}var Re=class{constructor(t){this._make=t;u(this,"_map",new WeakMap)}getOrMake(t,...r){if(this._map.has(t))return this._map.get(t);let n=this._make(t,...r);return this._map.set(t,n),n}};function Jr(e,t,r){return new kt(new $t(e,t,r),{})}function Hr(e){return(e==null?void 0:e.resourceType)==="compute-pipeline"}var kt=class e{constructor(t,r){this._core=t;this._priors=r;u(this,"resourceType","compute-pipeline")}get label(){return this._core.label}get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){var n;return new e(this._core,{bindGroupLayoutMap:new Map([...(n=this._priors.bindGroupLayoutMap)!=null?n:[],[t,r]])})}dispatchWorkgroups(t,r,n){let a=this._core.unwrap(),{branch:o,label:i}=this._core,p=o.commandEncoder.beginComputePass({label:i!=null?i:"<unnamed>"});p.setPipeline(a.pipeline);let l=new Set(a.bindGroupLayouts);if(a.bindGroupLayouts.forEach((s,m)=>{var g;if(a.catchall&&m===a.catchall[0])p.setBindGroup(m,o.unwrap(a.catchall[1])),l.delete(s);else{let f=(g=this._priors.bindGroupLayoutMap)==null?void 0:g.get(s);f!==void 0&&(l.delete(s),p.setBindGroup(m,o.unwrap(f)))}}),l.size>0)throw new ee(l);p.dispatchWorkgroups(t,r,n),p.end()}$name(t){return this._core.label=t,this}},$t=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n;u(this,"label");u(this,"_memo")}unwrap(){var t,r,n,a,o;if(this._memo===void 0){let i=this.branch.device,{code:p,bindGroupLayouts:l,catchall:s}=ye({"~resolve":m=>(m.withSlots(this._slotBindings,()=>{m.resolve(this._entryFn)}),""),toString:()=>{var m;return`computePipeline:${(m=this.label)!=null?m:"<unnamed>"}`}},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});s!==null&&((r=l[s[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`)),this._memo={pipeline:i.createComputePipeline({label:(n=this.label)!=null?n:"<unnamed>",layout:i.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:l.map(m=>this.branch.unwrap(m))}),compute:{module:i.createShaderModule({label:`${(o=this.label)!=null?o:"<unnamed>"} - Shader`,code:p})}}),bindGroupLayouts:l,catchall:s}}return this._memo}};function Nt(e,t="vertex"){return new Wt(e,t)}function He(e){return(e==null?void 0:e.resourceType)==="vertex-layout"}var Mt=Symbol("defaultAttribEntry");function Je(e,t,r,n,a){if(Zt(t)||nr(t)){let o=j(t);return o!==void 0&&(n[a!=null?a:Mt]=o),Je(e,t.inner,M(r,O(t)),n)}if(B(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,p])=>{o=M(o,D(p));let l=[i,Je(e,p,o,n,i)];return o+=x(p),l}))}if(me(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,p])=>{o=M(o,O(p));let l=[i,Je(e,p,o,n,i)];return o+=x(p),l}))}if("type"in t&&typeof t.type=="string"){if(er.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=tr[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var Wt=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;u(this,"resourceType","vertex-layout");u(this,"stride");u(this,"attrib");u(this,"_customLocationMap",{});u(this,"_label");let n=t(0);this.stride=M(x(n.elementType),D(n)),this.attrib=Je(this,n.elementType,0,this._customLocationMap)}get label(){return this._label}get vertexLayout(){if(this._customLocationMap[Mt]!==void 0){if(typeof this.attrib.format!="string"||typeof this.attrib.offset!="number")throw new Error("Single attribute vertex layouts must have a format and offset.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[{format:this.attrib.format,offset:this.attrib.offset,shaderLocation:this._customLocationMap[Mt]}]}}if(!Object.keys(this.attrib).every(r=>this._customLocationMap[r]!==void 0))throw new Error("All attributes must have custom locations in order to unwrap a vertex layout.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[...Object.entries(this.attrib).map(([r,n])=>({format:n.format,offset:n.offset,shaderLocation:this._customLocationMap[r]}))]}}$name(t){return this._label=t,this}};function In(e){return typeof(e==null?void 0:e.loadOp)=="string"}function Yr(e,t){if(z(e)){if(!In(t))throw new Error("Expected a single color attachment, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Rn(e){return typeof(e==null?void 0:e.format)=="string"}function Qr(e,t){if(z(e)){if(!Rn(t))throw new Error("Expected a single color target configuration, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Xr(e){return new jt(new zt(e),{})}function Zr(e){return(e==null?void 0:e.resourceType)==="render-pipeline"}var jt=class e{constructor(t,r){this.core=t;this.priors=r;u(this,"resourceType","render-pipeline")}get label(){return this.core.label}$name(t){return this.core.label=t,this}with(t,r){var n,a;if(Ke(t))return new e(this.core,R(v({},this.priors),{bindGroupLayoutMap:new Map([...(n=this.priors.bindGroupLayoutMap)!=null?n:[],[t,r]])}));if(He(t))return new e(this.core,R(v({},this.priors),{vertexLayoutMap:new Map([...(a=this.priors.vertexLayoutMap)!=null?a:[],[t,r]])}));throw new Error("Unsupported value passed into .with()")}withColorAttachment(t){return new e(this.core,R(v({},this.priors),{colorAttachment:t}))}withDepthStencilAttachment(t){return new e(this.core,R(v({},this.priors),{depthStencilAttachment:t}))}draw(t,r,n,a){var c;let o=this.core.unwrap(),{branch:i,fragmentFn:p}=this.core.options,s={colorAttachments:Yr(p.shell.targets,(c=this.priors.colorAttachment)!=null?c:{}).map(T=>W(T.view)?R(v({},T),{view:i.unwrap(T.view).createView()}):T)};if(this.core.label!==void 0&&(s.label=this.core.label),this.priors.depthStencilAttachment!==void 0){let T=this.priors.depthStencilAttachment;W(T.view)?s.depthStencilAttachment=R(v({},T),{view:i.unwrap(T.view).createView()}):s.depthStencilAttachment=T}let m=i.commandEncoder.beginRenderPass(s);m.setPipeline(o.pipeline);let g=new Set(o.bindGroupLayouts);o.bindGroupLayouts.forEach((T,b)=>{var y;if(o.catchall&&b===o.catchall[0])m.setBindGroup(b,i.unwrap(o.catchall[1])),g.delete(T);else{let S=(y=this.priors.bindGroupLayoutMap)==null?void 0:y.get(T);S!==void 0&&(g.delete(T),m.setBindGroup(b,i.unwrap(S)))}});let f=new Set(this.core.usedVertexLayouts);if(this.core.usedVertexLayouts.forEach((T,b)=>{var S;let y=(S=this.priors.vertexLayoutMap)==null?void 0:S.get(T);y&&(f.delete(T),m.setVertexBuffer(b,i.unwrap(y)))}),g.size>0)throw new ee(g);if(f.size>0)throw new xe(f);m.draw(t,r,n,a),m.end()}},zt=class{constructor(t){this.options=t;u(this,"label");u(this,"usedVertexLayouts");u(this,"_memo");u(this,"_vertexBufferLayouts");u(this,"_targets");let r=vr(t.vertexFn.shell.attributes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=Qr(t.fragmentFn.shell.targets,t.targets)}unwrap(){var t,r,n,a;if(this._memo===void 0){let{branch:o,vertexFn:i,fragmentFn:p,slotBindings:l,primitiveState:s,depthStencilState:m}=this.options,{code:g,bindGroupLayouts:f,catchall:w}=ye({"~resolve":y=>(y.withSlots(l,()=>{y.resolve(i),y.resolve(p)}),""),toString:()=>{var y;return`renderPipeline:${(y=this.label)!=null?y:"<unnamed>"}`}},{names:o.nameRegistry,jitTranspiler:o.jitTranspiler});w!==null&&((r=f[w[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`));let c=o.device,T=c.createShaderModule({label:`${(n=this.label)!=null?n:"<unnamed>"} - Shader`,code:g}),b={layout:c.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:f.map(y=>o.unwrap(y))}),vertex:{module:T,buffers:this._vertexBufferLayouts},fragment:{module:T,targets:this._targets}};this.label!==void 0&&(b.label=this.label),s&&(b.primitive=s),m&&(b.depthStencil=m),this._memo={pipeline:c.createRenderPipeline(b),bindGroupLayouts:f,catchall:w}}return this._memo}};var Kt=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[re(t)?t.slot:t,r]])}withCompute(t){return new qt(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new Jt({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r})}},qt=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return Jr(this._root,this._slotBindings,this._entryFn)}},Jt=class{constructor(t){this._options=t}withFragment(t,r,n){return ce(typeof t!="string","Just type mismatch validation"),ce(typeof r!="string","Just type mismatch validation"),new Ht(R(v({},this._options),{fragmentFn:t,targets:r}))}},Ht=class e{constructor(t){this._options=t}withPrimitive(t){return new e(R(v({},this._options),{primitiveState:t}))}withDepthStencil(t){return new e(R(v({},this._options),{depthStencilState:t}))}createPipeline(){return Xr(this._options)}},Ye=class extends Kt{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;u(this,"~unstable");u(this,"_disposables",[]);u(this,"_unwrappedBindGroupLayouts",new Re(r=>r.unwrap(this)));u(this,"_unwrappedBindGroups",new Re(r=>r.unwrap(this)));u(this,"_commandEncoder",null);this["~unstable"]=this}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=Gr(this,r,n);return this._disposables.push(a),a}createUniform(r,n){return this.createBuffer(r,n).$usage("uniform").as("uniform")}createMutable(r,n){return this.createBuffer(r,n).$usage("storage").as("mutable")}createReadonly(r,n){return this.createBuffer(r,n).$usage("storage").as("readonly")}createBindGroup(r,n){return new ue(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=Nr(r,this);return this._disposables.push(n),n}unwrap(r){if(Hr(r))return r.rawPipeline;if(Zr(r))return r.core.unwrap().pipeline;if(Ke(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(Ct(r))return this._unwrappedBindGroups.getOrMake(r);if(Z(r))return r.buffer;if(W(r)||Rt(r)||Bt(r))return r.unwrap();if(He(r))return r.vertexLayout;if(Dt(r)){if("unwrap"in r)return r.unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if(Ut(r)){if("unwrap"in r)return r.unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,i=new Map,p,l=()=>{if(!p)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:s,priors:m}=p,g=s.unwrap();a.setPipeline(g.pipeline);let f=new Set(g.bindGroupLayouts);g.bindGroupLayouts.forEach((c,T)=>{var b,y;if(g.catchall&&T===g.catchall[0])a.setBindGroup(T,this.unwrap(g.catchall[1])),f.delete(c);else{let S=(y=(b=m.bindGroupLayoutMap)==null?void 0:b.get(c))!=null?y:o.get(c);S!==void 0&&(f.delete(c),Ct(S)?a.setBindGroup(T,this.unwrap(S)):a.setBindGroup(T,S))}});let w=new Set;if(s.usedVertexLayouts.forEach((c,T)=>{var S;let b=(S=m.vertexLayoutMap)==null?void 0:S.get(c),y=b?{buffer:b,offset:void 0,size:void 0}:i.get(c);!y||!y.buffer?w.add(c):Z(y.buffer)?a.setVertexBuffer(T,this.unwrap(y.buffer),y.offset,y.size):a.setVertexBuffer(T,y.buffer,y.offset,y.size)}),f.size>0)throw new ee(f);if(w.size>0)throw new xe(w)};n({setViewport(...s){a.setViewport(...s)},setScissorRect(...s){a.setScissorRect(...s)},setBlendConstant(...s){a.setBlendConstant(...s)},setStencilReference(...s){a.setStencilReference(...s)},beginOcclusionQuery(...s){a.beginOcclusionQuery(...s)},endOcclusionQuery(...s){a.endOcclusionQuery(...s)},executeBundles(...s){a.executeBundles(...s)},setPipeline(s){p=s},setIndexBuffer:(s,m,g,f)=>{Z(s)?a.setIndexBuffer(this.unwrap(s),m,g,f):a.setIndexBuffer(s,m,g,f)},setVertexBuffer(s,m,g,f){i.set(s,{buffer:m,offset:g,size:f})},setBindGroup(s,m){o.set(s,m)},draw(s,m,g,f){l(),a.draw(s,m,g,f)},drawIndexed(...s){l(),a.drawIndexed(...s)},drawIndirect(...s){l(),a.drawIndirect(...s)},drawIndexedIndirect(...s){l(),a.drawIndexedIndirect(...s)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function en(e){let{adapter:t,device:r,unstable_names:n="random",unstable_jitTranspiler:a}=e!=null?e:{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(t);if(!o)throw new Error("Could not find a compatible GPU");return new Ye(await o.requestDevice(r),n==="random"?new Y:new Q,a,!0)}function tn(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e!=null?e:{};return new Ye(t,r==="random"?new Y:new Q,n,!1)}function Qe(e){return new Yt(e)}var Yt=class{constructor(t=void 0){this.defaultValue=t;u(this,"resourceType","slot");u(this,"label");u(this,"~repr")}$name(t){return this.label=t,this}areEqual(t,r){return Object.is(t,r)}toString(){var t;return`slot:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){let t=te();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return Fe(t.unwrap(this))}};function rn(e,t){return new Qt(e,t)}var Qt=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;u(this,"resourceType","accessor");u(this,"~repr");u(this,"label");u(this,"slot");this.slot=Qe(r)}$name(t){return this.label=t,this.slot.$name(t),this}toString(){var t;return`accessor:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!te())throw new Error("Cannot access tgpu.accessor's value outside of resolution.");return new Proxy({"~resolve":r=>r.resolve(this),toString:()=>{var r;return`.value:${(r=this.label)!=null?r:"<unnamed>"}`}},k)}"~resolve"(t){let r=t.unwrap(this.slot);return Le(r)?t.resolve(r):lt(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function nn(e){return Pn(e)}function Bn([e,t]){var r;return`${(r=e.label)!=null?r:"<unnamed>"}=${t}`}function Pn(e){return{resourceType:"derived","~compute":e,"~repr":void 0,get value(){let r=te();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return Fe(r.unwrap(this))},with(r,n){return an(this,[[r,n]])},toString(){return"derived"}}}function an(e,t){return{resourceType:"derived","~repr":void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},"~providing":{inner:e,pairs:t},get value(){let n=te();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return Fe(n.unwrap(this))},with(n,a){return an(e,[...t,[n,a]])},toString(){return`derived[${t.map(Bn).join(", ")}]`}}}function on(e,t){return new Xe("private",e,t)}function sn(e){return new Xe("workgroup",e)}var Xe=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n;u(this,"_label")}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label);return this._initialValue?t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)} = ${t.resolveValue(this._initialValue,this._dataType)};`):t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)};`),r}get label(){return this._label}toString(){var t;return`var:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access tgpu.var's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},k)}};var un={bindGroupLayout:ze,vertexLayout:Nt,init:en,initFromDevice:tn,resolve:qr,"~unstable":{fn:wr,fragmentFn:Fr,vertexFn:Dr,computeFn:hr,vertexLayout:Nt,derived:nn,slot:Qe,accessor:rn,privateVar:on,workgroupVar:sn,const:gr,declare:Tr,sampler:Or,comparisonSampler:kr}},Es=un;Object.assign(un,{__assignAst:xr});export{ee as MissingBindGroupsError,tt as MissingLinksError,Ze as MissingSlotValueError,xe as MissingVertexBuffersError,et as NotUniformError,Y as RandomNameRegistry,le as ResolutionError,Q as StrictNameRegistry,Es as default,Z as isBuffer,Ut as isComparisonSampler,J as isDerived,Bt as isSampledTextureView,Dt as isSampler,q as isSlot,Rt as isStorageTextureView,W as isTexture,lt as isTgpuFn,An as isUsableAsRender,Pt as isUsableAsSampled,se as isUsableAsStorage,Ee as isUsableAsUniform,vn as isUsableAsVertex,un as tgpu,yt as unstable_asMutable,ct as unstable_asReadonly,xt as unstable_asUniform};
20
+ `)}${r}`}finally{nr(ot.GPU)}return this._getOrInstantiate(t)}return String(t)}resolveValue(t,r){if(re(t))return this.resolve(t);if(r&&Be(r))return`array(${t.map(n=>this.resolveValue(n,r.elementType))})`;if(Array.isArray(t))return`array(${t.map(n=>this.resolveValue(n))})`;if(r&&I(r))return`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>this.resolveValue(t[n],a))})`;throw new Error(`Value ${t} (as json: ${JSON.stringify(t)}) of schema ${r} is not resolvable to WGSL`)}};function ce(e,t){var g;let r=new Mt(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],i=new Set([...a.keys()].map(f=>f.index).filter(f=>f!==void 0)),u=_r(i),l=r.fixedBindings.map((f,w)=>[String(w),f.layoutEntry]),s=()=>{let f=u.next().value,w=Je(Object.fromEntries(l));return o[f]=w,n=n.replaceAll(Qr,String(f)),[f,new ue(w,Object.fromEntries(r.fixedBindings.map((y,T)=>[String(T),y.resource])))]},m=l.length>0?s():null;for(let[f,w]of a.entries()){let y=(g=f.index)!=null?g:u.next().value;o[y]=f,n=n.replaceAll(w,String(y))}return{code:n,bindGroupLayouts:o,catchall:m}}function Xr(e){let{externals:t,template:r,names:n,unstable_jitTranspiler:a}=e,o={};ne(o,t!=null?t:{});let i={"~resolve"(l){return ae(l,o,r!=null?r:"")},toString:()=>"<root>"},{code:u}=ce(i,{names:n==="strict"?new Y:new H,jitTranspiler:a});return u}var Ie=class{constructor(t){this._make=t;p(this,"_map",new WeakMap)}getOrMake(t,...r){if(this._map.has(t))return this._map.get(t);let n=this._make(t,...r);return this._map.set(t,n),n}};function Zr(e,t,r){return new Wt(new Nt(e,t,r),{})}function en(e){return(e==null?void 0:e.resourceType)==="compute-pipeline"}var Wt=class e{constructor(t,r){this._core=t;this._priors=r;p(this,"resourceType","compute-pipeline")}get label(){return this._core.label}get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){var n;return new e(this._core,{bindGroupLayoutMap:new Map([...(n=this._priors.bindGroupLayoutMap)!=null?n:[],[t,r]])})}dispatchWorkgroups(t,r,n){let a=this._core.unwrap(),{branch:o,label:i}=this._core,u=o.commandEncoder.beginComputePass({label:i!=null?i:"<unnamed>"});u.setPipeline(a.pipeline);let l=new Set(a.bindGroupLayouts);if(a.bindGroupLayouts.forEach((s,m)=>{var g;if(a.catchall&&m===a.catchall[0])u.setBindGroup(m,o.unwrap(a.catchall[1])),l.delete(s);else{let f=(g=this._priors.bindGroupLayoutMap)==null?void 0:g.get(s);f!==void 0&&(l.delete(s),u.setBindGroup(m,o.unwrap(f)))}}),l.size>0)throw new Z(l);u.dispatchWorkgroups(t,r,n),u.end()}$name(t){return this._core.label=t,this}},Nt=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n;p(this,"label");p(this,"_memo")}unwrap(){var t,r,n,a,o;if(this._memo===void 0){let i=this.branch.device,{code:u,bindGroupLayouts:l,catchall:s}=ce({"~resolve":m=>(m.withSlots(this._slotBindings,()=>{m.resolve(this._entryFn)}),""),toString:()=>{var m;return`computePipeline:${(m=this.label)!=null?m:"<unnamed>"}`}},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});s!==null&&((r=l[s[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`)),this._memo={pipeline:i.createComputePipeline({label:(n=this.label)!=null?n:"<unnamed>",layout:i.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:l.map(m=>this.branch.unwrap(m))}),compute:{module:i.createShaderModule({label:`${(o=this.label)!=null?o:"<unnamed>"} - Shader`,code:u})}}),bindGroupLayouts:l,catchall:s}}return this._memo}};function Kt(e,t="vertex"){return new zt(e,t)}function Xe(e){return(e==null?void 0:e.resourceType)==="vertex-layout"}var jt=Symbol("defaultAttribEntry");function Qe(e,t,r,n,a){if(ar(t)||ur(t)){let o=j(t);return o!==void 0&&(n[a!=null?a:jt]=o),Qe(e,t.inner,W(r,O(t)),n)}if(I(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,u])=>{o=W(o,v(u));let l=[i,Qe(e,u,o,n,i)];return o+=b(u),l}))}if(me(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,u])=>{o=W(o,O(u));let l=[i,Qe(e,u,o,n,i)];return o+=b(u),l}))}if("type"in t&&typeof t.type=="string"){if(or.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=ir[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var zt=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;p(this,"resourceType","vertex-layout");p(this,"stride");p(this,"attrib");p(this,"_customLocationMap",{});p(this,"_label");let n=t(0);this.stride=W(b(n.elementType),v(n)),this.attrib=Qe(this,n.elementType,0,this._customLocationMap)}get label(){return this._label}get vertexLayout(){if(this._customLocationMap[jt]!==void 0){if(typeof this.attrib.format!="string"||typeof this.attrib.offset!="number")throw new Error("Single attribute vertex layouts must have a format and offset.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[{format:this.attrib.format,offset:this.attrib.offset,shaderLocation:this._customLocationMap[jt]}]}}if(!Object.keys(this.attrib).every(r=>this._customLocationMap[r]!==void 0))throw new Error("All attributes must have custom locations in order to unwrap a vertex layout.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[...Object.entries(this.attrib).map(([r,n])=>({format:n.format,offset:n.offset,shaderLocation:this._customLocationMap[r]}))]}}$name(t){return this._label=t,this}};function En(e){return typeof(e==null?void 0:e.loadOp)=="string"}function tn(e,t){if(k(e)){if(!En(t))throw new Error("Expected a single color attachment, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Vn(e){return typeof(e==null?void 0:e.format)=="string"}function rn(e,t){if(k(e)){if(!Vn(t))throw new Error("Expected a single color target configuration, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function nn(e){return new qt(new Jt(e),{})}function an(e){return(e==null?void 0:e.resourceType)==="render-pipeline"}var qt=class e{constructor(t,r){this.core=t;this.priors=r;p(this,"resourceType","render-pipeline")}get label(){return this.core.label}$name(t){return this.core.label=t,this}with(t,r){var n,a;if(He(t))return new e(this.core,R(U({},this.priors),{bindGroupLayoutMap:new Map([...(n=this.priors.bindGroupLayoutMap)!=null?n:[],[t,r]])}));if(Xe(t))return new e(this.core,R(U({},this.priors),{vertexLayoutMap:new Map([...(a=this.priors.vertexLayoutMap)!=null?a:[],[t,r]])}));throw new Error("Unsupported value passed into .with()")}withColorAttachment(t){return new e(this.core,R(U({},this.priors),{colorAttachment:t}))}withDepthStencilAttachment(t){return new e(this.core,R(U({},this.priors),{depthStencilAttachment:t}))}draw(t,r,n,a){var y;let o=this.core.unwrap(),{branch:i,fragmentFn:u}=this.core.options,s={colorAttachments:tn(u.shell.targets,(y=this.priors.colorAttachment)!=null?y:{}).map(T=>N(T.view)?R(U({},T),{view:i.unwrap(T.view).createView()}):T)};if(this.core.label!==void 0&&(s.label=this.core.label),this.priors.depthStencilAttachment!==void 0){let T=this.priors.depthStencilAttachment;N(T.view)?s.depthStencilAttachment=R(U({},T),{view:i.unwrap(T.view).createView()}):s.depthStencilAttachment=T}let m=i.commandEncoder.beginRenderPass(s);m.setPipeline(o.pipeline);let g=new Set(o.bindGroupLayouts);o.bindGroupLayouts.forEach((T,S)=>{var c;if(o.catchall&&S===o.catchall[0])m.setBindGroup(S,i.unwrap(o.catchall[1])),g.delete(T);else{let x=(c=this.priors.bindGroupLayoutMap)==null?void 0:c.get(T);x!==void 0&&(g.delete(T),m.setBindGroup(S,i.unwrap(x)))}});let f=new Set(this.core.usedVertexLayouts);if(this.core.usedVertexLayouts.forEach((T,S)=>{var x;let c=(x=this.priors.vertexLayoutMap)==null?void 0:x.get(T);c&&(f.delete(T),m.setVertexBuffer(S,i.unwrap(c)))}),g.size>0)throw new Z(g);if(f.size>0)throw new xe(f);m.draw(t,r,n,a),m.end()}},Jt=class{constructor(t){this.options=t;p(this,"label");p(this,"usedVertexLayouts");p(this,"_memo");p(this,"_vertexBufferLayouts");p(this,"_targets");let r=Pr(t.vertexFn.shell.attributes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=rn(t.fragmentFn.shell.targets,t.targets)}unwrap(){var t,r,n,a;if(this._memo===void 0){let{branch:o,vertexFn:i,fragmentFn:u,slotBindings:l,primitiveState:s,depthStencilState:m,multisampleState:g}=this.options,{code:f,bindGroupLayouts:w,catchall:y}=ce({"~resolve":x=>(x.withSlots(l,()=>{x.resolve(i),x.resolve(u)}),""),toString:()=>{var x;return`renderPipeline:${(x=this.label)!=null?x:"<unnamed>"}`}},{names:o.nameRegistry,jitTranspiler:o.jitTranspiler});y!==null&&((r=w[y[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`));let T=o.device,S=T.createShaderModule({label:`${(n=this.label)!=null?n:"<unnamed>"} - Shader`,code:f}),c={layout:T.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:w.map(x=>o.unwrap(x))}),vertex:{module:S,buffers:this._vertexBufferLayouts},fragment:{module:S,targets:this._targets}};this.label!==void 0&&(c.label=this.label),s&&(c.primitive=s),m&&(c.depthStencil=m),g&&(c.multisample=g),this._memo={pipeline:T.createRenderPipeline(c),bindGroupLayouts:w,catchall:y}}return this._memo}};var Ht=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[te(t)?t.slot:t,r]])}withCompute(t){return new Yt(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new Qt({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r,multisampleState:void 0})}},Yt=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return Zr(this._root,this._slotBindings,this._entryFn)}},Qt=class{constructor(t){this._options=t}withFragment(t,r,n){return ye(typeof t!="string","Just type mismatch validation"),ye(typeof r!="string","Just type mismatch validation"),new Xt(R(U({},this._options),{fragmentFn:t,targets:r}))}},Xt=class e{constructor(t){this._options=t}withPrimitive(t){return new e(R(U({},this._options),{primitiveState:t}))}withDepthStencil(t){return new e(R(U({},this._options),{depthStencilState:t}))}withMultisample(t){return new e(R(U({},this._options),{multisampleState:t}))}createPipeline(){return nn(this._options)}},Ze=class extends Ht{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;p(this,"~unstable");p(this,"_disposables",[]);p(this,"_unwrappedBindGroupLayouts",new Ie(r=>r.unwrap(this)));p(this,"_unwrappedBindGroups",new Ie(r=>r.unwrap(this)));p(this,"_commandEncoder",null);this["~unstable"]=this}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=Wr(this,r,n);return this._disposables.push(a),a}createUniform(r,n){return this.createBuffer(r,n).$usage("uniform").as("uniform")}createMutable(r,n){return this.createBuffer(r,n).$usage("storage").as("mutable")}createReadonly(r,n){return this.createBuffer(r,n).$usage("storage").as("readonly")}createBindGroup(r,n){return new ue(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=Jr(r,this);return this._disposables.push(n),n}unwrap(r){if(en(r))return r.rawPipeline;if(an(r))return r.core.unwrap().pipeline;if(He(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(Gt(r))return this._unwrappedBindGroups.getOrMake(r);if(X(r))return r.buffer;if(N(r)||_t(r)||Lt(r))return r.unwrap();if(Xe(r))return r.vertexLayout;if(At(r)){if("unwrap"in r)return r.unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if(Rt(r)){if("unwrap"in r)return r.unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,i=new Map,u,l=()=>{if(!u)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:s,priors:m}=u,g=s.unwrap();a.setPipeline(g.pipeline);let f=new Set(g.bindGroupLayouts);g.bindGroupLayouts.forEach((y,T)=>{var S,c;if(g.catchall&&T===g.catchall[0])a.setBindGroup(T,this.unwrap(g.catchall[1])),f.delete(y);else{let x=(c=(S=m.bindGroupLayoutMap)==null?void 0:S.get(y))!=null?c:o.get(y);x!==void 0&&(f.delete(y),Gt(x)?a.setBindGroup(T,this.unwrap(x)):a.setBindGroup(T,x))}});let w=new Set;if(s.usedVertexLayouts.forEach((y,T)=>{var x;let S=(x=m.vertexLayoutMap)==null?void 0:x.get(y),c=S?{buffer:S,offset:void 0,size:void 0}:i.get(y);!c||!c.buffer?w.add(y):X(c.buffer)?a.setVertexBuffer(T,this.unwrap(c.buffer),c.offset,c.size):a.setVertexBuffer(T,c.buffer,c.offset,c.size)}),f.size>0)throw new Z(f);if(w.size>0)throw new xe(w)};n({setViewport(...s){a.setViewport(...s)},setScissorRect(...s){a.setScissorRect(...s)},setBlendConstant(...s){a.setBlendConstant(...s)},setStencilReference(...s){a.setStencilReference(...s)},beginOcclusionQuery(...s){a.beginOcclusionQuery(...s)},endOcclusionQuery(...s){a.endOcclusionQuery(...s)},executeBundles(...s){a.executeBundles(...s)},setPipeline(s){u=s},setIndexBuffer:(s,m,g,f)=>{X(s)?a.setIndexBuffer(this.unwrap(s),m,g,f):a.setIndexBuffer(s,m,g,f)},setVertexBuffer(s,m,g,f){i.set(s,{buffer:m,offset:g,size:f})},setBindGroup(s,m){o.set(s,m)},draw(s,m,g,f){l(),a.draw(s,m,g,f)},drawIndexed(...s){l(),a.drawIndexed(...s)},drawIndirect(...s){l(),a.drawIndirect(...s)},drawIndexedIndirect(...s){l(),a.drawIndexedIndirect(...s)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function on(e){let{adapter:t,device:r,unstable_names:n="random",unstable_jitTranspiler:a}=e!=null?e:{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(t);if(!o)throw new Error("Could not find a compatible GPU");return new Ze(await o.requestDevice(r),n==="random"?new H:new Y,a,!0)}function sn(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e!=null?e:{};return new Ze(t,r==="random"?new H:new Y,n,!1)}function et(e){return new Zt(e)}var Zt=class{constructor(t=void 0){this.defaultValue=t;p(this,"resourceType","slot");p(this,"label");p(this,"~repr")}$name(t){return this.label=t,this}areEqual(t,r){return Object.is(t,r)}toString(){var t;return`slot:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){let t=ee();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return Fe(t.unwrap(this))}};function un(e,t){return new er(e,t)}var er=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;p(this,"resourceType","accessor");p(this,"~repr");p(this,"label");p(this,"slot");this.slot=et(r)}$name(t){return this.label=t,this.slot.$name(t),this}toString(){var t;return`accessor:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!ee())throw new Error("Cannot access tgpu.accessor's value outside of resolution.");return new Proxy({"~resolve":r=>r.resolve(this),toString:()=>{var r;return`.value:${(r=this.label)!=null?r:"<unnamed>"}`}},$)}"~resolve"(t){let r=t.unwrap(this.slot);return Ve(r)?t.resolve(r):ft(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function pn(e){return kn(e)}function Gn([e,t]){var r;return`${(r=e.label)!=null?r:"<unnamed>"}=${t}`}function kn(e){return{resourceType:"derived","~compute":e,"~repr":void 0,get value(){let r=ee();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return Fe(r.unwrap(this))},with(r,n){return ln(this,[[r,n]])},toString(){return"derived"}}}function ln(e,t){return{resourceType:"derived","~repr":void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},"~providing":{inner:e,pairs:t},get value(){let n=ee();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return Fe(n.unwrap(this))},with(n,a){return ln(e,[...t,[n,a]])},toString(){return`derived[${t.map(Gn).join(", ")}]`}}}function dn(e,t){return new tt("private",e,t)}function mn(e){return new tt("workgroup",e)}var tt=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n;p(this,"_label")}$name(t){return this._label=t,this}"~resolve"(t){let r=t.names.makeUnique(this._label);return this._initialValue?t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)} = ${t.resolveValue(this._initialValue,this._dataType)};`):t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)};`),r}get label(){return this._label}toString(){var t;return`var:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access tgpu.var's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>{var t;return`.value:${(t=this.label)!=null?t:"<unnamed>"}`}},$)}};var gn={bindGroupLayout:Je,vertexLayout:Kt,init:on,initFromDevice:sn,resolve:Xr,"~unstable":{fn:vr,fragmentFn:Rr,vertexFn:Ir,computeFn:Ur,vertexLayout:Kt,derived:pn,slot:et,accessor:un,privateVar:dn,workgroupVar:mn,const:xr,declare:hr,sampler:Nr,comparisonSampler:jr}},js=gn;Object.assign(gn,{__assignAst:Fr});export{Z as MissingBindGroupsError,at as MissingLinksError,rt as MissingSlotValueError,xe as MissingVertexBuffersError,nt as NotUniformError,H as RandomNameRegistry,le as ResolutionError,Y as StrictNameRegistry,js as default,X as isBuffer,Rt as isComparisonSampler,q as isDerived,Lt as isSampledTextureView,At as isSampler,K as isSlot,_t as isStorageTextureView,N as isTexture,ft as isTgpuFn,Cn as isUsableAsRender,Ct as isUsableAsSampled,se as isUsableAsStorage,Oe as isUsableAsUniform,Ln as isUsableAsVertex,gn as tgpu,bt as unstable_asMutable,ht as unstable_asReadonly,wt as unstable_asUniform};
19
21
  //# sourceMappingURL=index.js.map