typegpu 0.3.1 → 0.3.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. package/LICENSE.md +1 -1
  2. package/chunk-2CMWQRQC.cjs +2 -0
  3. package/chunk-2CMWQRQC.cjs.map +1 -0
  4. package/chunk-2ZAQFPSX.js +1266 -0
  5. package/chunk-2ZAQFPSX.js.map +1 -0
  6. package/chunk-35UVS2JJ.cjs +591 -0
  7. package/chunk-35UVS2JJ.cjs.map +1 -0
  8. package/chunk-A2QB4MSZ.js +4 -0
  9. package/{chunk-47YH5LQ7.cjs.map → chunk-A2QB4MSZ.js.map} +1 -1
  10. package/chunk-CMYXKKUP.cjs +1266 -0
  11. package/chunk-CMYXKKUP.cjs.map +1 -0
  12. package/chunk-DDEF2Y4S.js +591 -0
  13. package/chunk-DDEF2Y4S.js.map +1 -0
  14. package/chunk-KYBPSQX5.js +2 -0
  15. package/chunk-KYBPSQX5.js.map +1 -0
  16. package/chunk-VRYGOFCW.cjs +4 -0
  17. package/chunk-VRYGOFCW.cjs.map +1 -0
  18. package/data/index.cjs +192 -1
  19. package/data/index.d.cts +2 -2
  20. package/data/index.d.ts +2 -2
  21. package/data/index.js +192 -1
  22. package/{index-CopjPGJg.d.cts → index-CuzbyKXg.d.cts} +5 -3
  23. package/{index-BM7ZTN7E.d.ts → index-FHKuURMs.d.ts} +5 -3
  24. package/index.cjs +4269 -14
  25. package/index.cjs.map +1 -1
  26. package/index.d.cts +80 -11
  27. package/index.d.ts +80 -11
  28. package/index.js +4269 -14
  29. package/index.js.map +1 -1
  30. package/package.json +1 -1
  31. package/std/index.cjs +490 -1
  32. package/std/index.cjs.map +1 -1
  33. package/std/index.d.cts +1 -1
  34. package/std/index.d.ts +1 -1
  35. package/std/index.js +490 -1
  36. package/std/index.js.map +1 -1
  37. package/{vector-BSez01sn.d.cts → vector-CDD2FV2v.d.cts} +19 -3
  38. package/{vector-BSez01sn.d.ts → vector-CDD2FV2v.d.ts} +19 -3
  39. package/chunk-47YH5LQ7.cjs +0 -4
  40. package/chunk-BGPVBIFN.js +0 -4
  41. package/chunk-BGPVBIFN.js.map +0 -1
  42. package/chunk-MCUGRE3S.js +0 -2
  43. package/chunk-MCUGRE3S.js.map +0 -1
  44. package/chunk-OHFPIYFY.cjs +0 -2
  45. package/chunk-OHFPIYFY.cjs.map +0 -1
package/index.js CHANGED
@@ -1,15 +1,4270 @@
1
- import{Aa as Ot,Da as kt,Fa as xe,Ga as $t,a as G,b as Ut,c as R,j as vt,k as ke,l as U,m as _,n as l,na as v,oa as $,p as At,q as ie,qa as b,r as Rt,s as _t,v as It,va as Vt,w as Et,wa as Ct,x as ue,xa as Gt,y as O}from"./chunk-MCUGRE3S.js";import{a as B,b as V,c as i,d as oe,e as X,f as Ge,g as ce,h as Oe,i as se,j as Ft,k as C,l as P,m as k,n as Lt,o as pe,p as le,q as $e,r as Bt,s as We,t as Me,u as x,v as Pt,w as I,x as E}from"./chunk-BGPVBIFN.js";function Wt(e,t){return new Ne(e,t)}var Ne=class{constructor(t,r){this.dataType=t;this._value=r;i(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 P()?this:this._value}};function Mt(e){return!!e&&(typeof e=="object"||typeof e=="function")&&"$name"in e}function Q(e){return(e==null?void 0:e.resourceType)==="slot"}function Z(e){return(e==null?void 0:e.resourceType)==="derived"}function de(e){return(e==null?void 0:e.resourceType)==="accessor"}var S=Symbol("Unknown data type");function je(e){return typeof(e==null?void 0:e["~resolve"])=="function"}function z(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||je(e)||G(e)||Q(e)||Z(e)}function Nt(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function K(e,t){for(let[r,n]of Object.entries(t))e[r]=n,Mt(n)&&(!("label"in n)||n.label===void 0)&&n.$name(r)}function jt(e,t,r){let n=[...e.matchAll(new RegExp(":\\s*(?<arg>.*?)\\s*[,)]","g"))].map(a=>{var o;return(o=a.groups)==null?void 0:o.arg});r(Object.fromEntries(t.flatMap((a,o)=>{let s=n?n[o]:void 0;return R(a)&&s!==void 0?[[s,a]]:[]})))}function ee(e,t,r){var a,o,s;let n=(s=(o=(a=e.match(new RegExp("->(?<output>.*?){","s")))==null?void 0:a.groups)==null?void 0:o.output)==null?void 0:s.trim();R(t)&&n&&!/\s/g.test(n)&&r({[n]:t})}function Gr(e){return new RegExp(`(?<![\\w_.])${e}(?![\\w_])`,"g")}function q(e,t,r){return Object.entries(t).reduce((n,[a,o])=>{var s;return z(o)?n.replaceAll(Gr(a),e.resolve(o)):o!==null&&typeof o=="object"?((s=[...r.matchAll(new RegExp(`${a}\\.(?<prop>.*?)(?![\\w_])`,"g"))].map(d=>{var p;return(p=d==null?void 0:d.groups)==null?void 0:p.prop}))!=null?s:[]).reduce((d,p)=>p&&p in o?q(e,{[`${a}.${p}`]:o[p]},d):d,n):n},r)}function zt(e){return new ze(e)}var ze=class{constructor(t){this.declaration=t;i(this,"externalsToApply",[])}$uses(t){return this.externalsToApply.push(t),this}"~resolve"(t){let r={};for(let a of this.externalsToApply)K(r,a);let n=q(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var Kt=new WeakMap;function qt(e){return Kt.get(e)}function Jt(e,t,r){return Kt.set(e,{ast:t,externals:r}),e}function W(e,t){let r=[];return typeof t=="string"&&(jt(t,e.argTypes,n=>r.push(n)),ee(t,e.returnType,n=>r.push(n))),{label:void 0,applyExternals(n){r.push(n)},resolve(n,a=""){var u;let o={};for(let d of r)K(o,d);let s=n.names.makeUnique(this.label);if(typeof t=="string"){let d=q(n,o,t.trim());n.addDeclaration(`${a}fn ${s}${d}`)}else{let d=qt(t);if(d!=null&&d.externals){let f=Object.fromEntries(Object.entries(d.externals).filter(([h])=>!(h in o)));K(o,f)}let p=(u=d==null?void 0:d.ast)!=null?u:n.transpileFn(String(t)),T=p.externalNames.filter(f=>!(f in o));if(T.length>0)throw new Oe(this.label,T);let g=p.argNames.map((f,h)=>({value:f,dataType:e.argTypes[h]})),{head:m,body:c}=n.fnToWgsl({args:g,returnType:e.returnType,body:p.body,externalMap:o});n.addDeclaration(`${a}fn ${s}${n.resolve(m)}${n.resolve(c)}`)}return s}}}function Yt(e,t){var n,a,o;let{workgroupSize:r}=t;return{argTypes:[],returnType:void 0,workgroupSize:[(n=r[0])!=null?n:1,(a=r[1])!=null?a:1,(o=r[2])!=null?o:1],does(s){return Or(this,r,s)}}}function Or(e,t,r){let n=W(e,r);return{shell:e,get label(){return n.label},$uses(a){return n.applyExternals(a),this},$name(a){return n.label=a,this},"~resolve"(a){return n.resolve(a,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){var a;return`computeFn:${(a=this.label)!=null?a:"<unnamed>"}`}}}function Ht(e,t){return{argTypes:e,returnType:t,does(r){return kr(this,r)}}}function Ke(e){return(e==null?void 0:e.resourceType)==="function"}function kr(e,t){let r=W(e,t),o=Object.assign((...s)=>{if(P())return new be(o,s);if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...s)},{shell:e,resourceType:"function",$uses(s){return r.applyExternals(s),this},$name(s){return r.label=s,this},with(s,u){return Xt(o,de(s)?s.slot:s,u)},"~resolve"(s){return r.resolve(s)}});return Object.defineProperty(o,"label",{get:()=>r.label}),Object.defineProperty(o,"toString",{value:()=>{var s;return`fn:${(s=r.label)!=null?s:"<unnamed>"}`}}),o}function Xt(e,t,r){let n={resourceType:"function",shell:e.shell,$uses(s){return e.$uses(s),this},$name(s){return e.$name(s),this},with(s,u){return Xt(o,de(s)?s.slot:s,u)},"~resolve"(s){return s.withSlots([[t,r]],()=>s.resolve(e))}},o=Object.assign((...s)=>P()?new be(o,s):e(...s),n);return Object.defineProperty(o,"label",{get:()=>e.label}),Object.defineProperty(o,"toString",{value(){var s,u;return`fn:${(s=e.label)!=null?s:"<unnamed>"}[${(u=t.label)!=null?u:"<unnamed>"}=${r}]`}}),o}var be=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 $r(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(xe(n))return[r,n];let a=ue(n);return a!==void 0?(t=a+1,[r,n]):[r,Ot(n,{type:"@location",value:t++})]}))}function he(e){return O(e)?kt(0,e):At($r(e))}function Qt(e,t){return{argTypes:[e],returnType:t,does(r){return Wr(this,r)}}}function Wr(e,t){let r=W(e,t),n=he(e.returnType);return typeof t=="string"&&ee(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,get label(){return r.label},$uses(o){return r.applyExternals(o),this},$name(o){return r.label=o,R(n)&&n.$name(`${o}_Output`),this},"~resolve"(o){return r.resolve(o,"@fragment ")},toString(){var o;return`fragmentFn:${(o=this.label)!=null?o:"<unnamed>"}`}}}function Zt(e,t){return{argTypes:[e],returnType:t,does(r){return Mr(this,r)}}}function Mr(e,t){let r=W(e,t),n=he(e.returnType);return typeof t=="string"&&ee(t,n,a=>r.applyExternals(a)),{shell:e,outputType:n,get label(){return r.label},$uses(a){return r.applyExternals(a),this},$name(a){return r.label=a,R(n)&&n.$name(`${a}_Output`),this},"~resolve"(a){return r.resolve(a,"@vertex ")},toString(){var a;return`vertexFn:${(a=this.label)!=null?a:"<unnamed>"}`}}}var M=class{constructor(){i(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++}`}},N=class{constructor(){i(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 er(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var Nr=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2f","mat3x3f","mat4x4f"];function jr(e){return Nr.includes(e.type)}function zr(e,[t,r]){return` ${$t(r)}${t}: ${e.resolve(r)},
2
- `}function Kr(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
3
- struct ${r} {
4
- ${Object.entries(t.propTypes).map(n=>zr(e,n)).join("")}}
5
- `),r}function qr(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function qe(e,t){if(jr(t))return t.type;if(t.type==="struct")return Kr(e,t);if(t.type==="array")return qr(e,t);if(t.type==="atomic")return`atomic<${qe(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);er(t,"resolveData")}function*tr(e){let t=0;for(;;)e.has(t)||(yield t),t++}var Jr=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"];function w(e,t){return z(t.value)||G(t.value)?e.resolve(t.value):String(t.value)}function Yr(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function rr(e,t){return t?{value:"true",dataType:ke}:{value:"false",dataType:ke}}function nr(e,t){return`${e.indent()}{
6
- ${t.b.map(r=>Ye(e,r)).join(`
7
- `)}
8
- ${e.dedent()}}`}function Je(e,t){return e.getById(t)}function F(e,t){if(typeof t=="string")return Je(e,t);if(typeof t=="boolean")return rr(e,t);if("x"in t){let[r,n,a]=t.x,o=w(e,F(e,r)),s=w(e,F(e,a));return{value:Jr.includes(n)?`(${o} ${n} ${s})`:`${o} ${n} ${s}`,dataType:S}}if("u"in t){let[r,n]=t.u,a=w(e,F(e,n));return{value:`${r}${a}`,dataType:S}}if("a"in t){let[r,n]=t.a,a=F(e,r),o=w(e,F(e,n));if(typeof a.value=="string")return{value:`${a.value}.${o}`,dataType:S};if(z(a.value))return o==="value"?{value:w(e,a),dataType:S}:{value:a.value[o],dataType:S};if(typeof a.value=="object")return{value:a.value[o],dataType:S};throw new Error(`Cannot access member ${o} of ${a.value}`)}if("i"in t){let[r,n]=t.i,a=w(e,F(e,r)),o=w(e,F(e,n));return{value:`${a}[${o}]`,dataType:S}}if("n"in t)return{value:t.n,dataType:S};if("f"in t){let[r,n]=t.f,o=F(e,r).value,u=n.map(p=>F(e,p)).map(p=>w(e,p));return typeof o=="string"?{value:`${o}(${u.join(", ")})`,dataType:S}:{value:o(...u),dataType:S}}Yr(t)}function Ye(e,t){if(typeof t=="string")return`${e.pre}${w(e,Je(e,t))};`;if(typeof t=="boolean")return`${e.pre}${w(e,rr(e,t))};`;if("r"in t)return t.r===null?`${e.pre}return;`:`${e.pre}return ${w(e,F(e,t.r))};`;if("q"in t){let[r,n,a]=t.q,o=w(e,F(e,r));e.indent();let s=Ye(e,n);e.dedent(),e.indent();let u=a?Ye(e,a):void 0;return e.dedent(),u?`${e.pre}if (${o})
9
- ${s}
10
- ${e.pre}else
11
- ${u}`:`${e.pre}if (${o})
12
- ${s}`}if("l"in t||"c"in t){let[r,n]="l"in t?t.l:t.c,a=w(e,Je(e,r)),o=n?F(e,n):void 0;if(!o)throw new Error("Cannot create variable without an initial value.");return`${e.pre}var ${a} = ${w(e,o)};`}return"b"in t?nr(e,t):`${e.pre}${w(e,F(e,t))};`}function He(e,t){return nr(e,t)}import{BufferReader as Xe,BufferWriter as Qe}from"typed-binary";function Hr(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 y=Hr;var D={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);y(e,n);for(let[a,o]of Object.entries(t.propTypes))y(e,v(o)),te(e,o,r[a]);y(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=v(t);y(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)y(e,n),te(e,t.elementType,r[o]);e.seekTo(a+b(t))},atomic(e,t,r){var n;(n=D[t.inner.type])==null||n.call(D,e,t,r)},decorated(e,t,r){var o,s;let n=$(t);y(e,n);let a=e.currentByteOffset;(s=D[(o=t.inner)==null?void 0:o.type])==null||s.call(D,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,s;let n=v(t);y(e,n);let a=e.currentByteOffset;for(let u=0;u<Math.min(t.elementCount,r.length);u++)y(e,n),(s=D[(o=t.elementType)==null?void 0:o.type])==null||s.call(D,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=D[o.type])==null||n.call(D,e,o,r[a])},"loose-decorated"(e,t,r){var s;let n=$(t);y(e,n);let a=e.currentByteOffset,o=D[(s=t.inner)==null?void 0:s.type];return o==null||o(e,t.inner,r),e.seekTo(a+b(t)),r}};function te(e,t,r){let n=D[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var J={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 $e(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return x(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Lt(e.readFloat16(),e.readFloat16())},vec3h(e){return Bt(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return Pt(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return pe(e.readInt32(),e.readInt32())},vec3i(e){return We(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return I(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return le(e.readUint32(),e.readUint32())},vec3u(e){return Me(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return E(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},mat2x2f(e){return Vt(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return Ct(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return Gt(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);y(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))y(e,v(o)),n[a]=L(e,o);return y(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++){y(e,r);let o=t.elementType,s=L(e,o);n.push(s)}return y(e,r),n},atomic(e,t){return L(e,t.inner)},decorated(e,t){let r=$(t);y(e,r);let n=e.currentByteOffset,a=L(e,t.inner);return e.seekTo(n+b(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>le(e.readUint8(),e.readUint8()),uint8x4:e=>E(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>pe(e.readInt8(),e.readInt8()),sint8x4:e=>I(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>k(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>x(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=>x((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>le(e.readUint16(),e.readUint16()),uint16x4:e=>E(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>pe(e.readInt16(),e.readInt16()),sint16x4:e=>I(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>k(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>x(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>k(J.snorm16(e),J.snorm16(e)),snorm16x4:e=>x(J.snorm16(e),J.snorm16(e),J.snorm16(e),J.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>k(e.readFloat16(),e.readFloat16()),float16x4:e=>x(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>k(e.readFloat32(),e.readFloat32()),float32x3:e=>$e(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>x(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>le(e.readUint32(),e.readUint32()),uint32x3:e=>Me(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>E(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>pe(e.readInt32(),e.readInt32()),sint32x3:e=>We(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>I(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 x(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 x(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=L(e,a);return r},disarray(e,t){let r=v(t),n=[];for(let a=0;a<t.elementCount;a++)y(e,r),n.push(L(e,t.elementType));return y(e,r),n},"loose-decorated"(e,t){y(e,$(t));let r=e.currentByteOffset,n=L(e,t.inner);return e.seekTo(r+b(t)),n}};function L(e,t){let r=J[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}function ar(e,t,r){return G(t)?new we(e,t,r):new we(e,t,r,["storage","uniform"])}function re(e){return e.resourceType==="buffer"}function me(e){return!!e.usableAsUniform}function Xr(e){return!!e.usableAsVertex}var we=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;i(this,"resourceType","buffer");i(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);i(this,"_buffer",null);i(this,"_ownBuffer");i(this,"_destroyed",!1);i(this,"_label");i(this,"initial");i(this,"usableAsUniform",!1);i(this,"usableAsStorage",!1);i(this,"usableAsVertex",!1);Nt(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 Qe(this._buffer.getMappedRange());te(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} 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 s=r.getMappedRange();te(new Qe(s),this.dataType,t);return}let a=b(this.dataType);this._group.flush();let o=new ArrayBuffer(a);te(new Qe(o),this.dataType,t),n.queue.writeBuffer(r,0,o,0,a)}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 s=t.getMappedRange();return L(new Xe(s),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let s=t.getMappedRange(),u=L(new Xe(s),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=L(new Xe(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}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 Y(e){return!!(e!=null&&e.usableAsStorage)}var Se=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 ur(e){return(e==null?void 0:e.resourceType)==="buffer-usage"}var pr={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Te=class{constructor(t,r){this.usage=t;this.buffer=r;i(this,"~repr");i(this,"resourceType","buffer-usage")}get label(){return this.buffer.label}$name(t){this.buffer.$name(t)}"~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=pr[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!P())throw new Error("Cannot access buffer's value directly in JS.");return this}},ge=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;i(this,"~repr");i(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=pr[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(!P())throw new Error("Cannot access buffer's value directly in JS.");return this}},or=new WeakMap;function Qr(e){if(!Y(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=or.get(e);return t||(t=new Te("mutable",e),or.set(e,t)),t}var sr=new WeakMap;function Zr(e){if(!Y(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=sr.get(e);return t||(t=new Te("readonly",e),sr.set(e,t)),t}var ir=new WeakMap;function en(e){if(!me(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=ir.get(e);return t||(t=new Te("uniform",e),ir.set(e,t)),t}function lr(e){return new Ze(e)}function dr(e){return new et(e)}function tn(e){return(e==null?void 0:e.resourceType)==="sampler"}function rn(e){return(e==null?void 0:e.resourceType)==="sampler-comparison"}var De=class{constructor(t){this._membership=t;i(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>"}`}},Fe=class{constructor(t){this._membership=t;i(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>"}`}},Ze=class{constructor(t){this._props=t;i(this,"resourceType","sampler");i(this,"_label");i(this,"_filtering");this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}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>"}`}},et=class{constructor(t){this._props=t;i(this,"resourceType","sampler-comparison");i(this,"_label")}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 Ue=class{constructor(t){this._membership=t;i(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 mr={r8unorm:l,r8snorm:l,r8uint:U,r8sint:_,r16uint:U,r16sint:_,r16float:l,rg8unorm:l,rg8snorm:l,rg8uint:U,rg8sint:_,r32uint:U,r32sint:_,r32float:l,rg16uint:U,rg16sint:_,rg16float:l,rgba8unorm:l,"rgba8unorm-srgb":l,rgba8snorm:l,rgba8uint:U,rgba8sint:_,bgra8unorm:l,"bgra8unorm-srgb":l,rgb9e5ufloat:l,rgb10a2uint:U,rgb10a2unorm:l,rg11b10ufloat:l,rg32uint:U,rg32sint:_,rg32float:l,rgba16uint:U,rgba16sint:_,rgba16float:l,rgba32uint:U,rgba32sint:_,rgba32float:l,stencil8:l,depth16unorm:l,depth24plus:l,"depth24plus-stencil8":l,depth32float:l,"depth32float-stencil8":l,"bc1-rgba-unorm":l,"bc1-rgba-unorm-srgb":l,"bc2-rgba-unorm":l,"bc2-rgba-unorm-srgb":l,"bc3-rgba-unorm":l,"bc3-rgba-unorm-srgb":l,"bc4-r-unorm":l,"bc4-r-snorm":l,"bc5-rg-unorm":l,"bc5-rg-snorm":l,"bc6h-rgb-ufloat":l,"bc6h-rgb-float":l,"bc7-rgba-unorm":l,"bc7-rgba-unorm-srgb":l,"etc2-rgb8unorm":l,"etc2-rgb8unorm-srgb":l,"etc2-rgb8a1unorm":l,"etc2-rgb8a1unorm-srgb":l,"etc2-rgba8unorm":l,"etc2-rgba8unorm-srgb":l,"eac-r11unorm":l,"eac-r11snorm":l,"eac-rg11unorm":l,"eac-rg11snorm":l,"astc-4x4-unorm":l,"astc-4x4-unorm-srgb":l,"astc-5x4-unorm":l,"astc-5x4-unorm-srgb":l,"astc-5x5-unorm":l,"astc-5x5-unorm-srgb":l,"astc-6x5-unorm":l,"astc-6x5-unorm-srgb":l,"astc-6x6-unorm":l,"astc-6x6-unorm-srgb":l,"astc-8x5-unorm":l,"astc-8x5-unorm-srgb":l,"astc-8x6-unorm":l,"astc-8x6-unorm-srgb":l,"astc-8x8-unorm":l,"astc-8x8-unorm-srgb":l,"astc-10x5-unorm":l,"astc-10x5-unorm-srgb":l,"astc-10x6-unorm":l,"astc-10x6-unorm-srgb":l,"astc-10x8-unorm":l,"astc-10x8-unorm-srgb":l,"astc-10x10-unorm":l,"astc-10x10-unorm-srgb":l,"astc-12x10-unorm":l,"astc-12x10-unorm-srgb":l,"astc-12x12-unorm":l,"astc-12x12-unorm-srgb":l},fe={rgba8unorm:x,rgba8snorm:x,rgba8uint:E,rgba8sint:I,rgba16uint:E,rgba16sint:I,rgba16float:x,r32uint:E,r32sint:I,r32float:x,rg32uint:E,rg32sint:I,rg32float:x,rgba32uint:E,rgba32sint:I,rgba32float:x,bgra8unorm:x},Tr={f32:"float",u32:"uint",i32:"sint"},gr={float:l,"unfilterable-float":l,uint:U,sint:_,depth:l};function fr(e,t){return new tt(e,t)}function j(e){return(e==null?void 0:e.resourceType)==="texture"}function at(e){return(e==null?void 0:e.resourceType)==="texture-storage-view"}function ot(e){return(e==null?void 0:e.resourceType)==="texture-sampled-view"}var yr={mutable:"read_write",readonly:"read",writeonly:"write"},tt=class{constructor(t,r){this.props=t;this._branch=r;i(this,"resourceType","texture");i(this,"usableAsSampled",!1);i(this,"usableAsStorage",!1);i(this,"usableAsRender",!1);i(this,"_destroyed",!1);i(this,"_label");i(this,"_flags",GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC);i(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=fe[n];return oe(!!a,`Unsupported storage texture format: ${n}`),new rt(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(!fe[r])throw new Error(`Unsupported storage texture format: ${r}`);return new nt(t,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,(t=this._texture)==null||t.destroy())}},Re={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},rt=class{constructor(t,r,n){this.access=r;this._texture=n;i(this,"resourceType","texture-storage-view");i(this,"texelDataType");i(this,"dimension");i(this,"_view");i(this,"_format");var a,o,s;this.dimension=(o=(a=t==null?void 0:t.dimension)!=null?a:n.props.dimension)!=null?o:"2d",this._format=(s=t==null?void 0:t.format)!=null?s:n.props.format,this.texelDataType=fe[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_${Re[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${yr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},ve=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;i(this,"resourceType","texture-storage-view");i(this,"texelDataType");this.texelDataType=fe[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_${Re[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${yr[this.access]}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},nt=class{constructor(t,r){this._props=t;this._texture=r;i(this,"resourceType","texture-sampled-view");i(this,"channelDataType");i(this,"dimension");i(this,"_format");i(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=mr[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(B({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:Tr[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),s=n?"texture_multisampled_2d":`texture_${Re[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${s}<${t.resolve(this.channelDataType)}>;`),r}toString(){var t;return`${this.resourceType}:${(t=this.label)!=null?t:"<unnamed>"}`}},Ae=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;i(this,"resourceType","texture-sampled-view");i(this,"channelDataType");this.channelDataType=gr[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_${Re[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 st(e){return!!(e!=null&&e.usableAsSampled)}function nn(e){return!!(e!=null&&e.usableAsRender)}var _e=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 Ie(e){return new ut(e)}function Ee(e){return!!e&&e.resourceType==="bind-group-layout"}function xr(e){return!!e&&e.resourceType==="bind-group"}var it=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)}},cr=["compute"],ne=["compute","vertex","fragment"],ut=class{constructor(t){this.entries=t;i(this,"_label");i(this,"_index");i(this,"resourceType","bind-group-layout");i(this,"bound",{});var n,a,o,s,u;let r=0;for(let[d,p]of Object.entries(t)){if(p===null){r++;continue}let T={idx:r,key:d,layout:this};if("uniform"in p&&(this.bound[d]=new ge("uniform",p.uniform,T)),"storage"in p){let g="type"in p.storage?p.storage:p.storage(0);this.bound[d]=new ge((n=p.access)!=null?n:"readonly",g,T)}"texture"in p&&(this.bound[d]=new Ae(p.texture,(a=p.viewDimension)!=null?a:"2d",(o=p.multisampled)!=null?o:!1,T)),"storageTexture"in p&&(this.bound[d]=new ve(p.storageTexture,(s=p.viewDimension)!=null?s:"2d",(u=p.access)!=null?u:"writeonly",T)),"externalTexture"in p&&(this.bound[d]=new Ue(T)),"sampler"in p&&(p.sampler==="comparison"?this.bound[d]=new Fe(T):this.bound[d]=new De(T)),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 d,p,T,g;if(a===null)return null;let s=a.visibility,u={binding:o,visibility:0};if("uniform"in a)s=s!=null?s:ne,u.buffer={type:"uniform"};else if("storage"in a)s=s!=null?s:a.access==="mutable"?cr:ne,u.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)s=s!=null?s:ne,u.sampler={type:a.sampler};else if("texture"in a)s=s!=null?s:ne,u.texture={sampleType:a.texture,viewDimension:(d=a.viewDimension)!=null?d:"2d",multisampled:(p=a.multisampled)!=null?p:!1};else if("storageTexture"in a){let m=(T=a.access)!=null?T:"writeonly";s=s!=null?s:m==="readonly"?ne:cr,u.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[m],viewDimension:(g=a.viewDimension)!=null?g:"2d"}}else"externalTexture"in a&&(s=s!=null?s:ne,u.externalTexture={});return s!=null&&s.includes("compute")&&(u.visibility|=GPUShaderStage.COMPUTE),s!=null&&s.includes("vertex")&&(u.visibility|=GPUShaderStage.VERTEX),s!=null&&s.includes("fragment")&&(u.visibility|=GPUShaderStage.FRAGMENT),u}).filter(a=>a!==null)})}populate(t){return new H(this,t)}},H=class{constructor(t,r){this.layout=t;this.entries=r;i(this,"resourceType","bind-group");for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new it(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],s)=>{var d;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 '${(d=this.layout.label)!=null?d:"<unnamed>"}'.`);if("uniform"in o){let p;if(re(u)){if(!me(u))throw new ce(u);p={buffer:t.unwrap(u)}}else p={buffer:u};return{binding:s,resource:p}}if("storage"in o){let p;if(re(u)){if(!Y(u))throw new ce(u);p={buffer:t.unwrap(u)}}else p={buffer:u};return{binding:s,resource:p}}if("texture"in o){let p;if(j(u)){if(!st(u))throw new _e(u);p=t.unwrap(u.createView("sampled"))}else p=u;return{binding:s,resource:p}}if("storageTexture"in o){let p;if(j(u)){if(!Y(u))throw new Se(u);o.access==="readonly"?p=t.unwrap(u.createView("readonly")):o.access==="mutable"?p=t.unwrap(u.createView("mutable")):p=t.unwrap(u.createView("writeonly"))}else p=u;return{binding:s,resource:p}}if("externalTexture"in o||"sampler"in o)return{binding:s,resource:u};throw new Error(`Malformed bind group entry: ${u} (${JSON.stringify(u)})`)}).filter(a=>a!==null)})}};var br="#CATCHALL#",lt=class{constructor(){i(this,"_stack",[]);i(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(s=>s.value===t);if(a!==void 0)return a;let o=n.externalMap[t];return o!==void 0?{value:o,dataType:S}: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}}}}},Le=[""," "," "," "," "," "," "," "," "],pt=Le.length-1,dt=class{constructor(){i(this,"identLevel",0)}get pre(){var t;return(t=Le[this.identLevel])!=null?t:Le[pt].repeat(this.identLevel/pt)+Le[this.identLevel%pt]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},mt=class{constructor(t){i(this,"_memoizedResolves",new WeakMap);i(this,"_memoizedDerived",new WeakMap);i(this,"_indentController",new dt);i(this,"_jitTranspiler");i(this,"_itemStateStack",new lt);i(this,"_declarations",[]);i(this,"bindGroupLayoutsToPlaceholderMap",new Map);i(this,"_nextFreeLayoutPlaceholderIdx",0);i(this,"fixedBindings",[]);i(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:S}}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=He(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}) -> ${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:br,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new Ge(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.pop()}}unwrap(t){let r=t;for(;;)if(Q(r))r=this.readSlot(r);else if(Z(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 s of r)if([...s.slotToValueMap.entries()].every(([d,p])=>d.areEqual(this._itemStateStack.readSlot(d),p)))return s.result;let a=t["~compute"](),o=new Map;for(let s of this._itemStateStack.topItem.usedSlots)o.set(s,this._itemStateStack.readSlot(s));return r.push({slotToValueMap:o,result:a}),this._memoizedDerived.set(t,r),a}catch(a){throw a instanceof X?a.appendToTrace(t):new X(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 s of r)if([...s.slotToValueMap.entries()].every(([d,p])=>d.areEqual(this._itemStateStack.readSlot(d),p)))return s.result;let a;G(t)?a=qe(this,t):Z(t)||Q(t)?a=this.resolve(t):je(t)?a=t["~resolve"](this):a=this.resolveValue(t);let o=new Map;for(let s of this._itemStateStack.topItem.usedSlots)o.set(s,this._itemStateStack.readSlot(s));return r.push({slotToValueMap:o,result:a}),this._memoizedResolves.set(t,r),a}catch(a){throw a instanceof X?a.appendToTrace(t):new X(a,[t])}finally{this._itemStateStack.pop()}}resolve(t){let r=this.unwrap(t);if(r&&typeof r=="object"||typeof r=="function"){if(this._itemStateStack.itemDepth===0){let n=Ft(this,()=>this._getOrInstantiate(r));return`${[...this._declarations].join(`
13
-
14
- `)}${n}`}return this._getOrInstantiate(r)}return String(r)}resolveValue(t,r){if(z(t))return this.resolve(t);if(r&&Ut(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&&R(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 ae(e,t){var g;let r=new mt(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],s=new Set([...a.keys()].map(m=>m.index).filter(m=>m!==void 0)),u=tr(s),d=r.fixedBindings.map((m,c)=>[String(c),m.layoutEntry]),p=()=>{let m=u.next().value,c=Ie(Object.fromEntries(d));return o[m]=c,n=n.replaceAll(br,String(m)),[m,new H(c,Object.fromEntries(r.fixedBindings.map((f,h)=>[String(h),f.resource])))]},T=d.length>0?p():null;for(let[m,c]of a.entries()){let f=(g=m.index)!=null?g:u.next().value;o[f]=m,n=n.replaceAll(c,String(f))}return{code:n,bindGroupLayouts:o,catchall:T}}function hr(e){let{externals:t,template:r,names:n,unstable_jitTranspiler:a}=e,o={};K(o,t!=null?t:{});let s={"~resolve"(d){return q(d,o,r!=null?r:"")},toString:()=>"<root>"},{code:u}=ae(s,{names:n==="strict"?new N:new M,jitTranspiler:a});return u}var ye=class{constructor(t){this._make=t;i(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 wr(e,t,r){return new Tt(new gt(e,t,r),{})}function Sr(e){return(e==null?void 0:e.resourceType)==="compute-pipeline"}var Tt=class e{constructor(t,r){this._core=t;this._priors=r;i(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){var s;let a=this._core.unwrap(),o=this._core.branch.commandEncoder.beginComputePass({label:(s=this._core.label)!=null?s:"<unnamed>"});o.setPipeline(a.pipeline),a.bindGroupLayouts.forEach((u,d)=>{var p;if(a.catchall&&d===a.catchall[0])o.setBindGroup(d,this._core.branch.unwrap(a.catchall[1]));else{let T=(p=this._priors.bindGroupLayoutMap)==null?void 0:p.get(u);if(T===void 0)throw new se(u.label);o.setBindGroup(d,this._core.branch.unwrap(T))}}),o.dispatchWorkgroups(t,r,n),o.end()}$name(t){return this._core.label=t,this}},gt=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n;i(this,"label");i(this,"_memo")}unwrap(){var t,r,n,a,o;if(this._memo===void 0){let s=this.branch.device,{code:u,bindGroupLayouts:d,catchall:p}=ae({"~resolve":T=>(T.withSlots(this._slotBindings,()=>{T.resolve(this._entryFn)}),""),toString:()=>{var T;return`computePipeline:${(T=this.label)!=null?T:"<unnamed>"}`}},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});p!==null&&((r=d[p[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`)),this._memo={pipeline:s.createComputePipeline({label:(n=this.label)!=null?n:"<unnamed>",layout:s.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:d.map(T=>this.branch.unwrap(T))}),compute:{module:s.createShaderModule({label:`${(o=this.label)!=null?o:"<unnamed>"} - Shader`,code:u})}}),bindGroupLayouts:d,catchall:p}}return this._memo}};function an(e){return typeof(e==null?void 0:e.format)=="string"}function Dr(e,t){var s,u;let r=[];if(O(e)){if(!an(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:(s=ue(e))!=null?s:0}]}]}}let n=[],a=new WeakMap,o=0;for(let[d,p]of Object.entries(e)){if(xe(p))continue;let T=t[d];if(!T)throw new Error(`An attribute by the name of '${d}' was not provided to the shader.`);let g=T._layout,m=a.get(g);m||(r.push(g),m=[],n.push({arrayStride:g.stride,stepMode:g.stepMode,attributes:m}),a.set(g,m)),o=(u=ue(p))!=null?u:o,m.push({format:T.format,offset:T.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}function Fr(e,t="vertex"){return new ft(e,t)}function Ur(e){return(e==null?void 0:e.resourceType)==="vertex-layout"}function Be(e,t,r){if(vt(t)||Et(t))return Be(e,t.inner,ie(r,$(t)));if(R(t)){let n=r;return Object.fromEntries(Object.entries(t.propTypes).map(([a,o])=>{n=ie(n,v(o));let s=[a,Be(e,o,n)];return n+=b(o),s}))}if(It(t)){let n=r;return Object.fromEntries(Object.entries(t.propTypes).map(([a,o])=>{n=ie(n,$(o));let s=[a,Be(e,o,n)];return n+=b(o),s}))}if("type"in t&&typeof t.type=="string"){if(Rt.includes(t.type))return{_layout:e,format:t.type,offset:r};let n=_t[t.type];if(n)return{_layout:e,format:n,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var ft=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;i(this,"resourceType","vertex-layout");i(this,"stride");i(this,"attrib");i(this,"_label");let n=t(0);this.stride=ie(b(n.elementType),v(n)),this.attrib=Be(this,n.elementType,0)}get label(){return this._label}$name(t){return this._label=t,this}};function on(e){return typeof(e==null?void 0:e.loadOp)=="string"}function vr(e,t){if(O(e)){if(!on(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 sn(e){return typeof(e==null?void 0:e.format)=="string"}function Ar(e,t){if(O(e)){if(!sn(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 Rr(e){return new yt(new ct(e),{})}var yt=class e{constructor(t,r){this._core=t;this._priors=r;i(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(Ee(t))return new e(this._core,V(B({},this._priors),{bindGroupLayoutMap:new Map([...(n=this._priors.bindGroupLayoutMap)!=null?n:[],[t,r]])}));if(Ur(t))return new e(this._core,V(B({},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,V(B({},this._priors),{colorAttachment:t}))}draw(t,r,n,a){var T,g;let o=this._core.unwrap(),{branch:s,fragmentFn:u}=this._core.options,d=vr(u.shell.returnType,(T=this._priors.colorAttachment)!=null?T:{}).map(m=>j(m.view)?V(B({},m),{view:s.unwrap(m.view).createView()}):m),p=s.commandEncoder.beginRenderPass({label:(g=this._core.label)!=null?g:"<unnamed>",colorAttachments:d});p.setPipeline(o.pipeline),o.bindGroupLayouts.forEach((m,c)=>{var f;if(o.catchall&&c===o.catchall[0])p.setBindGroup(c,s.unwrap(o.catchall[1]));else{let h=(f=this._priors.bindGroupLayoutMap)==null?void 0:f.get(m);if(h===void 0)throw new se(m.label);p.setBindGroup(c,s.unwrap(h))}}),this._core.usedVertexLayouts.forEach((m,c)=>{var h,A;let f=(h=this._priors.vertexLayoutMap)==null?void 0:h.get(m);if(!f)throw new Error(`Missing vertex buffer for layout '${(A=m.label)!=null?A:"<unnamed>"}'. Please provide it using pipeline.with(layout, buffer).(...)`);p.setVertexBuffer(c,s.unwrap(f))}),p.draw(t,r,n,a),p.end()}},ct=class{constructor(t){this.options=t;i(this,"label");i(this,"usedVertexLayouts");i(this,"_memo");i(this,"_vertexBufferLayouts");i(this,"_targets");let r=Dr(t.vertexFn.shell.argTypes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=Ar(t.fragmentFn.shell.returnType,t.targets)}unwrap(){var t,r,n,a;if(this._memo===void 0){let{branch:o,vertexFn:s,fragmentFn:u,slotBindings:d,primitiveState:p}=this.options,{code:T,bindGroupLayouts:g,catchall:m}=ae({"~resolve":A=>(A.withSlots(d,()=>{A.resolve(s),A.resolve(u)}),""),toString:()=>{var A;return`renderPipeline:${(A=this.label)!=null?A:"<unnamed>"}`}},{names:o.nameRegistry,jitTranspiler:o.jitTranspiler});m!==null&&((r=g[m[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`));let c=o.device,f=c.createShaderModule({label:`${(n=this.label)!=null?n:"<unnamed>"} - Shader`,code:T}),h={layout:c.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:g.map(A=>o.unwrap(A))}),vertex:{module:f,buffers:this._vertexBufferLayouts},fragment:{module:f,targets:this._targets}};this.label!==void 0&&(h.label=this.label),p&&(h.primitive=p),this._memo={pipeline:c.createRenderPipeline(h),bindGroupLayouts:g,catchall:m}}return this._memo}};var xt=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[de(t)?t.slot:t,r]])}withCompute(t){return new bt(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new ht({branch:this._getRoot(),primitiveState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r})}},bt=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return wr(this._root,this._slotBindings,this._entryFn)}},ht=class{constructor(t){this._options=t}withFragment(t,r,n){return oe(typeof t!="string","Just type mismatch validation"),oe(typeof r!="string","Just type mismatch validation"),new wt(V(B({},this._options),{fragmentFn:t,targets:r}))}},wt=class e{constructor(t){this._options=t}withPrimitive(t){return new e(V(B({},this._options),{primitiveState:t}))}createPipeline(){return Rr(this._options)}},Pe=class extends xt{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;i(this,"~unstable");i(this,"_disposables",[]);i(this,"_unwrappedBindGroupLayouts",new ye(r=>r.unwrap(this)));i(this,"_unwrappedBindGroups",new ye(r=>r.unwrap(this)));i(this,"_commandEncoder",null);this["~unstable"]={nameRegistry:this.nameRegistry,commandEncoder:this.commandEncoder,createTexture:this.createTexture.bind(this),with:this.with.bind(this),withCompute:this.withCompute.bind(this),withVertex:this.withVertex.bind(this),flush:this.flush.bind(this)}}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=ar(this,r,n);return this._disposables.push(a),a}createBindGroup(r,n){return new H(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=fr(r,this);return this._disposables.push(n),n}unwrap(r){if(Sr(r))return r.rawPipeline;if(Ee(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(xr(r))return this._unwrappedBindGroups.getOrMake(r);if(re(r))return r.buffer;if(j(r)||at(r)||ot(r))return r.unwrap();throw new Error(`Unknown resource type: ${r}`)}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function _r(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 Pe(await o.requestDevice(r),n==="random"?new M:new N,a,!0)}function Ir(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e!=null?e:{};return new Pe(t,r==="random"?new M:new N,n,!1)}function Ve(e){return new St(e)}var St=class{constructor(t=void 0){this.defaultValue=t;i(this,"resourceType","slot");i(this,"label")}$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=C();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return t.unwrap(this)}};function Er(e,t){return new Dt(e,t)}var Dt=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;i(this,"resourceType","accessor");i(this,"label");i(this,"slot");this.slot=Ve(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(!C())throw new Error("Cannot access tgpu.accessor's value outside of resolution.");return this}"~resolve"(t){let r=t.unwrap(this.slot);return ur(r)?t.resolve(r):Ke(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function Lr(e){return un(e)}function un(e){return{resourceType:"derived","~compute":e,get value(){let r=C();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return r.unwrap(this)},with(r,n){return Br(e,this,[r,n])},toString(){return"derived"}}}function Br(e,t,r){return{resourceType:"derived","~compute"(){let a=C();if(!a)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return a.withSlots([r],()=>a.unwrap(t))},get value(){let a=C();if(!a)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return a.unwrap(this)},with(a,o){return Br(e,this,[a,o])},toString(){var s;let[a,o]=r;return`derived[${(s=a.label)!=null?s:"<unnamed>"}=${o}]`}}}function Pr(e,t){return new Ce("private",e,t)}function Vr(e){return new Ce("workgroup",e)}var Ce=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n;i(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(!P())throw new Error("Cannot access tgpu.var's value directly in JS.");return this}};var Cr={bindGroupLayout:Ie,init:_r,initFromDevice:Ir,resolve:hr,"~unstable":{fn:Ht,fragmentFn:Qt,vertexFn:Zt,computeFn:Yt,vertexLayout:Fr,derived:Lr,slot:Ve,accessor:Er,privateVar:Pr,workgroupVar:Vr,const:Wt,declare:zt,sampler:lr,comparisonSampler:dr}},Es=Cr;Object.assign(Cr,{__assignAst:Jt});export{se as MissingBindGroupError,Oe as MissingLinksError,Ge as MissingSlotValueError,ce as NotUniformError,M as RandomNameRegistry,X as ResolutionError,N as StrictNameRegistry,Es as default,re as isBuffer,rn as isComparisonSampler,Z as isDerived,ot as isSampledTextureView,tn as isSampler,Q as isSlot,at as isStorageTextureView,j as isTexture,Ke as isTgpuFn,nn as isUsableAsRender,st as isUsableAsSampled,Y as isUsableAsStorage,me as isUsableAsUniform,Xr as isUsableAsVertex,Cr as tgpu,Qr as unstable_asMutable,Zr as unstable_asReadonly,en as unstable_asUniform};
1
+ import {
2
+ alignmentOf,
3
+ attribute,
4
+ bool,
5
+ customAlignmentOf,
6
+ f32,
7
+ getAttributesString,
8
+ getCustomLocation,
9
+ i32,
10
+ isBuiltin,
11
+ isData,
12
+ isDecorated,
13
+ isLooseDecorated,
14
+ isUnstruct,
15
+ isWgslArray,
16
+ isWgslData,
17
+ isWgslStruct,
18
+ kindToDefaultFormatMap,
19
+ location,
20
+ mat2x2f,
21
+ mat3x3f,
22
+ mat4x4f,
23
+ roundUp,
24
+ sizeOf,
25
+ struct,
26
+ u32,
27
+ vertexFormats
28
+ } from "./chunk-2ZAQFPSX.js";
29
+ import {
30
+ MissingBindGroupsError,
31
+ MissingLinksError,
32
+ MissingSlotValueError,
33
+ MissingVertexBuffersError,
34
+ NotUniformError,
35
+ ResolutionError,
36
+ __publicField,
37
+ __spreadProps,
38
+ __spreadValues,
39
+ getResolutionCtx,
40
+ inGPUMode,
41
+ invariant,
42
+ provideCtx,
43
+ vec2f,
44
+ vec2h,
45
+ vec2i,
46
+ vec2u,
47
+ vec3f,
48
+ vec3h,
49
+ vec3i,
50
+ vec3u,
51
+ vec4f,
52
+ vec4h,
53
+ vec4i,
54
+ vec4u
55
+ } from "./chunk-DDEF2Y4S.js";
56
+
57
+ // src/core/slot/slotTypes.ts
58
+ function isSlot(value) {
59
+ return (value == null ? void 0 : value.resourceType) === "slot";
60
+ }
61
+ function isDerived(value) {
62
+ return (value == null ? void 0 : value.resourceType) === "derived";
63
+ }
64
+ function isProviding(value) {
65
+ return (value == null ? void 0 : value["~providing"]) !== void 0;
66
+ }
67
+ function isAccessor(value) {
68
+ return (value == null ? void 0 : value.resourceType) === "accessor";
69
+ }
70
+
71
+ // src/types.ts
72
+ var UnknownData = Symbol("Unknown data type");
73
+ function isSelfResolvable(value) {
74
+ return typeof (value == null ? void 0 : value["~resolve"]) === "function";
75
+ }
76
+ function isWgsl(value) {
77
+ return typeof value === "number" || typeof value === "boolean" || typeof value === "string" || isSelfResolvable(value) || isWgslData(value) || isSlot(value) || isDerived(value) || isProviding(value);
78
+ }
79
+ function isGPUBuffer(value) {
80
+ return !!value && typeof value === "object" && "getMappedRange" in value && "mapAsync" in value;
81
+ }
82
+ function isBufferUsage(value) {
83
+ return (value == null ? void 0 : value.resourceType) === "buffer-usage";
84
+ }
85
+
86
+ // src/core/valueProxyUtils.ts
87
+ var valueProxyHandler = {
88
+ get(target, prop) {
89
+ if (prop in target) {
90
+ return Reflect.get(target, prop);
91
+ }
92
+ if (prop === "~providing") {
93
+ return void 0;
94
+ }
95
+ return new Proxy(
96
+ {
97
+ "~resolve": (ctx) => `${ctx.resolve(target)}.${String(prop)}`,
98
+ toString: () => {
99
+ var _a;
100
+ return `.value(...).${String(prop)}:${(_a = target.label) != null ? _a : "<unnamed>"}`;
101
+ }
102
+ },
103
+ valueProxyHandler
104
+ );
105
+ }
106
+ };
107
+ function unwrapProxy(value) {
108
+ let unwrapped = value;
109
+ while (isSlot(unwrapped) || isDerived(unwrapped) || isAccessor(unwrapped) || isBufferUsage(unwrapped)) {
110
+ unwrapped = unwrapped.value;
111
+ }
112
+ return unwrapped;
113
+ }
114
+
115
+ // src/core/constant/tgpuConstant.ts
116
+ function constant(dataType, value) {
117
+ return new TgpuConstImpl(dataType, value);
118
+ }
119
+ var TgpuConstImpl = class {
120
+ constructor(dataType, _value) {
121
+ this.dataType = dataType;
122
+ this._value = _value;
123
+ __publicField(this, "_label");
124
+ }
125
+ get label() {
126
+ return this._label;
127
+ }
128
+ $name(label) {
129
+ this._label = label;
130
+ return this;
131
+ }
132
+ "~resolve"(ctx) {
133
+ const id = ctx.names.makeUnique(this._label);
134
+ const resolvedValue = ctx.resolveValue(this._value, this.dataType);
135
+ ctx.addDeclaration(`const ${id} = ${resolvedValue};`);
136
+ return id;
137
+ }
138
+ toString() {
139
+ var _a;
140
+ return `const:${(_a = this.label) != null ? _a : "<unnamed>"}`;
141
+ }
142
+ get value() {
143
+ if (!inGPUMode()) {
144
+ return this._value;
145
+ }
146
+ return new Proxy(
147
+ {
148
+ "~resolve": (ctx) => ctx.resolve(this),
149
+ toString: () => {
150
+ var _a;
151
+ return `.value:${(_a = this.label) != null ? _a : "<unnamed>"}`;
152
+ }
153
+ },
154
+ valueProxyHandler
155
+ );
156
+ }
157
+ };
158
+
159
+ // src/namable.ts
160
+ function isNamable(value) {
161
+ return !!value && (typeof value === "object" || typeof value === "function") && "$name" in value;
162
+ }
163
+
164
+ // src/core/resolve/externals.ts
165
+ function applyExternals(existing, newExternals) {
166
+ for (const [key, value] of Object.entries(newExternals)) {
167
+ existing[key] = value;
168
+ if (isNamable(value) && (!("label" in value) || value.label === void 0)) {
169
+ value.$name(key);
170
+ }
171
+ }
172
+ }
173
+ function addArgTypesToExternals(implementation, argTypes, applyExternals2) {
174
+ const argTypeNames = [
175
+ ...implementation.matchAll(new RegExp(":\\s*(?<arg>.*?)\\s*[,)]", "g"))
176
+ ].map((found) => found ? found[1] : void 0);
177
+ applyExternals2(
178
+ Object.fromEntries(
179
+ argTypes.flatMap((argType, i) => {
180
+ const argTypeName = argTypeNames ? argTypeNames[i] : void 0;
181
+ return isWgslStruct(argType) && argTypeName !== void 0 ? [[argTypeName, argType]] : [];
182
+ })
183
+ )
184
+ );
185
+ }
186
+ function addReturnTypeToExternals(implementation, returnType, applyExternals2) {
187
+ var _a;
188
+ const matched = implementation.match(new RegExp("->(?<output>.*?){", "s"));
189
+ const outputName = matched ? (_a = matched[1]) == null ? void 0 : _a.trim() : void 0;
190
+ if (isWgslStruct(returnType) && outputName && !/\s/g.test(outputName)) {
191
+ applyExternals2({ [outputName]: returnType });
192
+ }
193
+ }
194
+ function identifierRegex(name) {
195
+ return new RegExp(
196
+ `(?<![\\w_.])${name.replaceAll(".", "\\.")}(?![\\w_])`,
197
+ "g"
198
+ );
199
+ }
200
+ function replaceExternalsInWgsl(ctx, externalMap, wgsl) {
201
+ return Object.entries(externalMap).reduce((acc, [externalName, external]) => {
202
+ var _a;
203
+ if (isWgsl(external)) {
204
+ return acc.replaceAll(
205
+ identifierRegex(externalName),
206
+ ctx.resolve(external)
207
+ );
208
+ }
209
+ if (external !== null && typeof external === "object") {
210
+ const foundProperties = (_a = [
211
+ ...wgsl.matchAll(
212
+ new RegExp(
213
+ `${externalName.replaceAll(".", "\\.")}\\.(?<prop>.*?)(?![\\w_])`,
214
+ "g"
215
+ )
216
+ )
217
+ ].map((found) => found[1])) != null ? _a : [];
218
+ return foundProperties.reduce(
219
+ (innerAcc, prop) => prop && prop in external ? replaceExternalsInWgsl(
220
+ ctx,
221
+ {
222
+ [`${externalName}.${prop}`]: external[prop]
223
+ },
224
+ innerAcc
225
+ ) : innerAcc,
226
+ acc
227
+ );
228
+ }
229
+ return acc;
230
+ }, wgsl);
231
+ }
232
+
233
+ // src/core/declare/tgpuDeclare.ts
234
+ function declare(declaration) {
235
+ return new TgpuDeclareImpl(declaration);
236
+ }
237
+ var TgpuDeclareImpl = class {
238
+ constructor(declaration) {
239
+ this.declaration = declaration;
240
+ __publicField(this, "externalsToApply", []);
241
+ }
242
+ $uses(dependencyMap) {
243
+ this.externalsToApply.push(dependencyMap);
244
+ return this;
245
+ }
246
+ "~resolve"(ctx) {
247
+ const externalMap = {};
248
+ for (const externals of this.externalsToApply) {
249
+ applyExternals(externalMap, externals);
250
+ }
251
+ const replacedDeclaration = replaceExternalsInWgsl(
252
+ ctx,
253
+ externalMap,
254
+ this.declaration
255
+ );
256
+ ctx.addDeclaration(replacedDeclaration);
257
+ return "";
258
+ }
259
+ toString() {
260
+ return `declare: ${this.declaration}`;
261
+ }
262
+ };
263
+
264
+ // src/core/function/astUtils.ts
265
+ var functionToAstMap = /* @__PURE__ */ new WeakMap();
266
+ function getPrebuiltAstFor(fn2) {
267
+ return functionToAstMap.get(fn2);
268
+ }
269
+ function assignAst(fn2, ast, externals) {
270
+ functionToAstMap.set(fn2, { ast, externals });
271
+ return fn2;
272
+ }
273
+
274
+ // src/core/function/fnCore.ts
275
+ function createFnCore(shell, implementation) {
276
+ const externalsToApply = [];
277
+ if (typeof implementation === "string") {
278
+ addArgTypesToExternals(
279
+ implementation,
280
+ shell.argTypes,
281
+ (externals) => externalsToApply.push(externals)
282
+ );
283
+ addReturnTypeToExternals(
284
+ implementation,
285
+ shell.returnType,
286
+ (externals) => externalsToApply.push(externals)
287
+ );
288
+ }
289
+ return {
290
+ label: void 0,
291
+ applyExternals(newExternals) {
292
+ externalsToApply.push(newExternals);
293
+ },
294
+ resolve(ctx, fnAttribute = "") {
295
+ var _a;
296
+ const externalMap = {};
297
+ for (const externals of externalsToApply) {
298
+ applyExternals(externalMap, externals);
299
+ }
300
+ const id = ctx.names.makeUnique(this.label);
301
+ if (typeof implementation === "string") {
302
+ const replacedImpl = replaceExternalsInWgsl(
303
+ ctx,
304
+ externalMap,
305
+ implementation.trim()
306
+ );
307
+ ctx.addDeclaration(`${fnAttribute}fn ${id}${replacedImpl}`);
308
+ } else {
309
+ const pluginData = getPrebuiltAstFor(implementation);
310
+ if (pluginData == null ? void 0 : pluginData.externals) {
311
+ const missing = Object.fromEntries(
312
+ Object.entries(pluginData.externals).filter(
313
+ ([name]) => !(name in externalMap)
314
+ )
315
+ );
316
+ applyExternals(externalMap, missing);
317
+ }
318
+ const ast = (_a = pluginData == null ? void 0 : pluginData.ast) != null ? _a : ctx.transpileFn(String(implementation));
319
+ const missingExternals = ast.externalNames.filter(
320
+ (name) => !(name in externalMap)
321
+ );
322
+ if (missingExternals.length > 0) {
323
+ throw new MissingLinksError(this.label, missingExternals);
324
+ }
325
+ const args = ast.argNames.map((name, idx) => ({
326
+ value: name,
327
+ dataType: shell.argTypes[idx]
328
+ }));
329
+ const { head, body } = ctx.fnToWgsl({
330
+ args,
331
+ returnType: shell.returnType,
332
+ body: ast.body,
333
+ externalMap
334
+ });
335
+ ctx.addDeclaration(
336
+ `${fnAttribute}fn ${id}${ctx.resolve(head)}${ctx.resolve(body)}`
337
+ );
338
+ }
339
+ return id;
340
+ }
341
+ };
342
+ }
343
+
344
+ // src/core/function/tgpuComputeFn.ts
345
+ function computeFn(argTypes, options) {
346
+ var _a, _b, _c;
347
+ const { workgroupSize } = options;
348
+ return {
349
+ argTypes: [],
350
+ returnType: void 0,
351
+ workgroupSize: [
352
+ (_a = workgroupSize[0]) != null ? _a : 1,
353
+ (_b = workgroupSize[1]) != null ? _b : 1,
354
+ (_c = workgroupSize[2]) != null ? _c : 1
355
+ ],
356
+ does(implementation) {
357
+ return createComputeFn(this, workgroupSize, implementation);
358
+ }
359
+ };
360
+ }
361
+ function createComputeFn(shell, workgroupSize, implementation) {
362
+ const core = createFnCore(shell, implementation);
363
+ return {
364
+ shell,
365
+ get label() {
366
+ return core.label;
367
+ },
368
+ $uses(newExternals) {
369
+ core.applyExternals(newExternals);
370
+ return this;
371
+ },
372
+ $name(newLabel) {
373
+ core.label = newLabel;
374
+ return this;
375
+ },
376
+ "~resolve"(ctx) {
377
+ return core.resolve(
378
+ ctx,
379
+ `@compute @workgroup_size(${workgroupSize.join(", ")}) `
380
+ );
381
+ },
382
+ toString() {
383
+ var _a;
384
+ return `computeFn:${(_a = this.label) != null ? _a : "<unnamed>"}`;
385
+ }
386
+ };
387
+ }
388
+
389
+ // src/core/function/tgpuFn.ts
390
+ function fn(argTypes, returnType) {
391
+ return {
392
+ argTypes,
393
+ returnType,
394
+ does(implementation) {
395
+ return createFn(this, implementation);
396
+ }
397
+ };
398
+ }
399
+ function isTgpuFn(value) {
400
+ return (value == null ? void 0 : value.resourceType) === "function";
401
+ }
402
+ function stringifyPair([slot2, value]) {
403
+ var _a;
404
+ return `${(_a = slot2.label) != null ? _a : "<unnamed>"}=${value}`;
405
+ }
406
+ function createFn(shell, implementation) {
407
+ const core = createFnCore(shell, implementation);
408
+ const fnBase = {
409
+ shell,
410
+ resourceType: "function",
411
+ $uses(newExternals) {
412
+ core.applyExternals(newExternals);
413
+ return this;
414
+ },
415
+ $name(newLabel) {
416
+ core.label = newLabel;
417
+ return this;
418
+ },
419
+ with(slot2, value) {
420
+ return createBoundFunction(fn2, [
421
+ [isAccessor(slot2) ? slot2.slot : slot2, value]
422
+ ]);
423
+ },
424
+ "~resolve"(ctx) {
425
+ return core.resolve(ctx);
426
+ }
427
+ };
428
+ const call = (...args) => {
429
+ if (inGPUMode()) {
430
+ return new FnCall(fn2, args);
431
+ }
432
+ if (typeof implementation === "string") {
433
+ throw new Error(
434
+ "Cannot execute on the CPU functions constructed with raw WGSL"
435
+ );
436
+ }
437
+ return implementation(...args);
438
+ };
439
+ const fn2 = Object.assign(call, fnBase);
440
+ Object.defineProperty(fn2, "label", {
441
+ get: () => core.label
442
+ });
443
+ Object.defineProperty(fn2, "toString", {
444
+ value: () => {
445
+ var _a;
446
+ return `fn:${(_a = core.label) != null ? _a : "<unnamed>"}`;
447
+ }
448
+ });
449
+ return fn2;
450
+ }
451
+ function createBoundFunction(innerFn, pairs) {
452
+ const fnBase = {
453
+ resourceType: "function",
454
+ shell: innerFn.shell,
455
+ "~providing": {
456
+ inner: innerFn,
457
+ pairs
458
+ },
459
+ $uses(newExternals) {
460
+ innerFn.$uses(newExternals);
461
+ return this;
462
+ },
463
+ $name(newLabel) {
464
+ innerFn.$name(newLabel);
465
+ return this;
466
+ },
467
+ with(slot2, value) {
468
+ return createBoundFunction(fn2, [
469
+ ...pairs,
470
+ [isAccessor(slot2) ? slot2.slot : slot2, value]
471
+ ]);
472
+ }
473
+ };
474
+ const call = (...args) => {
475
+ if (inGPUMode()) {
476
+ return new FnCall(fn2, args);
477
+ }
478
+ return innerFn(...args);
479
+ };
480
+ const fn2 = Object.assign(call, fnBase);
481
+ Object.defineProperty(fn2, "label", {
482
+ get: () => innerFn.label
483
+ });
484
+ Object.defineProperty(fn2, "toString", {
485
+ value() {
486
+ var _a;
487
+ const fnLabel = (_a = innerFn.label) != null ? _a : "<unnamed>";
488
+ return `fn:${fnLabel}[${pairs.map(stringifyPair).join(", ")}]`;
489
+ }
490
+ });
491
+ return fn2;
492
+ }
493
+ var FnCall = class {
494
+ constructor(_fn, _params) {
495
+ this._fn = _fn;
496
+ this._params = _params;
497
+ }
498
+ get label() {
499
+ return this._fn.label;
500
+ }
501
+ "~resolve"(ctx) {
502
+ return ctx.resolve(
503
+ `${ctx.resolve(this._fn)}(${this._params.map((param) => ctx.resolve(param)).join(", ")})`
504
+ );
505
+ }
506
+ toString() {
507
+ var _a;
508
+ return `call:${(_a = this.label) != null ? _a : "<unnamed>"}`;
509
+ }
510
+ };
511
+
512
+ // src/core/function/ioOutputType.ts
513
+ function withLocations(members) {
514
+ let nextLocation = 0;
515
+ return Object.fromEntries(
516
+ Object.entries(members).map(([key, member]) => {
517
+ if (isBuiltin(member)) {
518
+ return [key, member];
519
+ }
520
+ const customLocation = getCustomLocation(member);
521
+ if (customLocation !== void 0) {
522
+ nextLocation = customLocation + 1;
523
+ return [key, member];
524
+ }
525
+ return [
526
+ key,
527
+ attribute(member, { type: "@location", value: nextLocation++ })
528
+ ];
529
+ })
530
+ );
531
+ }
532
+ function createOutputType(returnType) {
533
+ return isData(returnType) ? location(0, returnType) : struct(withLocations(returnType));
534
+ }
535
+ function createStructFromIO(members) {
536
+ return struct(withLocations(members));
537
+ }
538
+
539
+ // src/core/function/tgpuFragmentFn.ts
540
+ function fragmentFn(inputType, outputType) {
541
+ return {
542
+ argTypes: [inputType],
543
+ returnType: outputType,
544
+ does(implementation) {
545
+ return createFragmentFn(this, implementation);
546
+ }
547
+ };
548
+ }
549
+ function createFragmentFn(shell, implementation) {
550
+ const core = createFnCore(shell, implementation);
551
+ const outputType = createOutputType(shell.returnType);
552
+ if (typeof implementation === "string") {
553
+ addReturnTypeToExternals(
554
+ implementation,
555
+ outputType,
556
+ (externals) => core.applyExternals(externals)
557
+ );
558
+ }
559
+ const result = {
560
+ shell,
561
+ outputType,
562
+ get label() {
563
+ return core.label;
564
+ },
565
+ $uses(newExternals) {
566
+ core.applyExternals(newExternals);
567
+ return this;
568
+ },
569
+ $name(newLabel) {
570
+ core.label = newLabel;
571
+ if (isNamable(outputType)) {
572
+ outputType.$name(`${newLabel}_Output`);
573
+ }
574
+ return this;
575
+ },
576
+ "~resolve"(ctx) {
577
+ return core.resolve(ctx, "@fragment ");
578
+ },
579
+ toString() {
580
+ var _a;
581
+ return `fragmentFn:${(_a = this.label) != null ? _a : "<unnamed>"}`;
582
+ }
583
+ };
584
+ return result;
585
+ }
586
+
587
+ // src/core/function/tgpuVertexFn.ts
588
+ function vertexFn(inputType, outputType) {
589
+ return {
590
+ attributes: [inputType],
591
+ returnType: createOutputType(outputType),
592
+ argTypes: [createStructFromIO(inputType)],
593
+ does(implementation) {
594
+ return createVertexFn(this, implementation);
595
+ }
596
+ };
597
+ }
598
+ function createVertexFn(shell, implementation) {
599
+ const core = createFnCore(shell, implementation);
600
+ const outputType = shell.returnType;
601
+ const inputType = shell.argTypes[0];
602
+ if (typeof implementation === "string") {
603
+ addReturnTypeToExternals(
604
+ implementation,
605
+ outputType,
606
+ (externals) => core.applyExternals(externals)
607
+ );
608
+ }
609
+ return {
610
+ shell,
611
+ outputType,
612
+ inputType,
613
+ get label() {
614
+ return core.label;
615
+ },
616
+ $uses(newExternals) {
617
+ core.applyExternals(newExternals);
618
+ return this;
619
+ },
620
+ $name(newLabel) {
621
+ core.label = newLabel;
622
+ if (isNamable(outputType)) {
623
+ outputType.$name(`${newLabel}_Output`);
624
+ }
625
+ if (isNamable(inputType)) {
626
+ inputType.$name(`${newLabel}_Input`);
627
+ }
628
+ return this;
629
+ },
630
+ "~resolve"(ctx) {
631
+ if (typeof implementation === "string") {
632
+ return core.resolve(ctx, "@vertex ");
633
+ }
634
+ const generationCtx = ctx;
635
+ if (generationCtx.callStack === void 0) {
636
+ throw new Error(
637
+ "Cannot resolve a TGSL function outside of a generation context"
638
+ );
639
+ }
640
+ try {
641
+ generationCtx.callStack.push(outputType);
642
+ return core.resolve(ctx, "@vertex ");
643
+ } finally {
644
+ generationCtx.callStack.pop();
645
+ }
646
+ },
647
+ toString() {
648
+ var _a;
649
+ return `vertexFn:${(_a = this.label) != null ? _a : "<unnamed>"}`;
650
+ }
651
+ };
652
+ }
653
+
654
+ // src/nameRegistry.ts
655
+ var RandomNameRegistry = class {
656
+ constructor() {
657
+ __publicField(this, "lastUniqueId", 0);
658
+ }
659
+ makeUnique(primer) {
660
+ let label;
661
+ if (primer) {
662
+ label = primer.replaceAll(/\s/g, "_");
663
+ label = label.replaceAll(/[^\w\d]/g, "");
664
+ } else {
665
+ label = "item";
666
+ }
667
+ return `${label}_${this.lastUniqueId++}`;
668
+ }
669
+ };
670
+ var StrictNameRegistry = class {
671
+ constructor() {
672
+ /**
673
+ * Allows to provide a good fallback for instances of the
674
+ * same function that are bound to different slot values.
675
+ */
676
+ __publicField(this, "_usedNames", /* @__PURE__ */ new Set());
677
+ }
678
+ makeUnique(primer) {
679
+ if (primer === void 0) {
680
+ throw new Error("Unnamed item found when using a strict name registry");
681
+ }
682
+ let index = 0;
683
+ let unusedName = primer;
684
+ while (this._usedNames.has(unusedName)) {
685
+ index++;
686
+ unusedName = `${primer}_${index}`;
687
+ }
688
+ this._usedNames.add(unusedName);
689
+ return unusedName;
690
+ }
691
+ };
692
+
693
+ // src/shared/utilityTypes.ts
694
+ function assertExhaustive(x, location2) {
695
+ throw new Error(`Failed to handle ${x} at ${location2}`);
696
+ }
697
+
698
+ // src/core/resolve/resolveData.ts
699
+ var identityTypes = [
700
+ "bool",
701
+ "f32",
702
+ "f16",
703
+ "i32",
704
+ "u32",
705
+ "vec2f",
706
+ "vec3f",
707
+ "vec4f",
708
+ "vec2h",
709
+ "vec3h",
710
+ "vec4h",
711
+ "vec2i",
712
+ "vec3i",
713
+ "vec4i",
714
+ "vec2u",
715
+ "vec3u",
716
+ "vec4u",
717
+ "mat2x2f",
718
+ "mat3x3f",
719
+ "mat4x4f"
720
+ ];
721
+ function isIdentityType(data) {
722
+ return identityTypes.includes(data.type);
723
+ }
724
+ function resolveStructProperty(ctx, [key, property]) {
725
+ return ` ${getAttributesString(property)}${key}: ${ctx.resolve(property)},
726
+ `;
727
+ }
728
+ function resolveStruct(ctx, struct2) {
729
+ const id = ctx.names.makeUnique(struct2.label);
730
+ ctx.addDeclaration(`
731
+ struct ${id} {
732
+ ${Object.entries(struct2.propTypes).map((prop) => resolveStructProperty(ctx, prop)).join("")}}
733
+ `);
734
+ return id;
735
+ }
736
+ function resolveArray(ctx, array) {
737
+ const element = ctx.resolve(array.elementType);
738
+ return array.elementCount === 0 ? `array<${element}>` : `array<${element}, ${array.elementCount}>`;
739
+ }
740
+ function resolveData(ctx, data) {
741
+ if (isIdentityType(data)) {
742
+ return data.type;
743
+ }
744
+ if (data.type === "struct") {
745
+ return resolveStruct(ctx, data);
746
+ }
747
+ if (data.type === "array") {
748
+ return resolveArray(ctx, data);
749
+ }
750
+ if (data.type === "atomic") {
751
+ return `atomic<${resolveData(ctx, data.inner)}>`;
752
+ }
753
+ if (data.type === "decorated") {
754
+ return ctx.resolve(data.inner);
755
+ }
756
+ if (data.type === "ptrFn") {
757
+ return `ptr<function, ${ctx.resolve(data.inner)}>`;
758
+ }
759
+ assertExhaustive(data, "resolveData");
760
+ }
761
+
762
+ // src/shared/generators.ts
763
+ function* naturalsExcept(excluded) {
764
+ let next = 0;
765
+ while (true) {
766
+ if (!excluded.has(next)) {
767
+ yield next;
768
+ }
769
+ next++;
770
+ }
771
+ }
772
+
773
+ // src/smol/wgslGenerator.ts
774
+ var parenthesizedOps = [
775
+ "==",
776
+ "!=",
777
+ "<",
778
+ "<=",
779
+ ">",
780
+ ">=",
781
+ "<<",
782
+ ">>",
783
+ "+",
784
+ "-",
785
+ "*",
786
+ "/",
787
+ "%",
788
+ "|",
789
+ "^",
790
+ "&",
791
+ "&&",
792
+ "||"
793
+ ];
794
+ function resolveRes(ctx, res) {
795
+ if (isWgsl(res.value) || isWgslData(res.value)) {
796
+ return ctx.resolve(res.value);
797
+ }
798
+ return String(res.value);
799
+ }
800
+ function assertExhaustive2(value) {
801
+ throw new Error(
802
+ `'${JSON.stringify(value)}' was not handled by the WGSL generator.`
803
+ );
804
+ }
805
+ function generateBoolean(ctx, value) {
806
+ return value ? { value: "true", dataType: bool } : { value: "false", dataType: bool };
807
+ }
808
+ function generateBlock(ctx, value) {
809
+ return `${ctx.indent()}{
810
+ ${value.b.map((statement) => generateStatement(ctx, statement)).join("\n")}
811
+ ${ctx.dedent()}}`;
812
+ }
813
+ function generateIdentifier(ctx, id) {
814
+ return ctx.getById(id);
815
+ }
816
+ function generateExpression(ctx, expression) {
817
+ if (typeof expression === "string") {
818
+ return generateIdentifier(ctx, expression);
819
+ }
820
+ if (typeof expression === "boolean") {
821
+ return generateBoolean(ctx, expression);
822
+ }
823
+ if ("x" in expression) {
824
+ const [lhs, op, rhs] = expression.x;
825
+ const lhsExpr = resolveRes(ctx, generateExpression(ctx, lhs));
826
+ const rhsExpr = resolveRes(ctx, generateExpression(ctx, rhs));
827
+ return {
828
+ value: parenthesizedOps.includes(op) ? `(${lhsExpr} ${op} ${rhsExpr})` : `${lhsExpr} ${op} ${rhsExpr}`,
829
+ // TODO: Infer data type from expression type and arguments.
830
+ dataType: UnknownData
831
+ };
832
+ }
833
+ if ("u" in expression) {
834
+ const [op, arg] = expression.u;
835
+ const argExpr = resolveRes(ctx, generateExpression(ctx, arg));
836
+ return {
837
+ value: `${op}${argExpr}`,
838
+ // TODO: Infer data type from expression type and arguments.
839
+ dataType: UnknownData
840
+ };
841
+ }
842
+ if ("a" in expression) {
843
+ const [targetId, property] = expression.a;
844
+ const target = generateExpression(ctx, targetId);
845
+ const propertyStr = resolveRes(ctx, generateExpression(ctx, property));
846
+ if (typeof target.value === "string") {
847
+ return {
848
+ value: `${target.value}.${propertyStr}`,
849
+ // TODO: Infer data type
850
+ dataType: UnknownData
851
+ };
852
+ }
853
+ if (isWgsl(target.value)) {
854
+ return {
855
+ // biome-ignore lint/suspicious/noExplicitAny: <sorry TypeScript>
856
+ value: target.value[propertyStr],
857
+ // TODO: Infer data type
858
+ dataType: UnknownData
859
+ };
860
+ }
861
+ if (typeof target.value === "object") {
862
+ return {
863
+ // biome-ignore lint/suspicious/noExplicitAny: <sorry TypeScript>
864
+ value: target.value[propertyStr],
865
+ // TODO: Infer data type
866
+ dataType: UnknownData
867
+ };
868
+ }
869
+ throw new Error(`Cannot access member ${propertyStr} of ${target.value}`);
870
+ }
871
+ if ("i" in expression) {
872
+ const [target, property] = expression.i;
873
+ const targetStr = resolveRes(ctx, generateExpression(ctx, target));
874
+ const propertyStr = resolveRes(ctx, generateExpression(ctx, property));
875
+ return {
876
+ value: `${targetStr}[${propertyStr}]`,
877
+ // TODO: Infer data type
878
+ dataType: UnknownData
879
+ };
880
+ }
881
+ if ("n" in expression) {
882
+ return { value: expression.n, dataType: UnknownData };
883
+ }
884
+ if ("f" in expression) {
885
+ const [callee, args] = expression.f;
886
+ const id = generateExpression(ctx, callee);
887
+ const idValue = id.value;
888
+ ctx.callStack.push(idValue);
889
+ const argResources = args.map((arg) => generateExpression(ctx, arg));
890
+ const argValues = argResources.map((res) => resolveRes(ctx, res));
891
+ ctx.callStack.pop();
892
+ if (typeof idValue === "string") {
893
+ return {
894
+ value: `${idValue}(${argValues.join(", ")})`,
895
+ dataType: UnknownData
896
+ };
897
+ }
898
+ if (isWgslStruct(idValue)) {
899
+ const id2 = ctx.resolve(idValue);
900
+ return {
901
+ value: `${id2}(${argValues.join(", ")})`,
902
+ dataType: UnknownData
903
+ };
904
+ }
905
+ const result = idValue(
906
+ ...argValues
907
+ );
908
+ return { value: result, dataType: UnknownData };
909
+ }
910
+ if ("o" in expression) {
911
+ const obj = expression.o;
912
+ const callee = ctx.callStack[ctx.callStack.length - 1];
913
+ const generateEntries = (values) => values.map((value) => {
914
+ const valueRes = generateExpression(ctx, value);
915
+ return resolveRes(ctx, valueRes);
916
+ }).join(", ");
917
+ if (isWgslStruct(callee)) {
918
+ const propKeys = Object.keys(callee.propTypes);
919
+ const values = propKeys.map((key) => {
920
+ const val = obj[key];
921
+ if (val === void 0) {
922
+ throw new Error(
923
+ `Missing property ${key} in object literal for struct ${callee}`
924
+ );
925
+ }
926
+ return val;
927
+ });
928
+ return {
929
+ value: generateEntries(values),
930
+ dataType: callee
931
+ };
932
+ }
933
+ return {
934
+ value: generateEntries(Object.values(obj)),
935
+ dataType: UnknownData
936
+ };
937
+ }
938
+ assertExhaustive2(expression);
939
+ }
940
+ function generateStatement(ctx, statement) {
941
+ if (typeof statement === "string") {
942
+ return `${ctx.pre}${resolveRes(ctx, generateIdentifier(ctx, statement))};`;
943
+ }
944
+ if (typeof statement === "boolean") {
945
+ return `${ctx.pre}${resolveRes(ctx, generateBoolean(ctx, statement))};`;
946
+ }
947
+ if ("r" in statement) {
948
+ if (isWgslStruct(ctx.callStack[ctx.callStack.length - 1]) && statement.r !== null) {
949
+ const resource = resolveRes(ctx, generateExpression(ctx, statement.r));
950
+ const resolvedStruct = ctx.resolve(
951
+ ctx.callStack[ctx.callStack.length - 1]
952
+ );
953
+ return `${ctx.pre}return ${resolvedStruct}(${resource});`;
954
+ }
955
+ return statement.r === null ? `${ctx.pre}return;` : `${ctx.pre}return ${resolveRes(ctx, generateExpression(ctx, statement.r))};`;
956
+ }
957
+ if ("q" in statement) {
958
+ const [cond, cons, alt] = statement.q;
959
+ const condition = resolveRes(ctx, generateExpression(ctx, cond));
960
+ ctx.indent();
961
+ const consequent = generateStatement(ctx, cons);
962
+ ctx.dedent();
963
+ ctx.indent();
964
+ const alternate = alt ? generateStatement(ctx, alt) : void 0;
965
+ ctx.dedent();
966
+ if (!alternate) {
967
+ return `${ctx.pre}if (${condition})
968
+ ${consequent}`;
969
+ }
970
+ return `${ctx.pre}if (${condition})
971
+ ${consequent}
972
+ ${ctx.pre}else
973
+ ${alternate}`;
974
+ }
975
+ if ("l" in statement || "c" in statement) {
976
+ const [rawId, rawValue] = "l" in statement ? statement.l : statement.c;
977
+ const id = resolveRes(ctx, generateIdentifier(ctx, rawId));
978
+ const eq = rawValue ? generateExpression(ctx, rawValue) : void 0;
979
+ if (!eq) {
980
+ throw new Error("Cannot create variable without an initial value.");
981
+ }
982
+ return `${ctx.pre}var ${id} = ${resolveRes(ctx, eq)};`;
983
+ }
984
+ if ("b" in statement) {
985
+ return generateBlock(ctx, statement);
986
+ }
987
+ return `${ctx.pre}${resolveRes(ctx, generateExpression(ctx, statement))};`;
988
+ }
989
+ function generateFunction(ctx, body) {
990
+ return generateBlock(ctx, body);
991
+ }
992
+
993
+ // src/core/buffer/buffer.ts
994
+ import { BufferReader, BufferWriter } from "typed-binary";
995
+
996
+ // src/data/alignIO.ts
997
+ function alignIO(io, baseAlignment) {
998
+ const currentPos = "size" in io ? io.size : io.currentByteOffset;
999
+ const bitMask = baseAlignment - 1;
1000
+ const offset = currentPos & bitMask;
1001
+ if ("skipBytes" in io) {
1002
+ io.skipBytes(baseAlignment - offset & bitMask);
1003
+ } else {
1004
+ io.add(baseAlignment - offset & bitMask);
1005
+ }
1006
+ }
1007
+ var alignIO_default = alignIO;
1008
+
1009
+ // src/data/dataIO.ts
1010
+ var dataWriters = {
1011
+ bool(output, _schema, value) {
1012
+ output.writeBool(value);
1013
+ },
1014
+ f32(output, _schema, value) {
1015
+ output.writeFloat32(value);
1016
+ },
1017
+ f16(output, _schema, value) {
1018
+ output.writeFloat16(value);
1019
+ },
1020
+ i32(output, _schema, value) {
1021
+ output.writeInt32(value);
1022
+ },
1023
+ u32(output, _schema, value) {
1024
+ output.writeUint32(value);
1025
+ },
1026
+ vec2f(output, _, value) {
1027
+ output.writeFloat32(value.x);
1028
+ output.writeFloat32(value.y);
1029
+ },
1030
+ vec2h(output, _, value) {
1031
+ output.writeFloat16(value.x);
1032
+ output.writeFloat16(value.y);
1033
+ },
1034
+ vec2i(output, _, value) {
1035
+ output.writeInt32(value.x);
1036
+ output.writeInt32(value.y);
1037
+ },
1038
+ vec2u(output, _, value) {
1039
+ output.writeUint32(value.x);
1040
+ output.writeUint32(value.y);
1041
+ },
1042
+ vec3f(output, _, value) {
1043
+ output.writeFloat32(value.x);
1044
+ output.writeFloat32(value.y);
1045
+ output.writeFloat32(value.z);
1046
+ },
1047
+ vec3h(output, _, value) {
1048
+ output.writeFloat16(value.x);
1049
+ output.writeFloat16(value.y);
1050
+ output.writeFloat16(value.z);
1051
+ },
1052
+ vec3i(output, _, value) {
1053
+ output.writeInt32(value.x);
1054
+ output.writeInt32(value.y);
1055
+ output.writeInt32(value.z);
1056
+ },
1057
+ vec3u(output, _, value) {
1058
+ output.writeUint32(value.x);
1059
+ output.writeUint32(value.y);
1060
+ output.writeUint32(value.z);
1061
+ },
1062
+ vec4f(output, _, value) {
1063
+ output.writeFloat32(value.x);
1064
+ output.writeFloat32(value.y);
1065
+ output.writeFloat32(value.z);
1066
+ output.writeFloat32(value.w);
1067
+ },
1068
+ vec4h(output, _, value) {
1069
+ output.writeFloat16(value.x);
1070
+ output.writeFloat16(value.y);
1071
+ output.writeFloat16(value.z);
1072
+ output.writeFloat16(value.w);
1073
+ },
1074
+ vec4i(output, _, value) {
1075
+ output.writeInt32(value.x);
1076
+ output.writeInt32(value.y);
1077
+ output.writeInt32(value.z);
1078
+ output.writeInt32(value.w);
1079
+ },
1080
+ vec4u(output, _, value) {
1081
+ output.writeUint32(value.x);
1082
+ output.writeUint32(value.y);
1083
+ output.writeUint32(value.z);
1084
+ output.writeUint32(value.w);
1085
+ },
1086
+ mat2x2f(output, _, value) {
1087
+ for (let i = 0; i < value.length; ++i) {
1088
+ output.writeFloat32(value[i]);
1089
+ }
1090
+ },
1091
+ mat3x3f(output, _, value) {
1092
+ for (let i = 0; i < value.length; ++i) {
1093
+ output.writeFloat32(value[i]);
1094
+ }
1095
+ },
1096
+ mat4x4f(output, _, value) {
1097
+ for (let i = 0; i < value.length; ++i) {
1098
+ output.writeFloat32(value[i]);
1099
+ }
1100
+ },
1101
+ struct(output, schema, value) {
1102
+ const alignment = alignmentOf(schema);
1103
+ alignIO_default(output, alignment);
1104
+ for (const [key, property] of Object.entries(schema.propTypes)) {
1105
+ alignIO_default(output, alignmentOf(property));
1106
+ writeData(output, property, value[key]);
1107
+ }
1108
+ alignIO_default(output, alignment);
1109
+ },
1110
+ array(output, schema, value) {
1111
+ if (schema.elementCount === 0) {
1112
+ throw new Error("Cannot write using a runtime-sized schema.");
1113
+ }
1114
+ const alignment = alignmentOf(schema);
1115
+ alignIO_default(output, alignment);
1116
+ const beginning = output.currentByteOffset;
1117
+ for (let i = 0; i < Math.min(schema.elementCount, value.length); i++) {
1118
+ alignIO_default(output, alignment);
1119
+ writeData(output, schema.elementType, value[i]);
1120
+ }
1121
+ output.seekTo(beginning + sizeOf(schema));
1122
+ },
1123
+ ptrFn() {
1124
+ throw new Error("Pointers are not host-shareable");
1125
+ },
1126
+ atomic(output, schema, value) {
1127
+ var _a;
1128
+ (_a = dataWriters[schema.inner.type]) == null ? void 0 : _a.call(dataWriters, output, schema, value);
1129
+ },
1130
+ decorated(output, schema, value) {
1131
+ var _a, _b;
1132
+ const alignment = customAlignmentOf(schema);
1133
+ alignIO_default(output, alignment);
1134
+ const beginning = output.currentByteOffset;
1135
+ (_b = dataWriters[(_a = schema.inner) == null ? void 0 : _a.type]) == null ? void 0 : _b.call(dataWriters, output, schema.inner, value);
1136
+ output.seekTo(beginning + sizeOf(schema));
1137
+ },
1138
+ // Loose Types
1139
+ uint8(output, _, value) {
1140
+ output.writeUint8(value);
1141
+ },
1142
+ uint8x2(output, _, value) {
1143
+ output.writeUint8(value.x);
1144
+ output.writeUint8(value.y);
1145
+ },
1146
+ uint8x4(output, _, value) {
1147
+ output.writeUint8(value.x);
1148
+ output.writeUint8(value.y);
1149
+ output.writeUint8(value.z);
1150
+ output.writeUint8(value.w);
1151
+ },
1152
+ sint8(output, _, value) {
1153
+ output.writeInt8(value);
1154
+ },
1155
+ sint8x2(output, _, value) {
1156
+ output.writeInt8(value.x);
1157
+ output.writeInt8(value.y);
1158
+ },
1159
+ sint8x4(output, _, value) {
1160
+ output.writeInt8(value.x);
1161
+ output.writeInt8(value.y);
1162
+ output.writeInt8(value.z);
1163
+ output.writeInt8(value.w);
1164
+ },
1165
+ unorm8(output, _, value) {
1166
+ output.writeUint8(value * 255);
1167
+ },
1168
+ unorm8x2(output, _, value) {
1169
+ output.writeUint8(value.x * 255);
1170
+ output.writeUint8(value.y * 255);
1171
+ },
1172
+ unorm8x4(output, _, value) {
1173
+ output.writeUint8(value.x * 255);
1174
+ output.writeUint8(value.y * 255);
1175
+ output.writeUint8(value.z * 255);
1176
+ output.writeUint8(value.w * 255);
1177
+ },
1178
+ snorm8(output, _, value) {
1179
+ output.writeUint8(value * 127 + 128);
1180
+ },
1181
+ snorm8x2(output, _, value) {
1182
+ output.writeUint8(value.x * 127 + 128);
1183
+ output.writeUint8(value.y * 127 + 128);
1184
+ },
1185
+ snorm8x4(output, _, value) {
1186
+ output.writeUint8(value.x * 127 + 128);
1187
+ output.writeUint8(value.y * 127 + 128);
1188
+ output.writeUint8(value.z * 127 + 128);
1189
+ output.writeUint8(value.w * 127 + 128);
1190
+ },
1191
+ uint16(output, _, value) {
1192
+ output.writeUint16(value);
1193
+ },
1194
+ uint16x2(output, _, value) {
1195
+ output.writeUint16(value.x);
1196
+ output.writeUint16(value.y);
1197
+ },
1198
+ uint16x4(output, _, value) {
1199
+ output.writeUint16(value.x);
1200
+ output.writeUint16(value.y);
1201
+ output.writeUint16(value.z);
1202
+ output.writeUint16(value.w);
1203
+ },
1204
+ sint16(output, _, value) {
1205
+ output.writeInt16(value);
1206
+ },
1207
+ sint16x2(output, _, value) {
1208
+ output.writeInt16(value.x);
1209
+ output.writeInt16(value.y);
1210
+ },
1211
+ sint16x4(output, _, value) {
1212
+ output.writeInt16(value.x);
1213
+ output.writeInt16(value.y);
1214
+ output.writeInt16(value.z);
1215
+ output.writeInt16(value.w);
1216
+ },
1217
+ unorm16(output, _, value) {
1218
+ output.writeUint16(value * 65535);
1219
+ },
1220
+ unorm16x2(output, _, value) {
1221
+ output.writeUint16(value.x * 65535);
1222
+ output.writeUint16(value.y * 65535);
1223
+ },
1224
+ unorm16x4(output, _, value) {
1225
+ output.writeUint16(value.x * 65535);
1226
+ output.writeUint16(value.y * 65535);
1227
+ output.writeUint16(value.z * 65535);
1228
+ output.writeUint16(value.w * 65535);
1229
+ },
1230
+ snorm16(output, _, value) {
1231
+ output.writeUint16(value * 32767 + 32768);
1232
+ },
1233
+ snorm16x2(output, _, value) {
1234
+ output.writeUint16(value.x * 32767 + 32768);
1235
+ output.writeUint16(value.y * 32767 + 32768);
1236
+ },
1237
+ snorm16x4(output, _, value) {
1238
+ output.writeUint16(value.x * 32767 + 32768);
1239
+ output.writeUint16(value.y * 32767 + 32768);
1240
+ output.writeUint16(value.z * 32767 + 32768);
1241
+ output.writeUint16(value.w * 32767 + 32768);
1242
+ },
1243
+ float16(output, _, value) {
1244
+ output.writeFloat16(value);
1245
+ },
1246
+ float16x2(output, _, value) {
1247
+ output.writeFloat16(value.x);
1248
+ output.writeFloat16(value.y);
1249
+ },
1250
+ float16x4(output, _, value) {
1251
+ output.writeFloat16(value.x);
1252
+ output.writeFloat16(value.y);
1253
+ output.writeFloat16(value.z);
1254
+ output.writeFloat16(value.w);
1255
+ },
1256
+ float32(output, _, value) {
1257
+ output.writeFloat32(value);
1258
+ },
1259
+ float32x2(output, _, value) {
1260
+ output.writeFloat32(value.x);
1261
+ output.writeFloat32(value.y);
1262
+ },
1263
+ float32x3(output, _, value) {
1264
+ output.writeFloat32(value.x);
1265
+ output.writeFloat32(value.y);
1266
+ output.writeFloat32(value.z);
1267
+ },
1268
+ float32x4(output, _, value) {
1269
+ output.writeFloat32(value.x);
1270
+ output.writeFloat32(value.y);
1271
+ output.writeFloat32(value.z);
1272
+ output.writeFloat32(value.w);
1273
+ },
1274
+ uint32(output, _, value) {
1275
+ output.writeUint32(value);
1276
+ },
1277
+ uint32x2(output, _, value) {
1278
+ output.writeUint32(value.x);
1279
+ output.writeUint32(value.y);
1280
+ },
1281
+ uint32x3(output, _, value) {
1282
+ output.writeUint32(value.x);
1283
+ output.writeUint32(value.y);
1284
+ output.writeUint32(value.z);
1285
+ },
1286
+ uint32x4(output, _, value) {
1287
+ output.writeUint32(value.x);
1288
+ output.writeUint32(value.y);
1289
+ output.writeUint32(value.z);
1290
+ output.writeUint32(value.w);
1291
+ },
1292
+ sint32(output, _, value) {
1293
+ output.writeInt32(value);
1294
+ },
1295
+ sint32x2(output, _, value) {
1296
+ output.writeInt32(value.x);
1297
+ output.writeInt32(value.y);
1298
+ },
1299
+ sint32x3(output, _, value) {
1300
+ output.writeInt32(value.x);
1301
+ output.writeInt32(value.y);
1302
+ output.writeInt32(value.z);
1303
+ },
1304
+ sint32x4(output, _, value) {
1305
+ output.writeInt32(value.x);
1306
+ output.writeInt32(value.y);
1307
+ output.writeInt32(value.z);
1308
+ output.writeInt32(value.w);
1309
+ },
1310
+ "unorm10-10-10-2"(output, _, value) {
1311
+ let packed = 0;
1312
+ packed |= (value.x * 1023 & 1023) << 22;
1313
+ packed |= (value.x * 1023 & 1023) << 12;
1314
+ packed |= (value.y * 1023 & 1023) << 2;
1315
+ packed |= value.z * 3 & 3;
1316
+ output.writeUint32(packed);
1317
+ },
1318
+ "unorm8x4-bgra"(output, _, value) {
1319
+ output.writeUint8(value.z * 255);
1320
+ output.writeUint8(value.y * 255);
1321
+ output.writeUint8(value.x * 255);
1322
+ output.writeUint8(value.w * 255);
1323
+ },
1324
+ disarray(output, schema, value) {
1325
+ var _a, _b;
1326
+ const alignment = alignmentOf(schema);
1327
+ alignIO_default(output, alignment);
1328
+ const beginning = output.currentByteOffset;
1329
+ for (let i = 0; i < Math.min(schema.elementCount, value.length); i++) {
1330
+ alignIO_default(output, alignment);
1331
+ (_b = dataWriters[(_a = schema.elementType) == null ? void 0 : _a.type]) == null ? void 0 : _b.call(
1332
+ dataWriters,
1333
+ output,
1334
+ schema.elementType,
1335
+ value[i]
1336
+ );
1337
+ }
1338
+ output.seekTo(beginning + sizeOf(schema));
1339
+ },
1340
+ unstruct(output, schema, value) {
1341
+ var _a;
1342
+ for (const [key, property] of Object.entries(schema.propTypes)) {
1343
+ (_a = dataWriters[property.type]) == null ? void 0 : _a.call(dataWriters, output, property, value[key]);
1344
+ }
1345
+ },
1346
+ "loose-decorated"(output, schema, value) {
1347
+ var _a;
1348
+ const alignment = customAlignmentOf(schema);
1349
+ alignIO_default(output, alignment);
1350
+ const beginning = output.currentByteOffset;
1351
+ const writer = dataWriters[(_a = schema.inner) == null ? void 0 : _a.type];
1352
+ writer == null ? void 0 : writer(output, schema.inner, value);
1353
+ output.seekTo(beginning + sizeOf(schema));
1354
+ return value;
1355
+ }
1356
+ };
1357
+ function writeData(output, schema, value) {
1358
+ const writer = dataWriters[schema.type];
1359
+ if (!writer) {
1360
+ throw new Error(`Cannot write data of type '${schema.type}'.`);
1361
+ }
1362
+ writer(output, schema, value);
1363
+ }
1364
+ var dataReaders = {
1365
+ bool(input) {
1366
+ return input.readBool();
1367
+ },
1368
+ f32(input) {
1369
+ return input.readFloat32();
1370
+ },
1371
+ f16(input) {
1372
+ return input.readFloat16();
1373
+ },
1374
+ i32(input) {
1375
+ return input.readInt32();
1376
+ },
1377
+ u32(input) {
1378
+ return input.readUint32();
1379
+ },
1380
+ vec2f(input) {
1381
+ return vec2f(input.readFloat32(), input.readFloat32());
1382
+ },
1383
+ vec3f(input) {
1384
+ return vec3f(input.readFloat32(), input.readFloat32(), input.readFloat32());
1385
+ },
1386
+ vec4f(input) {
1387
+ return vec4f(
1388
+ input.readFloat32(),
1389
+ input.readFloat32(),
1390
+ input.readFloat32(),
1391
+ input.readFloat32()
1392
+ );
1393
+ },
1394
+ vec2h(input) {
1395
+ return vec2h(input.readFloat16(), input.readFloat16());
1396
+ },
1397
+ vec3h(input) {
1398
+ return vec3h(input.readFloat16(), input.readFloat16(), input.readFloat16());
1399
+ },
1400
+ vec4h(input) {
1401
+ return vec4h(
1402
+ input.readFloat16(),
1403
+ input.readFloat16(),
1404
+ input.readFloat16(),
1405
+ input.readFloat16()
1406
+ );
1407
+ },
1408
+ vec2i(input) {
1409
+ return vec2i(input.readInt32(), input.readInt32());
1410
+ },
1411
+ vec3i(input) {
1412
+ return vec3i(input.readInt32(), input.readInt32(), input.readInt32());
1413
+ },
1414
+ vec4i(input) {
1415
+ return vec4i(
1416
+ input.readInt32(),
1417
+ input.readInt32(),
1418
+ input.readInt32(),
1419
+ input.readInt32()
1420
+ );
1421
+ },
1422
+ vec2u(input) {
1423
+ return vec2u(input.readUint32(), input.readUint32());
1424
+ },
1425
+ vec3u(input) {
1426
+ return vec3u(input.readUint32(), input.readUint32(), input.readUint32());
1427
+ },
1428
+ vec4u(input) {
1429
+ return vec4u(
1430
+ input.readUint32(),
1431
+ input.readUint32(),
1432
+ input.readUint32(),
1433
+ input.readUint32()
1434
+ );
1435
+ },
1436
+ mat2x2f(input) {
1437
+ return mat2x2f(
1438
+ input.readFloat32(),
1439
+ input.readFloat32(),
1440
+ input.readFloat32(),
1441
+ input.readFloat32()
1442
+ );
1443
+ },
1444
+ mat3x3f(input) {
1445
+ const skipOneAfter = () => {
1446
+ const value = input.readFloat32();
1447
+ input.readFloat32();
1448
+ return value;
1449
+ };
1450
+ return mat3x3f(
1451
+ input.readFloat32(),
1452
+ input.readFloat32(),
1453
+ skipOneAfter(),
1454
+ //
1455
+ input.readFloat32(),
1456
+ input.readFloat32(),
1457
+ skipOneAfter(),
1458
+ //
1459
+ input.readFloat32(),
1460
+ input.readFloat32(),
1461
+ skipOneAfter()
1462
+ );
1463
+ },
1464
+ mat4x4f(input) {
1465
+ return mat4x4f(
1466
+ input.readFloat32(),
1467
+ input.readFloat32(),
1468
+ input.readFloat32(),
1469
+ input.readFloat32(),
1470
+ //
1471
+ input.readFloat32(),
1472
+ input.readFloat32(),
1473
+ input.readFloat32(),
1474
+ input.readFloat32(),
1475
+ //
1476
+ input.readFloat32(),
1477
+ input.readFloat32(),
1478
+ input.readFloat32(),
1479
+ input.readFloat32(),
1480
+ //
1481
+ input.readFloat32(),
1482
+ input.readFloat32(),
1483
+ input.readFloat32(),
1484
+ input.readFloat32()
1485
+ );
1486
+ },
1487
+ struct(input, schema) {
1488
+ const alignment = alignmentOf(schema);
1489
+ alignIO_default(input, alignment);
1490
+ const result = {};
1491
+ for (const [key, property] of Object.entries(schema.propTypes)) {
1492
+ alignIO_default(input, alignmentOf(property));
1493
+ result[key] = readData(input, property);
1494
+ }
1495
+ alignIO_default(input, alignment);
1496
+ return result;
1497
+ },
1498
+ array(input, schema) {
1499
+ if (schema.elementCount === 0) {
1500
+ throw new Error("Cannot read using a runtime-sized schema.");
1501
+ }
1502
+ const alignment = alignmentOf(schema);
1503
+ const elements = [];
1504
+ for (let i = 0; i < schema.elementCount; i++) {
1505
+ alignIO_default(input, alignment);
1506
+ const elementType = schema.elementType;
1507
+ const value = readData(input, elementType);
1508
+ elements.push(value);
1509
+ }
1510
+ alignIO_default(input, alignment);
1511
+ return elements;
1512
+ },
1513
+ ptrFn() {
1514
+ throw new Error("Pointers are not host-shareable");
1515
+ },
1516
+ atomic(input, schema) {
1517
+ return readData(input, schema.inner);
1518
+ },
1519
+ decorated(input, schema) {
1520
+ const alignment = customAlignmentOf(schema);
1521
+ alignIO_default(input, alignment);
1522
+ const beginning = input.currentByteOffset;
1523
+ const value = readData(input, schema.inner);
1524
+ input.seekTo(beginning + sizeOf(schema));
1525
+ return value;
1526
+ },
1527
+ // Loose Types
1528
+ uint8: (i) => i.readUint8(),
1529
+ uint8x2: (i) => vec2u(i.readUint8(), i.readUint8()),
1530
+ uint8x4: (i) => vec4u(i.readUint8(), i.readUint8(), i.readUint8(), i.readUint8()),
1531
+ sint8: (i) => i.readInt8(),
1532
+ sint8x2: (i) => {
1533
+ return vec2i(i.readInt8(), i.readInt8());
1534
+ },
1535
+ sint8x4: (i) => vec4i(i.readInt8(), i.readInt8(), i.readInt8(), i.readInt8()),
1536
+ unorm8: (i) => i.readUint8() / 255,
1537
+ unorm8x2: (i) => vec2f(i.readUint8() / 255, i.readUint8() / 255),
1538
+ unorm8x4: (i) => vec4f(
1539
+ i.readUint8() / 255,
1540
+ i.readUint8() / 255,
1541
+ i.readUint8() / 255,
1542
+ i.readUint8() / 255
1543
+ ),
1544
+ snorm8: (i) => (i.readUint8() - 128) / 127,
1545
+ snorm8x2: (i) => vec2f((i.readUint8() - 128) / 127, (i.readUint8() - 128) / 127),
1546
+ snorm8x4: (i) => vec4f(
1547
+ (i.readUint8() - 128) / 127,
1548
+ (i.readUint8() - 128) / 127,
1549
+ (i.readUint8() - 128) / 127,
1550
+ (i.readUint8() - 128) / 127
1551
+ ),
1552
+ uint16: (i) => i.readUint16(),
1553
+ uint16x2: (i) => vec2u(i.readUint16(), i.readUint16()),
1554
+ uint16x4: (i) => vec4u(i.readUint16(), i.readUint16(), i.readUint16(), i.readUint16()),
1555
+ sint16: (i) => i.readInt16(),
1556
+ sint16x2: (i) => vec2i(i.readInt16(), i.readInt16()),
1557
+ sint16x4: (i) => vec4i(i.readInt16(), i.readInt16(), i.readInt16(), i.readInt16()),
1558
+ unorm16: (i) => i.readUint16() / 65535,
1559
+ unorm16x2: (i) => vec2f(i.readUint16() / 65535, i.readUint16() / 65535),
1560
+ unorm16x4: (i) => vec4f(
1561
+ i.readUint16() / 65535,
1562
+ i.readUint16() / 65535,
1563
+ i.readUint16() / 65535,
1564
+ i.readUint16() / 65535
1565
+ ),
1566
+ snorm16: (i) => (i.readUint16() - 32768) / 32767,
1567
+ snorm16x2: (i) => vec2f(dataReaders.snorm16(i), dataReaders.snorm16(i)),
1568
+ snorm16x4: (i) => vec4f(
1569
+ dataReaders.snorm16(i),
1570
+ dataReaders.snorm16(i),
1571
+ dataReaders.snorm16(i),
1572
+ dataReaders.snorm16(i)
1573
+ ),
1574
+ float16(i) {
1575
+ return i.readFloat16();
1576
+ },
1577
+ float16x2: (i) => vec2f(i.readFloat16(), i.readFloat16()),
1578
+ float16x4: (i) => vec4f(i.readFloat16(), i.readFloat16(), i.readFloat16(), i.readFloat16()),
1579
+ float32: (i) => i.readFloat32(),
1580
+ float32x2: (i) => vec2f(i.readFloat32(), i.readFloat32()),
1581
+ float32x3: (i) => vec3f(i.readFloat32(), i.readFloat32(), i.readFloat32()),
1582
+ float32x4: (i) => vec4f(i.readFloat32(), i.readFloat32(), i.readFloat32(), i.readFloat32()),
1583
+ uint32: (i) => i.readUint32(),
1584
+ uint32x2: (i) => vec2u(i.readUint32(), i.readUint32()),
1585
+ uint32x3: (i) => vec3u(i.readUint32(), i.readUint32(), i.readUint32()),
1586
+ uint32x4: (i) => vec4u(i.readUint32(), i.readUint32(), i.readUint32(), i.readUint32()),
1587
+ sint32: (i) => i.readInt32(),
1588
+ sint32x2: (i) => vec2i(i.readInt32(), i.readInt32()),
1589
+ sint32x3: (i) => vec3i(i.readInt32(), i.readInt32(), i.readInt32()),
1590
+ sint32x4: (i) => vec4i(i.readInt32(), i.readInt32(), i.readInt32(), i.readInt32()),
1591
+ "unorm10-10-10-2"(i) {
1592
+ const packed = i.readUint32();
1593
+ const r = (packed >> 22) / 1023;
1594
+ const g = (packed >> 12 & 1023) / 1023;
1595
+ const b = (packed >> 2 & 1023) / 1023;
1596
+ const a = (packed & 3) / 3;
1597
+ return vec4f(r, g, b, a);
1598
+ },
1599
+ "unorm8x4-bgra"(i) {
1600
+ const b = i.readByte() / 255;
1601
+ const g = i.readByte() / 255;
1602
+ const r = i.readByte() / 255;
1603
+ const a = i.readByte() / 255;
1604
+ return vec4f(r, g, b, a);
1605
+ },
1606
+ unstruct(input, schema) {
1607
+ const result = {};
1608
+ for (const [key, property] of Object.entries(schema.propTypes)) {
1609
+ result[key] = readData(input, property);
1610
+ }
1611
+ return result;
1612
+ },
1613
+ disarray(input, schema) {
1614
+ const alignment = alignmentOf(schema);
1615
+ const elements = [];
1616
+ for (let i = 0; i < schema.elementCount; i++) {
1617
+ alignIO_default(input, alignment);
1618
+ elements.push(readData(input, schema.elementType));
1619
+ }
1620
+ alignIO_default(input, alignment);
1621
+ return elements;
1622
+ },
1623
+ "loose-decorated"(input, schema) {
1624
+ alignIO_default(input, customAlignmentOf(schema));
1625
+ const beginning = input.currentByteOffset;
1626
+ const value = readData(input, schema.inner);
1627
+ input.seekTo(beginning + sizeOf(schema));
1628
+ return value;
1629
+ }
1630
+ };
1631
+ function readData(input, schema) {
1632
+ const reader = dataReaders[schema.type];
1633
+ if (!reader) {
1634
+ throw new Error(`Cannot read data of type '${schema.type}'.`);
1635
+ }
1636
+ return reader(input, schema);
1637
+ }
1638
+
1639
+ // src/core/buffer/buffer.ts
1640
+ function INTERNAL_createBuffer(group, typeSchema, initialOrBuffer) {
1641
+ if (!isWgslData(typeSchema)) {
1642
+ return new TgpuBufferImpl(group, typeSchema, initialOrBuffer, [
1643
+ "storage",
1644
+ "uniform"
1645
+ ]);
1646
+ }
1647
+ return new TgpuBufferImpl(group, typeSchema, initialOrBuffer);
1648
+ }
1649
+ function isBuffer(value) {
1650
+ return value.resourceType === "buffer";
1651
+ }
1652
+ function isUsableAsUniform(buffer) {
1653
+ return !!buffer.usableAsUniform;
1654
+ }
1655
+ function isUsableAsVertex(buffer) {
1656
+ return !!buffer.usableAsVertex;
1657
+ }
1658
+ var TgpuBufferImpl = class {
1659
+ constructor(_group, dataType, initialOrBuffer, _disallowedUsages) {
1660
+ this._group = _group;
1661
+ this.dataType = dataType;
1662
+ this.initialOrBuffer = initialOrBuffer;
1663
+ this._disallowedUsages = _disallowedUsages;
1664
+ __publicField(this, "resourceType", "buffer");
1665
+ __publicField(this, "flags", GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC);
1666
+ __publicField(this, "_buffer", null);
1667
+ __publicField(this, "_ownBuffer");
1668
+ __publicField(this, "_destroyed", false);
1669
+ __publicField(this, "_label");
1670
+ __publicField(this, "initial");
1671
+ __publicField(this, "usableAsUniform", false);
1672
+ __publicField(this, "usableAsStorage", false);
1673
+ __publicField(this, "usableAsVertex", false);
1674
+ if (isGPUBuffer(initialOrBuffer)) {
1675
+ this._ownBuffer = false;
1676
+ this._buffer = initialOrBuffer;
1677
+ } else {
1678
+ this._ownBuffer = true;
1679
+ this.initial = initialOrBuffer;
1680
+ }
1681
+ }
1682
+ get label() {
1683
+ return this._label;
1684
+ }
1685
+ get buffer() {
1686
+ var _a;
1687
+ const device = this._group.device;
1688
+ if (this._destroyed) {
1689
+ throw new Error("This buffer has been destroyed");
1690
+ }
1691
+ if (!this._buffer) {
1692
+ this._buffer = device.createBuffer({
1693
+ size: sizeOf(this.dataType),
1694
+ usage: this.flags,
1695
+ mappedAtCreation: !!this.initial,
1696
+ label: (_a = this.label) != null ? _a : "<unnamed>"
1697
+ });
1698
+ if (this.initial) {
1699
+ const writer = new BufferWriter(this._buffer.getMappedRange());
1700
+ writeData(writer, this.dataType, this.initial);
1701
+ this._buffer.unmap();
1702
+ }
1703
+ }
1704
+ return this._buffer;
1705
+ }
1706
+ get destroyed() {
1707
+ return this._destroyed;
1708
+ }
1709
+ $name(label) {
1710
+ this._label = label;
1711
+ if (this._buffer) {
1712
+ this._buffer.label = label;
1713
+ }
1714
+ return this;
1715
+ }
1716
+ $usage(...usages) {
1717
+ var _a;
1718
+ for (const usage of usages) {
1719
+ if ((_a = this._disallowedUsages) == null ? void 0 : _a.includes(usage)) {
1720
+ throw new Error(
1721
+ `Buffer of type ${this.dataType} cannot be used as ${usage}`
1722
+ );
1723
+ }
1724
+ this.flags |= usage === "uniform" ? GPUBufferUsage.UNIFORM : 0;
1725
+ this.flags |= usage === "storage" ? GPUBufferUsage.STORAGE : 0;
1726
+ this.flags |= usage === "vertex" ? GPUBufferUsage.VERTEX : 0;
1727
+ this.usableAsUniform = this.usableAsUniform || usage === "uniform";
1728
+ this.usableAsStorage = this.usableAsStorage || usage === "storage";
1729
+ this.usableAsVertex = this.usableAsVertex || usage === "vertex";
1730
+ }
1731
+ return this;
1732
+ }
1733
+ $addFlags(flags) {
1734
+ if (!this._ownBuffer) {
1735
+ throw new Error(
1736
+ "Cannot add flags to a buffer that is not managed by TypeGPU."
1737
+ );
1738
+ }
1739
+ if (flags & GPUBufferUsage.MAP_READ) {
1740
+ this.flags = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
1741
+ return this;
1742
+ }
1743
+ if (flags & GPUBufferUsage.MAP_WRITE) {
1744
+ this.flags = GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE;
1745
+ return this;
1746
+ }
1747
+ this.flags |= flags;
1748
+ return this;
1749
+ }
1750
+ write(data) {
1751
+ const gpuBuffer = this.buffer;
1752
+ const device = this._group.device;
1753
+ if (gpuBuffer.mapState === "mapped") {
1754
+ const mapped = gpuBuffer.getMappedRange();
1755
+ writeData(new BufferWriter(mapped), this.dataType, data);
1756
+ return;
1757
+ }
1758
+ const size = sizeOf(this.dataType);
1759
+ this._group.flush();
1760
+ const hostBuffer = new ArrayBuffer(size);
1761
+ writeData(new BufferWriter(hostBuffer), this.dataType, data);
1762
+ device.queue.writeBuffer(gpuBuffer, 0, hostBuffer, 0, size);
1763
+ }
1764
+ copyFrom(srcBuffer) {
1765
+ if (this.buffer.mapState === "mapped") {
1766
+ throw new Error("Cannot copy to a mapped buffer.");
1767
+ }
1768
+ const size = sizeOf(this.dataType);
1769
+ const encoder = this._group.commandEncoder;
1770
+ encoder.copyBufferToBuffer(srcBuffer.buffer, 0, this.buffer, 0, size);
1771
+ }
1772
+ async read() {
1773
+ this._group.flush();
1774
+ const gpuBuffer = this.buffer;
1775
+ const device = this._group.device;
1776
+ if (gpuBuffer.mapState === "mapped") {
1777
+ const mapped = gpuBuffer.getMappedRange();
1778
+ return readData(new BufferReader(mapped), this.dataType);
1779
+ }
1780
+ if (gpuBuffer.usage & GPUBufferUsage.MAP_READ) {
1781
+ await gpuBuffer.mapAsync(GPUMapMode.READ);
1782
+ const mapped = gpuBuffer.getMappedRange();
1783
+ const res2 = readData(new BufferReader(mapped), this.dataType);
1784
+ gpuBuffer.unmap();
1785
+ return res2;
1786
+ }
1787
+ const stagingBuffer = device.createBuffer({
1788
+ size: sizeOf(this.dataType),
1789
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
1790
+ });
1791
+ const commandEncoder = device.createCommandEncoder();
1792
+ commandEncoder.copyBufferToBuffer(
1793
+ gpuBuffer,
1794
+ 0,
1795
+ stagingBuffer,
1796
+ 0,
1797
+ sizeOf(this.dataType)
1798
+ );
1799
+ device.queue.submit([commandEncoder.finish()]);
1800
+ await device.queue.onSubmittedWorkDone();
1801
+ await stagingBuffer.mapAsync(GPUMapMode.READ, 0, sizeOf(this.dataType));
1802
+ const res = readData(
1803
+ new BufferReader(stagingBuffer.getMappedRange()),
1804
+ this.dataType
1805
+ );
1806
+ stagingBuffer.unmap();
1807
+ stagingBuffer.destroy();
1808
+ return res;
1809
+ }
1810
+ destroy() {
1811
+ var _a;
1812
+ if (this._destroyed) {
1813
+ return;
1814
+ }
1815
+ this._destroyed = true;
1816
+ if (this._ownBuffer) {
1817
+ (_a = this._buffer) == null ? void 0 : _a.destroy();
1818
+ }
1819
+ }
1820
+ toString() {
1821
+ var _a;
1822
+ return `buffer:${(_a = this._label) != null ? _a : "<unnamed>"}`;
1823
+ }
1824
+ };
1825
+
1826
+ // src/extension.ts
1827
+ function isUsableAsStorage(value) {
1828
+ return !!(value == null ? void 0 : value.usableAsStorage);
1829
+ }
1830
+ var NotStorageError = class _NotStorageError extends Error {
1831
+ constructor(value) {
1832
+ var _a;
1833
+ super(
1834
+ `Resource '${(_a = value.label) != null ? _a : "<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`
1835
+ );
1836
+ Object.setPrototypeOf(this, _NotStorageError.prototype);
1837
+ }
1838
+ };
1839
+
1840
+ // src/core/buffer/bufferUsage.ts
1841
+ var usageToVarTemplateMap = {
1842
+ uniform: "uniform",
1843
+ mutable: "storage, read_write",
1844
+ readonly: "storage, read"
1845
+ };
1846
+ var TgpuFixedBufferImpl = class {
1847
+ constructor(usage, buffer) {
1848
+ this.usage = usage;
1849
+ this.buffer = buffer;
1850
+ /** Type-token, not available at runtime */
1851
+ __publicField(this, "~repr");
1852
+ __publicField(this, "resourceType", "buffer-usage");
1853
+ }
1854
+ get label() {
1855
+ return this.buffer.label;
1856
+ }
1857
+ $name(label) {
1858
+ this.buffer.$name(label);
1859
+ }
1860
+ "~resolve"(ctx) {
1861
+ const id = ctx.names.makeUnique(this.label);
1862
+ const { group, binding } = ctx.allocateFixedEntry(
1863
+ this.usage === "uniform" ? { uniform: this.buffer.dataType } : { storage: this.buffer.dataType, access: this.usage },
1864
+ this.buffer
1865
+ );
1866
+ const usage = usageToVarTemplateMap[this.usage];
1867
+ ctx.addDeclaration(
1868
+ `@group(${group}) @binding(${binding}) var<${usage}> ${id}: ${ctx.resolve(
1869
+ this.buffer.dataType
1870
+ )};`
1871
+ );
1872
+ return id;
1873
+ }
1874
+ toString() {
1875
+ var _a;
1876
+ return `${this.usage}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
1877
+ }
1878
+ get value() {
1879
+ if (!inGPUMode()) {
1880
+ throw new Error(`Cannot access buffer's value directly in JS.`);
1881
+ }
1882
+ return new Proxy(
1883
+ {
1884
+ "~resolve": (ctx) => ctx.resolve(this),
1885
+ toString: () => {
1886
+ var _a;
1887
+ return `.value:${(_a = this.label) != null ? _a : "<unnamed>"}`;
1888
+ }
1889
+ },
1890
+ valueProxyHandler
1891
+ );
1892
+ }
1893
+ };
1894
+ var TgpuLaidOutBufferImpl = class {
1895
+ constructor(usage, dataType, _membership) {
1896
+ this.usage = usage;
1897
+ this.dataType = dataType;
1898
+ this._membership = _membership;
1899
+ /** Type-token, not available at runtime */
1900
+ __publicField(this, "~repr");
1901
+ __publicField(this, "resourceType", "buffer-usage");
1902
+ }
1903
+ get label() {
1904
+ return this._membership.key;
1905
+ }
1906
+ "~resolve"(ctx) {
1907
+ const id = ctx.names.makeUnique(this.label);
1908
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
1909
+ const usage = usageToVarTemplateMap[this.usage];
1910
+ ctx.addDeclaration(
1911
+ `@group(${group}) @binding(${this._membership.idx}) var<${usage}> ${id}: ${ctx.resolve(this.dataType)};`
1912
+ );
1913
+ return id;
1914
+ }
1915
+ toString() {
1916
+ var _a;
1917
+ return `${this.usage}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
1918
+ }
1919
+ get value() {
1920
+ if (!inGPUMode()) {
1921
+ throw new Error(`Cannot access buffer's value directly in JS.`);
1922
+ }
1923
+ return new Proxy(
1924
+ {
1925
+ "~resolve": (ctx) => ctx.resolve(this),
1926
+ toString: () => {
1927
+ var _a;
1928
+ return `.value:${(_a = this.label) != null ? _a : "<unnamed>"}`;
1929
+ }
1930
+ },
1931
+ valueProxyHandler
1932
+ );
1933
+ }
1934
+ };
1935
+ var mutableUsageMap = /* @__PURE__ */ new WeakMap();
1936
+ function asMutable(buffer) {
1937
+ if (!isUsableAsStorage(buffer)) {
1938
+ throw new Error(
1939
+ `Cannot pass ${buffer} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`
1940
+ );
1941
+ }
1942
+ let usage = mutableUsageMap.get(buffer);
1943
+ if (!usage) {
1944
+ usage = new TgpuFixedBufferImpl("mutable", buffer);
1945
+ mutableUsageMap.set(buffer, usage);
1946
+ }
1947
+ return usage;
1948
+ }
1949
+ var readonlyUsageMap = /* @__PURE__ */ new WeakMap();
1950
+ function asReadonly(buffer) {
1951
+ if (!isUsableAsStorage(buffer)) {
1952
+ throw new Error(
1953
+ `Cannot pass ${buffer} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`
1954
+ );
1955
+ }
1956
+ let usage = readonlyUsageMap.get(buffer);
1957
+ if (!usage) {
1958
+ usage = new TgpuFixedBufferImpl("readonly", buffer);
1959
+ readonlyUsageMap.set(buffer, usage);
1960
+ }
1961
+ return usage;
1962
+ }
1963
+ var uniformUsageMap = /* @__PURE__ */ new WeakMap();
1964
+ function asUniform(buffer) {
1965
+ if (!isUsableAsUniform(buffer)) {
1966
+ throw new Error(
1967
+ `Cannot pass ${buffer} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`
1968
+ );
1969
+ }
1970
+ let usage = uniformUsageMap.get(buffer);
1971
+ if (!usage) {
1972
+ usage = new TgpuFixedBufferImpl("uniform", buffer);
1973
+ uniformUsageMap.set(buffer, usage);
1974
+ }
1975
+ return usage;
1976
+ }
1977
+
1978
+ // src/core/sampler/sampler.ts
1979
+ function sampler(props) {
1980
+ return new TgpuFixedSamplerImpl(props);
1981
+ }
1982
+ function comparisonSampler(props) {
1983
+ return new TgpuFixedComparisonSamplerImpl(props);
1984
+ }
1985
+ function isSampler(resource) {
1986
+ return (resource == null ? void 0 : resource.resourceType) === "sampler";
1987
+ }
1988
+ function isComparisonSampler(resource) {
1989
+ return (resource == null ? void 0 : resource.resourceType) === "sampler-comparison";
1990
+ }
1991
+ var TgpuLaidOutSamplerImpl = class {
1992
+ constructor(_membership) {
1993
+ this._membership = _membership;
1994
+ __publicField(this, "resourceType", "sampler");
1995
+ }
1996
+ get label() {
1997
+ return this._membership.key;
1998
+ }
1999
+ "~resolve"(ctx) {
2000
+ const id = ctx.names.makeUnique(this.label);
2001
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
2002
+ ctx.addDeclaration(
2003
+ `@group(${group}) @binding(${this._membership.idx}) var ${id}: sampler;`
2004
+ );
2005
+ return id;
2006
+ }
2007
+ toString() {
2008
+ var _a;
2009
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2010
+ }
2011
+ };
2012
+ var TgpuLaidOutComparisonSamplerImpl = class {
2013
+ constructor(_membership) {
2014
+ this._membership = _membership;
2015
+ __publicField(this, "resourceType", "sampler-comparison");
2016
+ }
2017
+ get label() {
2018
+ return this._membership.key;
2019
+ }
2020
+ "~resolve"(ctx) {
2021
+ const id = ctx.names.makeUnique(this.label);
2022
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
2023
+ ctx.addDeclaration(
2024
+ `@group(${group}) @binding(${this._membership.idx}) var ${id}: sampler_comparison;`
2025
+ );
2026
+ return id;
2027
+ }
2028
+ toString() {
2029
+ var _a;
2030
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2031
+ }
2032
+ };
2033
+ var TgpuFixedSamplerImpl = class {
2034
+ constructor(_props) {
2035
+ this._props = _props;
2036
+ __publicField(this, "resourceType", "sampler");
2037
+ __publicField(this, "_label");
2038
+ __publicField(this, "_filtering");
2039
+ this._filtering = _props.minFilter === "linear" || _props.magFilter === "linear" || _props.mipmapFilter === "linear";
2040
+ }
2041
+ get label() {
2042
+ return this._label;
2043
+ }
2044
+ $name(label) {
2045
+ this._label = label;
2046
+ return this;
2047
+ }
2048
+ "~resolve"(ctx) {
2049
+ const id = ctx.names.makeUnique(this._label);
2050
+ const { group, binding } = ctx.allocateFixedEntry(
2051
+ {
2052
+ sampler: this._filtering ? "filtering" : "non-filtering"
2053
+ },
2054
+ this
2055
+ );
2056
+ ctx.addDeclaration(
2057
+ `@group(${group}) @binding(${binding}) var ${id}: sampler;`
2058
+ );
2059
+ return id;
2060
+ }
2061
+ toString() {
2062
+ var _a;
2063
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2064
+ }
2065
+ };
2066
+ var TgpuFixedComparisonSamplerImpl = class {
2067
+ constructor(_props) {
2068
+ this._props = _props;
2069
+ __publicField(this, "resourceType", "sampler-comparison");
2070
+ __publicField(this, "_label");
2071
+ }
2072
+ get label() {
2073
+ return this._label;
2074
+ }
2075
+ $name(label) {
2076
+ this._label = label;
2077
+ return this;
2078
+ }
2079
+ "~resolve"(ctx) {
2080
+ const id = ctx.names.makeUnique(this.label);
2081
+ const { group, binding } = ctx.allocateFixedEntry(
2082
+ { sampler: "comparison" },
2083
+ this
2084
+ );
2085
+ ctx.addDeclaration(
2086
+ `@group(${group}) @binding(${binding}) var ${id}: sampler_comparison;`
2087
+ );
2088
+ return id;
2089
+ }
2090
+ toString() {
2091
+ var _a;
2092
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2093
+ }
2094
+ };
2095
+
2096
+ // src/core/texture/externalTexture.ts
2097
+ var TgpuExternalTextureImpl = class {
2098
+ constructor(_membership) {
2099
+ this._membership = _membership;
2100
+ __publicField(this, "resourceType", "external-texture");
2101
+ }
2102
+ get label() {
2103
+ return this._membership.key;
2104
+ }
2105
+ "~resolve"(ctx) {
2106
+ const id = ctx.names.makeUnique(this.label);
2107
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
2108
+ ctx.addDeclaration(
2109
+ `@group(${group}) @binding(${this._membership.idx}) var ${id}: texture_external;`
2110
+ );
2111
+ return id;
2112
+ }
2113
+ toString() {
2114
+ var _a;
2115
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2116
+ }
2117
+ };
2118
+
2119
+ // src/core/texture/textureFormats.ts
2120
+ var texelFormatToChannelType = {
2121
+ r8unorm: f32,
2122
+ r8snorm: f32,
2123
+ r8uint: u32,
2124
+ r8sint: i32,
2125
+ r16uint: u32,
2126
+ r16sint: i32,
2127
+ r16float: f32,
2128
+ rg8unorm: f32,
2129
+ rg8snorm: f32,
2130
+ rg8uint: u32,
2131
+ rg8sint: i32,
2132
+ r32uint: u32,
2133
+ r32sint: i32,
2134
+ r32float: f32,
2135
+ rg16uint: u32,
2136
+ rg16sint: i32,
2137
+ rg16float: f32,
2138
+ rgba8unorm: f32,
2139
+ "rgba8unorm-srgb": f32,
2140
+ rgba8snorm: f32,
2141
+ rgba8uint: u32,
2142
+ rgba8sint: i32,
2143
+ bgra8unorm: f32,
2144
+ "bgra8unorm-srgb": f32,
2145
+ rgb9e5ufloat: f32,
2146
+ rgb10a2uint: u32,
2147
+ rgb10a2unorm: f32,
2148
+ rg11b10ufloat: f32,
2149
+ rg32uint: u32,
2150
+ rg32sint: i32,
2151
+ rg32float: f32,
2152
+ rgba16uint: u32,
2153
+ rgba16sint: i32,
2154
+ rgba16float: f32,
2155
+ rgba32uint: u32,
2156
+ rgba32sint: i32,
2157
+ rgba32float: f32,
2158
+ stencil8: f32,
2159
+ // NOTE: Honestly have no idea if this is right
2160
+ depth16unorm: f32,
2161
+ depth24plus: f32,
2162
+ // NOTE: Honestly have no idea if this is right
2163
+ "depth24plus-stencil8": f32,
2164
+ // NOTE: Honestly have no idea if this is right
2165
+ depth32float: f32,
2166
+ "depth32float-stencil8": f32,
2167
+ "bc1-rgba-unorm": f32,
2168
+ "bc1-rgba-unorm-srgb": f32,
2169
+ "bc2-rgba-unorm": f32,
2170
+ "bc2-rgba-unorm-srgb": f32,
2171
+ "bc3-rgba-unorm": f32,
2172
+ "bc3-rgba-unorm-srgb": f32,
2173
+ "bc4-r-unorm": f32,
2174
+ "bc4-r-snorm": f32,
2175
+ "bc5-rg-unorm": f32,
2176
+ "bc5-rg-snorm": f32,
2177
+ "bc6h-rgb-ufloat": f32,
2178
+ "bc6h-rgb-float": f32,
2179
+ "bc7-rgba-unorm": f32,
2180
+ "bc7-rgba-unorm-srgb": f32,
2181
+ "etc2-rgb8unorm": f32,
2182
+ "etc2-rgb8unorm-srgb": f32,
2183
+ "etc2-rgb8a1unorm": f32,
2184
+ "etc2-rgb8a1unorm-srgb": f32,
2185
+ "etc2-rgba8unorm": f32,
2186
+ "etc2-rgba8unorm-srgb": f32,
2187
+ "eac-r11unorm": f32,
2188
+ "eac-r11snorm": f32,
2189
+ "eac-rg11unorm": f32,
2190
+ "eac-rg11snorm": f32,
2191
+ "astc-4x4-unorm": f32,
2192
+ "astc-4x4-unorm-srgb": f32,
2193
+ "astc-5x4-unorm": f32,
2194
+ "astc-5x4-unorm-srgb": f32,
2195
+ "astc-5x5-unorm": f32,
2196
+ "astc-5x5-unorm-srgb": f32,
2197
+ "astc-6x5-unorm": f32,
2198
+ "astc-6x5-unorm-srgb": f32,
2199
+ "astc-6x6-unorm": f32,
2200
+ "astc-6x6-unorm-srgb": f32,
2201
+ "astc-8x5-unorm": f32,
2202
+ "astc-8x5-unorm-srgb": f32,
2203
+ "astc-8x6-unorm": f32,
2204
+ "astc-8x6-unorm-srgb": f32,
2205
+ "astc-8x8-unorm": f32,
2206
+ "astc-8x8-unorm-srgb": f32,
2207
+ "astc-10x5-unorm": f32,
2208
+ "astc-10x5-unorm-srgb": f32,
2209
+ "astc-10x6-unorm": f32,
2210
+ "astc-10x6-unorm-srgb": f32,
2211
+ "astc-10x8-unorm": f32,
2212
+ "astc-10x8-unorm-srgb": f32,
2213
+ "astc-10x10-unorm": f32,
2214
+ "astc-10x10-unorm-srgb": f32,
2215
+ "astc-12x10-unorm": f32,
2216
+ "astc-12x10-unorm-srgb": f32,
2217
+ "astc-12x12-unorm": f32,
2218
+ "astc-12x12-unorm-srgb": f32
2219
+ };
2220
+ var texelFormatToDataType = {
2221
+ rgba8unorm: vec4f,
2222
+ rgba8snorm: vec4f,
2223
+ rgba8uint: vec4u,
2224
+ rgba8sint: vec4i,
2225
+ rgba16uint: vec4u,
2226
+ rgba16sint: vec4i,
2227
+ rgba16float: vec4f,
2228
+ r32uint: vec4u,
2229
+ r32sint: vec4i,
2230
+ r32float: vec4f,
2231
+ rg32uint: vec4u,
2232
+ rg32sint: vec4i,
2233
+ rg32float: vec4f,
2234
+ rgba32uint: vec4u,
2235
+ rgba32sint: vec4i,
2236
+ rgba32float: vec4f,
2237
+ bgra8unorm: vec4f
2238
+ };
2239
+ var channelKindToFormat = {
2240
+ f32: "float",
2241
+ u32: "uint",
2242
+ i32: "sint"
2243
+ };
2244
+ var channelFormatToSchema = {
2245
+ float: f32,
2246
+ "unfilterable-float": f32,
2247
+ uint: u32,
2248
+ sint: i32,
2249
+ depth: f32
2250
+ // I guess?
2251
+ };
2252
+
2253
+ // src/core/texture/texture.ts
2254
+ function INTERNAL_createTexture(props, branch) {
2255
+ return new TgpuTextureImpl(
2256
+ props,
2257
+ branch
2258
+ );
2259
+ }
2260
+ function isTexture(value) {
2261
+ return (value == null ? void 0 : value.resourceType) === "texture";
2262
+ }
2263
+ function isStorageTextureView(value) {
2264
+ return (value == null ? void 0 : value.resourceType) === "texture-storage-view";
2265
+ }
2266
+ function isSampledTextureView(value) {
2267
+ return (value == null ? void 0 : value.resourceType) === "texture-sampled-view";
2268
+ }
2269
+ var accessMap = {
2270
+ mutable: "read_write",
2271
+ readonly: "read",
2272
+ writeonly: "write"
2273
+ };
2274
+ var TgpuTextureImpl = class {
2275
+ constructor(props, _branch) {
2276
+ this.props = props;
2277
+ this._branch = _branch;
2278
+ __publicField(this, "resourceType", "texture");
2279
+ __publicField(this, "usableAsSampled", false);
2280
+ __publicField(this, "usableAsStorage", false);
2281
+ __publicField(this, "usableAsRender", false);
2282
+ __publicField(this, "_destroyed", false);
2283
+ __publicField(this, "_label");
2284
+ __publicField(this, "_flags", GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC);
2285
+ __publicField(this, "_texture", null);
2286
+ }
2287
+ get label() {
2288
+ return this._label;
2289
+ }
2290
+ $name(label) {
2291
+ this._label = label;
2292
+ return this;
2293
+ }
2294
+ /**
2295
+ * NOTE: Internal use only, use this and you'll get fired. Use `root.unwrap` instead.
2296
+ */
2297
+ unwrap() {
2298
+ var _a, _b, _c, _d, _e;
2299
+ if (this._destroyed) {
2300
+ throw new Error("This texture has been destroyed");
2301
+ }
2302
+ if (!this._texture) {
2303
+ this._texture = this._branch.device.createTexture({
2304
+ label: (_a = this._label) != null ? _a : "<unnamed>",
2305
+ format: this.props.format,
2306
+ size: this.props.size,
2307
+ usage: this._flags,
2308
+ dimension: (_b = this.props.dimension) != null ? _b : "2d",
2309
+ viewFormats: (_c = this.props.viewFormats) != null ? _c : [],
2310
+ mipLevelCount: (_d = this.props.mipLevelCount) != null ? _d : 1,
2311
+ sampleCount: (_e = this.props.sampleCount) != null ? _e : 1
2312
+ });
2313
+ }
2314
+ return this._texture;
2315
+ }
2316
+ $usage(...usages) {
2317
+ const hasStorage = usages.includes("storage");
2318
+ const hasSampled = usages.includes("sampled");
2319
+ const hasRender = usages.includes("render");
2320
+ this._flags |= hasSampled ? GPUTextureUsage.TEXTURE_BINDING : 0;
2321
+ this._flags |= hasStorage ? GPUTextureUsage.STORAGE_BINDING : 0;
2322
+ this._flags |= hasRender ? GPUTextureUsage.RENDER_ATTACHMENT : 0;
2323
+ this.usableAsStorage || (this.usableAsStorage = hasStorage);
2324
+ this.usableAsSampled || (this.usableAsSampled = hasSampled);
2325
+ this.usableAsRender || (this.usableAsRender = hasRender);
2326
+ return this;
2327
+ }
2328
+ createView(access, params) {
2329
+ if (access === "sampled") {
2330
+ return this._asSampled(params);
2331
+ }
2332
+ const storageParams = params;
2333
+ switch (access) {
2334
+ case "mutable":
2335
+ return this._asMutable(storageParams);
2336
+ case "readonly":
2337
+ return this._asReadonly(storageParams);
2338
+ case "writeonly":
2339
+ return this._asWriteonly(storageParams);
2340
+ }
2341
+ }
2342
+ _asStorage(params, access) {
2343
+ var _a;
2344
+ if (!this.usableAsStorage) {
2345
+ throw new Error("Unusable as storage");
2346
+ }
2347
+ const format = (_a = params == null ? void 0 : params.format) != null ? _a : this.props.format;
2348
+ const type = texelFormatToDataType[format];
2349
+ invariant(!!type, `Unsupported storage texture format: ${format}`);
2350
+ return new TgpuFixedStorageTextureImpl(params != null ? params : {}, access, this);
2351
+ }
2352
+ _asReadonly(params) {
2353
+ return this._asStorage(params, "readonly");
2354
+ }
2355
+ _asWriteonly(params) {
2356
+ return this._asStorage(params, "writeonly");
2357
+ }
2358
+ _asMutable(params) {
2359
+ return this._asStorage(params, "mutable");
2360
+ }
2361
+ _asSampled(params) {
2362
+ var _a;
2363
+ if (!this.usableAsSampled) {
2364
+ throw new Error("Unusable as sampled");
2365
+ }
2366
+ const format = (_a = params == null ? void 0 : params.format) != null ? _a : this.props.format;
2367
+ const type = texelFormatToDataType[format];
2368
+ if (!type) {
2369
+ throw new Error(`Unsupported storage texture format: ${format}`);
2370
+ }
2371
+ return new TgpuFixedSampledTextureImpl(params, this);
2372
+ }
2373
+ destroy() {
2374
+ var _a;
2375
+ if (this._destroyed) {
2376
+ return;
2377
+ }
2378
+ this._destroyed = true;
2379
+ (_a = this._texture) == null ? void 0 : _a.destroy();
2380
+ }
2381
+ };
2382
+ var dimensionToCodeMap = {
2383
+ "1d": "1d",
2384
+ "2d": "2d",
2385
+ "2d-array": "2d_array",
2386
+ cube: "cube",
2387
+ "cube-array": "cube_array",
2388
+ "3d": "3d"
2389
+ };
2390
+ var TgpuFixedStorageTextureImpl = class {
2391
+ constructor(props, access, _texture) {
2392
+ this.access = access;
2393
+ this._texture = _texture;
2394
+ __publicField(this, "resourceType", "texture-storage-view");
2395
+ __publicField(this, "texelDataType");
2396
+ __publicField(this, "dimension");
2397
+ __publicField(this, "_view");
2398
+ __publicField(this, "_format");
2399
+ var _a, _b, _c;
2400
+ this.dimension = (_b = (_a = props == null ? void 0 : props.dimension) != null ? _a : _texture.props.dimension) != null ? _b : "2d";
2401
+ this._format = (_c = props == null ? void 0 : props.format) != null ? _c : _texture.props.format;
2402
+ this.texelDataType = texelFormatToDataType[this._format];
2403
+ }
2404
+ get label() {
2405
+ return this._texture.label;
2406
+ }
2407
+ $name(label) {
2408
+ this._texture.$name(label);
2409
+ return this;
2410
+ }
2411
+ unwrap() {
2412
+ var _a;
2413
+ if (!this._view) {
2414
+ this._view = this._texture.unwrap().createView({
2415
+ label: `${(_a = this.label) != null ? _a : "<unnamed>"} - View`,
2416
+ format: this._format,
2417
+ dimension: this.dimension
2418
+ });
2419
+ }
2420
+ return this._view;
2421
+ }
2422
+ "~resolve"(ctx) {
2423
+ const id = ctx.names.makeUnique(this.label);
2424
+ const { group, binding } = ctx.allocateFixedEntry(
2425
+ {
2426
+ storageTexture: this._format,
2427
+ access: this.access,
2428
+ viewDimension: this.dimension
2429
+ },
2430
+ this
2431
+ );
2432
+ const type = `texture_storage_${dimensionToCodeMap[this.dimension]}`;
2433
+ ctx.addDeclaration(
2434
+ `@group(${group}) @binding(${binding}) var ${id}: ${type}<${this._format}, ${accessMap[this.access]}>;`
2435
+ );
2436
+ return id;
2437
+ }
2438
+ toString() {
2439
+ var _a;
2440
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2441
+ }
2442
+ };
2443
+ var TgpuLaidOutStorageTextureImpl = class {
2444
+ constructor(_format, dimension, access, _membership) {
2445
+ this._format = _format;
2446
+ this.dimension = dimension;
2447
+ this.access = access;
2448
+ this._membership = _membership;
2449
+ __publicField(this, "resourceType", "texture-storage-view");
2450
+ __publicField(this, "texelDataType");
2451
+ this.texelDataType = texelFormatToDataType[this._format];
2452
+ }
2453
+ get label() {
2454
+ return this._membership.key;
2455
+ }
2456
+ "~resolve"(ctx) {
2457
+ const id = ctx.names.makeUnique(this.label);
2458
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
2459
+ const type = `texture_storage_${dimensionToCodeMap[this.dimension]}`;
2460
+ ctx.addDeclaration(
2461
+ `@group(${group}) @binding(${this._membership.idx}) var ${id}: ${type}<${this._format}, ${accessMap[this.access]}>;`
2462
+ );
2463
+ return id;
2464
+ }
2465
+ toString() {
2466
+ var _a;
2467
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2468
+ }
2469
+ };
2470
+ var TgpuFixedSampledTextureImpl = class {
2471
+ constructor(_props, _texture) {
2472
+ this._props = _props;
2473
+ this._texture = _texture;
2474
+ __publicField(this, "resourceType", "texture-sampled-view");
2475
+ __publicField(this, "channelDataType");
2476
+ __publicField(this, "dimension");
2477
+ __publicField(this, "_format");
2478
+ __publicField(this, "_view");
2479
+ var _a, _b, _c;
2480
+ this.dimension = (_b = (_a = _props == null ? void 0 : _props.dimension) != null ? _a : _texture.props.dimension) != null ? _b : "2d";
2481
+ this._format = (_c = _props == null ? void 0 : _props.format) != null ? _c : _texture.props.format;
2482
+ this.channelDataType = texelFormatToChannelType[this._format];
2483
+ }
2484
+ get label() {
2485
+ return this._texture.label;
2486
+ }
2487
+ $name(label) {
2488
+ this._texture.$name(label);
2489
+ return this;
2490
+ }
2491
+ unwrap() {
2492
+ var _a;
2493
+ if (!this._view) {
2494
+ this._view = this._texture.unwrap().createView(__spreadValues({
2495
+ label: `${(_a = this.label) != null ? _a : "<unnamed>"} - View`
2496
+ }, this._props));
2497
+ }
2498
+ return this._view;
2499
+ }
2500
+ "~resolve"(ctx) {
2501
+ var _a;
2502
+ const id = ctx.names.makeUnique(this.label);
2503
+ const multisampled = ((_a = this._texture.props.sampleCount) != null ? _a : 1) > 1;
2504
+ const { group, binding } = ctx.allocateFixedEntry(
2505
+ {
2506
+ texture: channelKindToFormat[this.channelDataType.type],
2507
+ viewDimension: this.dimension,
2508
+ multisampled
2509
+ },
2510
+ this
2511
+ );
2512
+ const type = multisampled ? "texture_multisampled_2d" : `texture_${dimensionToCodeMap[this.dimension]}`;
2513
+ ctx.addDeclaration(
2514
+ `@group(${group}) @binding(${binding}) var ${id}: ${type}<${ctx.resolve(this.channelDataType)}>;`
2515
+ );
2516
+ return id;
2517
+ }
2518
+ toString() {
2519
+ var _a;
2520
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2521
+ }
2522
+ };
2523
+ var TgpuLaidOutSampledTextureImpl = class {
2524
+ constructor(sampleType, dimension, _multisampled, _membership) {
2525
+ this.dimension = dimension;
2526
+ this._multisampled = _multisampled;
2527
+ this._membership = _membership;
2528
+ __publicField(this, "resourceType", "texture-sampled-view");
2529
+ __publicField(this, "channelDataType");
2530
+ this.channelDataType = channelFormatToSchema[sampleType];
2531
+ }
2532
+ get label() {
2533
+ return this._membership.key;
2534
+ }
2535
+ "~resolve"(ctx) {
2536
+ const id = ctx.names.makeUnique(this.label);
2537
+ const group = ctx.allocateLayoutEntry(this._membership.layout);
2538
+ const type = this._multisampled ? "texture_multisampled_2d" : `texture_${dimensionToCodeMap[this.dimension]}`;
2539
+ ctx.addDeclaration(
2540
+ `@group(${group}) @binding(${this._membership.idx}) var ${id}: ${type}<${ctx.resolve(this.channelDataType)}>;`
2541
+ );
2542
+ return id;
2543
+ }
2544
+ toString() {
2545
+ var _a;
2546
+ return `${this.resourceType}:${(_a = this.label) != null ? _a : "<unnamed>"}`;
2547
+ }
2548
+ };
2549
+
2550
+ // src/core/texture/usageExtension.ts
2551
+ function isUsableAsSampled(value) {
2552
+ return !!(value == null ? void 0 : value.usableAsSampled);
2553
+ }
2554
+ function isUsableAsRender(value) {
2555
+ return !!(value == null ? void 0 : value.usableAsRender);
2556
+ }
2557
+ var NotSampledError = class _NotSampledError extends Error {
2558
+ constructor(value) {
2559
+ var _a;
2560
+ super(
2561
+ `Resource '${(_a = value.label) != null ? _a : "<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`
2562
+ );
2563
+ Object.setPrototypeOf(this, _NotSampledError.prototype);
2564
+ }
2565
+ };
2566
+
2567
+ // src/tgpuBindGroupLayout.ts
2568
+ function bindGroupLayout(entries) {
2569
+ return new TgpuBindGroupLayoutImpl(entries);
2570
+ }
2571
+ function isBindGroupLayout(value) {
2572
+ return !!value && value.resourceType === "bind-group-layout";
2573
+ }
2574
+ function isBindGroup(value) {
2575
+ return !!value && value.resourceType === "bind-group";
2576
+ }
2577
+ var MissingBindingError = class _MissingBindingError extends Error {
2578
+ constructor(groupLabel, key) {
2579
+ super(
2580
+ `Bind group '${groupLabel != null ? groupLabel : "<unnamed>"}' is missing a required binding '${key}'`
2581
+ );
2582
+ Object.setPrototypeOf(this, _MissingBindingError.prototype);
2583
+ }
2584
+ };
2585
+ var DEFAULT_MUTABLE_VISIBILITY = ["compute"];
2586
+ var DEFAULT_READONLY_VISIBILITY = [
2587
+ "compute",
2588
+ "vertex",
2589
+ "fragment"
2590
+ ];
2591
+ var TgpuBindGroupLayoutImpl = class {
2592
+ constructor(entries) {
2593
+ this.entries = entries;
2594
+ __publicField(this, "_label");
2595
+ __publicField(this, "_index");
2596
+ __publicField(this, "resourceType", "bind-group-layout");
2597
+ __publicField(this, "bound", {});
2598
+ var _a, _b, _c, _d, _e;
2599
+ let idx = 0;
2600
+ for (const [key, entry] of Object.entries(entries)) {
2601
+ if (entry === null) {
2602
+ idx++;
2603
+ continue;
2604
+ }
2605
+ const membership = { idx, key, layout: this };
2606
+ if ("uniform" in entry) {
2607
+ this.bound[key] = new TgpuLaidOutBufferImpl(
2608
+ "uniform",
2609
+ entry.uniform,
2610
+ membership
2611
+ );
2612
+ }
2613
+ if ("storage" in entry) {
2614
+ const dataType = "type" in entry.storage ? entry.storage : entry.storage(0);
2615
+ this.bound[key] = new TgpuLaidOutBufferImpl(
2616
+ (_a = entry.access) != null ? _a : "readonly",
2617
+ dataType,
2618
+ membership
2619
+ );
2620
+ }
2621
+ if ("texture" in entry) {
2622
+ this.bound[key] = new TgpuLaidOutSampledTextureImpl(
2623
+ entry.texture,
2624
+ (_b = entry.viewDimension) != null ? _b : "2d",
2625
+ (_c = entry.multisampled) != null ? _c : false,
2626
+ membership
2627
+ );
2628
+ }
2629
+ if ("storageTexture" in entry) {
2630
+ this.bound[key] = new TgpuLaidOutStorageTextureImpl(
2631
+ entry.storageTexture,
2632
+ (_d = entry.viewDimension) != null ? _d : "2d",
2633
+ (_e = entry.access) != null ? _e : "writeonly",
2634
+ membership
2635
+ );
2636
+ }
2637
+ if ("externalTexture" in entry) {
2638
+ this.bound[key] = new TgpuExternalTextureImpl(membership);
2639
+ }
2640
+ if ("sampler" in entry) {
2641
+ if (entry.sampler === "comparison") {
2642
+ this.bound[key] = new TgpuLaidOutComparisonSamplerImpl(
2643
+ membership
2644
+ );
2645
+ } else {
2646
+ this.bound[key] = new TgpuLaidOutSamplerImpl(membership);
2647
+ }
2648
+ }
2649
+ idx++;
2650
+ }
2651
+ }
2652
+ get label() {
2653
+ return this._label;
2654
+ }
2655
+ get index() {
2656
+ return this._index;
2657
+ }
2658
+ $name(label) {
2659
+ this._label = label;
2660
+ return this;
2661
+ }
2662
+ $idx(index) {
2663
+ this._index = index;
2664
+ return this;
2665
+ }
2666
+ unwrap(unwrapper) {
2667
+ var _a;
2668
+ const unwrapped = unwrapper.device.createBindGroupLayout({
2669
+ label: (_a = this.label) != null ? _a : "<unnamed>",
2670
+ entries: Object.values(this.entries).map((entry, idx) => {
2671
+ var _a2, _b, _c, _d;
2672
+ if (entry === null) {
2673
+ return null;
2674
+ }
2675
+ let visibility = entry.visibility;
2676
+ const binding = {
2677
+ binding: idx,
2678
+ visibility: 0
2679
+ };
2680
+ if ("uniform" in entry) {
2681
+ visibility = visibility != null ? visibility : DEFAULT_READONLY_VISIBILITY;
2682
+ binding.buffer = {
2683
+ type: "uniform"
2684
+ };
2685
+ } else if ("storage" in entry) {
2686
+ visibility = visibility != null ? visibility : entry.access === "mutable" ? DEFAULT_MUTABLE_VISIBILITY : DEFAULT_READONLY_VISIBILITY;
2687
+ binding.buffer = {
2688
+ type: entry.access === "mutable" ? "storage" : "read-only-storage"
2689
+ };
2690
+ } else if ("sampler" in entry) {
2691
+ visibility = visibility != null ? visibility : DEFAULT_READONLY_VISIBILITY;
2692
+ binding.sampler = {
2693
+ type: entry.sampler
2694
+ };
2695
+ } else if ("texture" in entry) {
2696
+ visibility = visibility != null ? visibility : DEFAULT_READONLY_VISIBILITY;
2697
+ binding.texture = {
2698
+ sampleType: entry.texture,
2699
+ viewDimension: (_a2 = entry.viewDimension) != null ? _a2 : "2d",
2700
+ multisampled: (_b = entry.multisampled) != null ? _b : false
2701
+ };
2702
+ } else if ("storageTexture" in entry) {
2703
+ const access = (_c = entry.access) != null ? _c : "writeonly";
2704
+ visibility = visibility != null ? visibility : access === "readonly" ? DEFAULT_READONLY_VISIBILITY : DEFAULT_MUTABLE_VISIBILITY;
2705
+ binding.storageTexture = {
2706
+ format: entry.storageTexture,
2707
+ access: {
2708
+ mutable: "read-write",
2709
+ readonly: "read-only",
2710
+ writeonly: "write-only"
2711
+ }[access],
2712
+ viewDimension: (_d = entry.viewDimension) != null ? _d : "2d"
2713
+ };
2714
+ } else if ("externalTexture" in entry) {
2715
+ visibility = visibility != null ? visibility : DEFAULT_READONLY_VISIBILITY;
2716
+ binding.externalTexture = {};
2717
+ }
2718
+ if (visibility == null ? void 0 : visibility.includes("compute")) {
2719
+ binding.visibility |= GPUShaderStage.COMPUTE;
2720
+ }
2721
+ if (visibility == null ? void 0 : visibility.includes("vertex")) {
2722
+ binding.visibility |= GPUShaderStage.VERTEX;
2723
+ }
2724
+ if (visibility == null ? void 0 : visibility.includes("fragment")) {
2725
+ binding.visibility |= GPUShaderStage.FRAGMENT;
2726
+ }
2727
+ return binding;
2728
+ }).filter((v) => v !== null)
2729
+ });
2730
+ return unwrapped;
2731
+ }
2732
+ populate(entries) {
2733
+ return new TgpuBindGroupImpl(this, entries);
2734
+ }
2735
+ };
2736
+ var TgpuBindGroupImpl = class {
2737
+ constructor(layout, entries) {
2738
+ this.layout = layout;
2739
+ this.entries = entries;
2740
+ __publicField(this, "resourceType", "bind-group");
2741
+ for (const key of Object.keys(layout.entries)) {
2742
+ if (layout.entries[key] !== null && !(key in entries)) {
2743
+ throw new MissingBindingError(layout.label, key);
2744
+ }
2745
+ }
2746
+ }
2747
+ unwrap(unwrapper) {
2748
+ var _a;
2749
+ const unwrapped = unwrapper.device.createBindGroup({
2750
+ label: (_a = this.layout.label) != null ? _a : "<unnamed>",
2751
+ layout: unwrapper.unwrap(this.layout),
2752
+ entries: Object.entries(this.layout.entries).map(([key, entry], idx) => {
2753
+ var _a2;
2754
+ if (entry === null) {
2755
+ return null;
2756
+ }
2757
+ const value = this.entries[key];
2758
+ if (value === void 0) {
2759
+ throw new Error(
2760
+ `'${key}' is a resource required to populate bind group layout '${(_a2 = this.layout.label) != null ? _a2 : "<unnamed>"}'.`
2761
+ );
2762
+ }
2763
+ if ("uniform" in entry) {
2764
+ let resource;
2765
+ if (isBuffer(value)) {
2766
+ if (!isUsableAsUniform(value)) {
2767
+ throw new NotUniformError(value);
2768
+ }
2769
+ resource = { buffer: unwrapper.unwrap(value) };
2770
+ } else {
2771
+ resource = { buffer: value };
2772
+ }
2773
+ return {
2774
+ binding: idx,
2775
+ resource
2776
+ };
2777
+ }
2778
+ if ("storage" in entry) {
2779
+ let resource;
2780
+ if (isBuffer(value)) {
2781
+ if (!isUsableAsStorage(value)) {
2782
+ throw new NotUniformError(value);
2783
+ }
2784
+ resource = { buffer: unwrapper.unwrap(value) };
2785
+ } else {
2786
+ resource = { buffer: value };
2787
+ }
2788
+ return {
2789
+ binding: idx,
2790
+ resource
2791
+ };
2792
+ }
2793
+ if ("texture" in entry) {
2794
+ let resource;
2795
+ if (isTexture(value)) {
2796
+ if (!isUsableAsSampled(value)) {
2797
+ throw new NotSampledError(value);
2798
+ }
2799
+ resource = unwrapper.unwrap(
2800
+ value.createView("sampled")
2801
+ );
2802
+ } else {
2803
+ resource = value;
2804
+ }
2805
+ return {
2806
+ binding: idx,
2807
+ resource
2808
+ };
2809
+ }
2810
+ if ("storageTexture" in entry) {
2811
+ let resource;
2812
+ if (isTexture(value)) {
2813
+ if (!isUsableAsStorage(value)) {
2814
+ throw new NotStorageError(value);
2815
+ }
2816
+ if (entry.access === "readonly") {
2817
+ resource = unwrapper.unwrap(
2818
+ value.createView("readonly")
2819
+ );
2820
+ } else if (entry.access === "mutable") {
2821
+ resource = unwrapper.unwrap(
2822
+ value.createView("mutable")
2823
+ );
2824
+ } else {
2825
+ resource = unwrapper.unwrap(
2826
+ value.createView("writeonly")
2827
+ );
2828
+ }
2829
+ } else {
2830
+ resource = value;
2831
+ }
2832
+ return {
2833
+ binding: idx,
2834
+ resource
2835
+ };
2836
+ }
2837
+ if ("externalTexture" in entry || "sampler" in entry) {
2838
+ return {
2839
+ binding: idx,
2840
+ resource: value
2841
+ };
2842
+ }
2843
+ throw new Error(
2844
+ `Malformed bind group entry: ${value} (${JSON.stringify(value)})`
2845
+ );
2846
+ }).filter((v) => v !== null)
2847
+ });
2848
+ return unwrapped;
2849
+ }
2850
+ };
2851
+
2852
+ // src/resolutionCtx.ts
2853
+ var CATCHALL_BIND_GROUP_IDX_MARKER = "#CATCHALL#";
2854
+ var ItemStateStack = class {
2855
+ constructor() {
2856
+ __publicField(this, "_stack", []);
2857
+ __publicField(this, "_itemDepth", 0);
2858
+ }
2859
+ get itemDepth() {
2860
+ return this._itemDepth;
2861
+ }
2862
+ get topItem() {
2863
+ const state = this._stack[this._stack.length - 1];
2864
+ if (!state || state.type !== "item") {
2865
+ throw new Error("Internal error, expected item layer to be on top.");
2866
+ }
2867
+ return state;
2868
+ }
2869
+ pushItem() {
2870
+ this._itemDepth++;
2871
+ this._stack.push({
2872
+ type: "item",
2873
+ usedSlots: /* @__PURE__ */ new Set()
2874
+ });
2875
+ }
2876
+ pushSlotBindings(pairs) {
2877
+ this._stack.push({
2878
+ type: "slotBinding",
2879
+ bindingMap: new WeakMap(pairs)
2880
+ });
2881
+ }
2882
+ pushFunctionScope(args, returnType, externalMap) {
2883
+ this._stack.push({
2884
+ type: "functionScope",
2885
+ args,
2886
+ returnType,
2887
+ externalMap
2888
+ });
2889
+ }
2890
+ pop() {
2891
+ const layer = this._stack.pop();
2892
+ if ((layer == null ? void 0 : layer.type) === "item") {
2893
+ this._itemDepth--;
2894
+ }
2895
+ }
2896
+ readSlot(slot2) {
2897
+ for (let i = this._stack.length - 1; i >= 0; --i) {
2898
+ const layer = this._stack[i];
2899
+ if ((layer == null ? void 0 : layer.type) === "item") {
2900
+ layer.usedSlots.add(slot2);
2901
+ } else if ((layer == null ? void 0 : layer.type) === "slotBinding") {
2902
+ const boundValue = layer.bindingMap.get(slot2);
2903
+ if (boundValue !== void 0) {
2904
+ return boundValue;
2905
+ }
2906
+ } else if ((layer == null ? void 0 : layer.type) === "functionScope" || (layer == null ? void 0 : layer.type) === "blockScope") {
2907
+ } else {
2908
+ throw new Error("Unknown layer type.");
2909
+ }
2910
+ }
2911
+ return slot2.defaultValue;
2912
+ }
2913
+ getResourceById(id) {
2914
+ for (let i = this._stack.length - 1; i >= 0; --i) {
2915
+ const layer = this._stack[i];
2916
+ if ((layer == null ? void 0 : layer.type) === "functionScope") {
2917
+ const arg = layer.args.find((a) => a.value === id);
2918
+ if (arg !== void 0) {
2919
+ return arg;
2920
+ }
2921
+ const external = layer.externalMap[id];
2922
+ if (external !== void 0) {
2923
+ return { value: external, dataType: UnknownData };
2924
+ }
2925
+ return void 0;
2926
+ }
2927
+ if ((layer == null ? void 0 : layer.type) === "blockScope") {
2928
+ const declarationType = layer.declarations.get(id);
2929
+ if (declarationType !== void 0) {
2930
+ return { value: id, dataType: declarationType };
2931
+ }
2932
+ } else {
2933
+ }
2934
+ }
2935
+ return void 0;
2936
+ }
2937
+ };
2938
+ var INDENT = [
2939
+ "",
2940
+ // 0
2941
+ " ",
2942
+ // 1
2943
+ " ",
2944
+ // 2
2945
+ " ",
2946
+ // 3
2947
+ " ",
2948
+ // 4
2949
+ " ",
2950
+ // 5
2951
+ " ",
2952
+ // 6
2953
+ " ",
2954
+ // 7
2955
+ " "
2956
+ // 8
2957
+ ];
2958
+ var N = INDENT.length - 1;
2959
+ var IndentController = class {
2960
+ constructor() {
2961
+ __publicField(this, "identLevel", 0);
2962
+ }
2963
+ get pre() {
2964
+ var _a;
2965
+ return (_a = INDENT[this.identLevel]) != null ? _a : INDENT[N].repeat(this.identLevel / N) + INDENT[this.identLevel % N];
2966
+ }
2967
+ indent() {
2968
+ const str = this.pre;
2969
+ this.identLevel++;
2970
+ return str;
2971
+ }
2972
+ dedent() {
2973
+ this.identLevel--;
2974
+ return this.pre;
2975
+ }
2976
+ };
2977
+ var ResolutionCtxImpl = class {
2978
+ constructor(opts) {
2979
+ __publicField(this, "_memoizedResolves", /* @__PURE__ */ new WeakMap());
2980
+ __publicField(this, "_memoizedDerived", /* @__PURE__ */ new WeakMap());
2981
+ __publicField(this, "_indentController", new IndentController());
2982
+ __publicField(this, "_jitTranspiler");
2983
+ __publicField(this, "_itemStateStack", new ItemStateStack());
2984
+ __publicField(this, "_declarations", []);
2985
+ // -- Bindings
2986
+ /**
2987
+ * A map from registered bind group layouts to random strings put in
2988
+ * place of their group index. The whole tree has to be traversed to
2989
+ * collect every use of a typed bind group layout, since they can be
2990
+ * explicitly imposed group indices, and they cannot collide.
2991
+ */
2992
+ __publicField(this, "bindGroupLayoutsToPlaceholderMap", /* @__PURE__ */ new Map());
2993
+ __publicField(this, "_nextFreeLayoutPlaceholderIdx", 0);
2994
+ __publicField(this, "fixedBindings", []);
2995
+ // --
2996
+ __publicField(this, "callStack", []);
2997
+ __publicField(this, "names");
2998
+ this.names = opts.names;
2999
+ this._jitTranspiler = opts.jitTranspiler;
3000
+ }
3001
+ get pre() {
3002
+ return this._indentController.pre;
3003
+ }
3004
+ indent() {
3005
+ return this._indentController.indent();
3006
+ }
3007
+ dedent() {
3008
+ return this._indentController.dedent();
3009
+ }
3010
+ getById(id) {
3011
+ var _a;
3012
+ return (_a = this._itemStateStack.getResourceById(id)) != null ? _a : {
3013
+ value: id,
3014
+ dataType: UnknownData
3015
+ };
3016
+ }
3017
+ transpileFn(fn2) {
3018
+ if (!this._jitTranspiler) {
3019
+ throw new Error(
3020
+ "Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time."
3021
+ );
3022
+ }
3023
+ return this._jitTranspiler.transpileFn(fn2);
3024
+ }
3025
+ fnToWgsl(options) {
3026
+ this._itemStateStack.pushFunctionScope(
3027
+ options.args,
3028
+ options.returnType,
3029
+ options.externalMap
3030
+ );
3031
+ const str = generateFunction(this, options.body);
3032
+ this._itemStateStack.pop();
3033
+ const argList = options.args.map(
3034
+ (arg) => `${arg.value}: ${this.resolve(arg.dataType)}`
3035
+ ).join(", ");
3036
+ return {
3037
+ head: options.returnType !== void 0 ? `(${argList}) -> ${this.resolve(options.returnType)}` : `(${argList})`,
3038
+ body: str
3039
+ };
3040
+ }
3041
+ addDeclaration(declaration) {
3042
+ this._declarations.push(declaration);
3043
+ }
3044
+ allocateLayoutEntry(layout) {
3045
+ const memoMap = this.bindGroupLayoutsToPlaceholderMap;
3046
+ let placeholderKey = memoMap.get(layout);
3047
+ if (!placeholderKey) {
3048
+ placeholderKey = `#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`;
3049
+ memoMap.set(layout, placeholderKey);
3050
+ }
3051
+ return placeholderKey;
3052
+ }
3053
+ allocateFixedEntry(layoutEntry, resource) {
3054
+ const binding = this.fixedBindings.length;
3055
+ this.fixedBindings.push({ layoutEntry, resource });
3056
+ return {
3057
+ group: CATCHALL_BIND_GROUP_IDX_MARKER,
3058
+ binding
3059
+ };
3060
+ }
3061
+ readSlot(slot2) {
3062
+ const value = this._itemStateStack.readSlot(slot2);
3063
+ if (value === void 0) {
3064
+ throw new MissingSlotValueError(slot2);
3065
+ }
3066
+ return value;
3067
+ }
3068
+ withSlots(pairs, callback) {
3069
+ this._itemStateStack.pushSlotBindings(pairs);
3070
+ try {
3071
+ return callback();
3072
+ } finally {
3073
+ this._itemStateStack.pop();
3074
+ }
3075
+ }
3076
+ unwrap(eventual) {
3077
+ if (isProviding(eventual)) {
3078
+ return this.withSlots(
3079
+ eventual["~providing"].pairs,
3080
+ () => this.unwrap(eventual["~providing"].inner)
3081
+ );
3082
+ }
3083
+ let maybeEventual = eventual;
3084
+ while (true) {
3085
+ if (isSlot(maybeEventual)) {
3086
+ maybeEventual = this.readSlot(maybeEventual);
3087
+ } else if (isDerived(maybeEventual)) {
3088
+ maybeEventual = this._getOrCompute(maybeEventual);
3089
+ } else {
3090
+ break;
3091
+ }
3092
+ }
3093
+ return maybeEventual;
3094
+ }
3095
+ _getOrCompute(derived2) {
3096
+ var _a;
3097
+ const instances = (_a = this._memoizedDerived.get(derived2)) != null ? _a : [];
3098
+ this._itemStateStack.pushItem();
3099
+ try {
3100
+ for (const instance of instances) {
3101
+ const slotValuePairs = [...instance.slotToValueMap.entries()];
3102
+ if (slotValuePairs.every(
3103
+ ([slot2, expectedValue]) => slot2.areEqual(this._itemStateStack.readSlot(slot2), expectedValue)
3104
+ )) {
3105
+ return instance.result;
3106
+ }
3107
+ }
3108
+ const result = derived2["~compute"]();
3109
+ const slotToValueMap = /* @__PURE__ */ new Map();
3110
+ for (const usedSlot of this._itemStateStack.topItem.usedSlots) {
3111
+ slotToValueMap.set(usedSlot, this._itemStateStack.readSlot(usedSlot));
3112
+ }
3113
+ instances.push({ slotToValueMap, result });
3114
+ this._memoizedDerived.set(derived2, instances);
3115
+ return result;
3116
+ } catch (err) {
3117
+ if (err instanceof ResolutionError) {
3118
+ throw err.appendToTrace(derived2);
3119
+ }
3120
+ throw new ResolutionError(err, [derived2]);
3121
+ } finally {
3122
+ this._itemStateStack.pop();
3123
+ }
3124
+ }
3125
+ /**
3126
+ * @param item The item whose resolution should be either retrieved from the cache (if there is a cache hit), or resolved.
3127
+ */
3128
+ _getOrInstantiate(item) {
3129
+ var _a;
3130
+ const instances = (_a = this._memoizedResolves.get(item)) != null ? _a : [];
3131
+ this._itemStateStack.pushItem();
3132
+ try {
3133
+ for (const instance of instances) {
3134
+ const slotValuePairs = [...instance.slotToValueMap.entries()];
3135
+ if (slotValuePairs.every(
3136
+ ([slot2, expectedValue]) => slot2.areEqual(this._itemStateStack.readSlot(slot2), expectedValue)
3137
+ )) {
3138
+ return instance.result;
3139
+ }
3140
+ }
3141
+ let result;
3142
+ if (isWgslData(item)) {
3143
+ result = resolveData(this, item);
3144
+ } else if (isDerived(item) || isSlot(item)) {
3145
+ result = this.resolve(this.unwrap(item));
3146
+ } else if (isSelfResolvable(item)) {
3147
+ result = item["~resolve"](this);
3148
+ } else {
3149
+ result = this.resolveValue(item);
3150
+ }
3151
+ const slotToValueMap = /* @__PURE__ */ new Map();
3152
+ for (const usedSlot of this._itemStateStack.topItem.usedSlots) {
3153
+ slotToValueMap.set(usedSlot, this._itemStateStack.readSlot(usedSlot));
3154
+ }
3155
+ instances.push({ slotToValueMap, result });
3156
+ this._memoizedResolves.set(item, instances);
3157
+ return result;
3158
+ } catch (err) {
3159
+ if (err instanceof ResolutionError) {
3160
+ throw err.appendToTrace(item);
3161
+ }
3162
+ throw new ResolutionError(err, [item]);
3163
+ } finally {
3164
+ this._itemStateStack.pop();
3165
+ }
3166
+ }
3167
+ resolve(item) {
3168
+ if (isProviding(item)) {
3169
+ return this.withSlots(
3170
+ item["~providing"].pairs,
3171
+ () => this.resolve(item["~providing"].inner)
3172
+ );
3173
+ }
3174
+ if (item && typeof item === "object" || typeof item === "function") {
3175
+ if (this._itemStateStack.itemDepth === 0) {
3176
+ const result = provideCtx(this, () => this._getOrInstantiate(item));
3177
+ return `${[...this._declarations].join("\n\n")}${result}`;
3178
+ }
3179
+ return this._getOrInstantiate(item);
3180
+ }
3181
+ return String(item);
3182
+ }
3183
+ resolveValue(value, schema) {
3184
+ if (isWgsl(value)) {
3185
+ return this.resolve(value);
3186
+ }
3187
+ if (schema && isWgslArray(schema)) {
3188
+ return `array(${value.map((element) => this.resolveValue(element, schema.elementType))})`;
3189
+ }
3190
+ if (Array.isArray(value)) {
3191
+ return `array(${value.map((element) => this.resolveValue(element))})`;
3192
+ }
3193
+ if (schema && isWgslStruct(schema)) {
3194
+ return `${this.resolve(schema)}(${Object.entries(schema.propTypes).map(([key, type_]) => this.resolveValue(value[key], type_))})`;
3195
+ }
3196
+ throw new Error(
3197
+ `Value ${value} (as json: ${JSON.stringify(value)}) of schema ${schema} is not resolvable to WGSL`
3198
+ );
3199
+ }
3200
+ };
3201
+ function resolve(item, options) {
3202
+ var _a;
3203
+ const ctx = new ResolutionCtxImpl(options);
3204
+ let code = ctx.resolve(item);
3205
+ const memoMap = ctx.bindGroupLayoutsToPlaceholderMap;
3206
+ const bindGroupLayouts = [];
3207
+ const takenIndices = new Set(
3208
+ [...memoMap.keys()].map((layout) => layout.index).filter((v) => v !== void 0)
3209
+ );
3210
+ const automaticIds = naturalsExcept(takenIndices);
3211
+ const layoutEntries = ctx.fixedBindings.map(
3212
+ (binding, idx) => [String(idx), binding.layoutEntry]
3213
+ );
3214
+ const createCatchallGroup = () => {
3215
+ const catchallIdx = automaticIds.next().value;
3216
+ const catchallLayout = bindGroupLayout(Object.fromEntries(layoutEntries));
3217
+ bindGroupLayouts[catchallIdx] = catchallLayout;
3218
+ code = code.replaceAll(CATCHALL_BIND_GROUP_IDX_MARKER, String(catchallIdx));
3219
+ return [
3220
+ catchallIdx,
3221
+ new TgpuBindGroupImpl(
3222
+ catchallLayout,
3223
+ Object.fromEntries(
3224
+ ctx.fixedBindings.map(
3225
+ (binding, idx) => (
3226
+ // biome-ignore lint/suspicious/noExplicitAny: <it's fine>
3227
+ [String(idx), binding.resource]
3228
+ )
3229
+ )
3230
+ )
3231
+ )
3232
+ ];
3233
+ };
3234
+ const catchall = layoutEntries.length > 0 ? createCatchallGroup() : null;
3235
+ for (const [layout, placeholder] of memoMap.entries()) {
3236
+ const idx = (_a = layout.index) != null ? _a : automaticIds.next().value;
3237
+ bindGroupLayouts[idx] = layout;
3238
+ code = code.replaceAll(placeholder, String(idx));
3239
+ }
3240
+ return {
3241
+ code,
3242
+ bindGroupLayouts,
3243
+ catchall
3244
+ };
3245
+ }
3246
+
3247
+ // src/core/resolve/tgpuResolve.ts
3248
+ function resolve2(options) {
3249
+ const {
3250
+ externals,
3251
+ template,
3252
+ names,
3253
+ unstable_jitTranspiler: jitTranspiler
3254
+ } = options;
3255
+ const dependencies = {};
3256
+ applyExternals(dependencies, externals != null ? externals : {});
3257
+ const resolutionObj = {
3258
+ "~resolve"(ctx) {
3259
+ return replaceExternalsInWgsl(ctx, dependencies, template != null ? template : "");
3260
+ },
3261
+ toString: () => "<root>"
3262
+ };
3263
+ const { code } = resolve(resolutionObj, {
3264
+ names: names === "strict" ? new StrictNameRegistry() : new RandomNameRegistry(),
3265
+ jitTranspiler
3266
+ });
3267
+ return code;
3268
+ }
3269
+
3270
+ // src/memo.ts
3271
+ var WeakMemo = class {
3272
+ constructor(_make) {
3273
+ this._make = _make;
3274
+ __publicField(this, "_map", /* @__PURE__ */ new WeakMap());
3275
+ }
3276
+ getOrMake(key, ...args) {
3277
+ if (this._map.has(key)) {
3278
+ return this._map.get(key);
3279
+ }
3280
+ const value = this._make(key, ...args);
3281
+ this._map.set(key, value);
3282
+ return value;
3283
+ }
3284
+ };
3285
+
3286
+ // src/core/pipeline/computePipeline.ts
3287
+ function INTERNAL_createComputePipeline(branch, slotBindings, entryFn) {
3288
+ return new TgpuComputePipelineImpl(
3289
+ new ComputePipelineCore(branch, slotBindings, entryFn),
3290
+ {}
3291
+ );
3292
+ }
3293
+ function isComputePipeline(value) {
3294
+ return (value == null ? void 0 : value.resourceType) === "compute-pipeline";
3295
+ }
3296
+ var TgpuComputePipelineImpl = class _TgpuComputePipelineImpl {
3297
+ constructor(_core, _priors) {
3298
+ this._core = _core;
3299
+ this._priors = _priors;
3300
+ __publicField(this, "resourceType", "compute-pipeline");
3301
+ }
3302
+ get label() {
3303
+ return this._core.label;
3304
+ }
3305
+ get rawPipeline() {
3306
+ return this._core.unwrap().pipeline;
3307
+ }
3308
+ with(bindGroupLayout2, bindGroup) {
3309
+ var _a;
3310
+ return new _TgpuComputePipelineImpl(this._core, {
3311
+ bindGroupLayoutMap: new Map([
3312
+ ...(_a = this._priors.bindGroupLayoutMap) != null ? _a : [],
3313
+ [bindGroupLayout2, bindGroup]
3314
+ ])
3315
+ });
3316
+ }
3317
+ dispatchWorkgroups(x, y, z) {
3318
+ const memo = this._core.unwrap();
3319
+ const { branch, label } = this._core;
3320
+ const pass = branch.commandEncoder.beginComputePass({
3321
+ label: label != null ? label : "<unnamed>"
3322
+ });
3323
+ pass.setPipeline(memo.pipeline);
3324
+ const missingBindGroups = new Set(memo.bindGroupLayouts);
3325
+ memo.bindGroupLayouts.forEach((layout, idx) => {
3326
+ var _a;
3327
+ if (memo.catchall && idx === memo.catchall[0]) {
3328
+ pass.setBindGroup(idx, branch.unwrap(memo.catchall[1]));
3329
+ missingBindGroups.delete(layout);
3330
+ } else {
3331
+ const bindGroup = (_a = this._priors.bindGroupLayoutMap) == null ? void 0 : _a.get(layout);
3332
+ if (bindGroup !== void 0) {
3333
+ missingBindGroups.delete(layout);
3334
+ pass.setBindGroup(idx, branch.unwrap(bindGroup));
3335
+ }
3336
+ }
3337
+ });
3338
+ if (missingBindGroups.size > 0) {
3339
+ throw new MissingBindGroupsError(missingBindGroups);
3340
+ }
3341
+ pass.dispatchWorkgroups(x, y, z);
3342
+ pass.end();
3343
+ }
3344
+ $name(label) {
3345
+ this._core.label = label;
3346
+ return this;
3347
+ }
3348
+ };
3349
+ var ComputePipelineCore = class {
3350
+ constructor(branch, _slotBindings, _entryFn) {
3351
+ this.branch = branch;
3352
+ this._slotBindings = _slotBindings;
3353
+ this._entryFn = _entryFn;
3354
+ __publicField(this, "label");
3355
+ __publicField(this, "_memo");
3356
+ }
3357
+ unwrap() {
3358
+ var _a, _b, _c, _d, _e;
3359
+ if (this._memo === void 0) {
3360
+ const device = this.branch.device;
3361
+ const { code, bindGroupLayouts, catchall } = resolve(
3362
+ {
3363
+ "~resolve": (ctx) => {
3364
+ ctx.withSlots(this._slotBindings, () => {
3365
+ ctx.resolve(this._entryFn);
3366
+ });
3367
+ return "";
3368
+ },
3369
+ toString: () => {
3370
+ var _a2;
3371
+ return `computePipeline:${(_a2 = this.label) != null ? _a2 : "<unnamed>"}`;
3372
+ }
3373
+ },
3374
+ {
3375
+ names: this.branch.nameRegistry,
3376
+ jitTranspiler: this.branch.jitTranspiler
3377
+ }
3378
+ );
3379
+ if (catchall !== null) {
3380
+ (_b = bindGroupLayouts[catchall[0]]) == null ? void 0 : _b.$name(
3381
+ `${(_a = this.label) != null ? _a : "<unnamed>"} - Automatic Bind Group & Layout`
3382
+ );
3383
+ }
3384
+ this._memo = {
3385
+ pipeline: device.createComputePipeline({
3386
+ label: (_c = this.label) != null ? _c : "<unnamed>",
3387
+ layout: device.createPipelineLayout({
3388
+ label: `${(_d = this.label) != null ? _d : "<unnamed>"} - Pipeline Layout`,
3389
+ bindGroupLayouts: bindGroupLayouts.map(
3390
+ (l) => this.branch.unwrap(l)
3391
+ )
3392
+ }),
3393
+ compute: {
3394
+ module: device.createShaderModule({
3395
+ label: `${(_e = this.label) != null ? _e : "<unnamed>"} - Shader`,
3396
+ code
3397
+ })
3398
+ }
3399
+ }),
3400
+ bindGroupLayouts,
3401
+ catchall
3402
+ };
3403
+ }
3404
+ return this._memo;
3405
+ }
3406
+ };
3407
+
3408
+ // src/core/vertexLayout/connectAttributesToShader.ts
3409
+ function isAttribute(value) {
3410
+ return typeof (value == null ? void 0 : value.format) === "string";
3411
+ }
3412
+ function connectAttributesToShader(shaderInputLayout, attributes) {
3413
+ var _a, _b;
3414
+ const usedVertexLayouts = [];
3415
+ if (isData(shaderInputLayout)) {
3416
+ if (!isAttribute(attributes)) {
3417
+ throw new Error(
3418
+ "Shader expected a single attribute, not a record of attributes to be passed in."
3419
+ );
3420
+ }
3421
+ usedVertexLayouts.push(attributes._layout);
3422
+ return {
3423
+ usedVertexLayouts,
3424
+ bufferDefinitions: [
3425
+ {
3426
+ arrayStride: attributes._layout.stride,
3427
+ stepMode: attributes._layout.stepMode,
3428
+ attributes: [
3429
+ {
3430
+ format: attributes.format,
3431
+ offset: attributes.offset,
3432
+ shaderLocation: (_a = getCustomLocation(shaderInputLayout)) != null ? _a : 0
3433
+ }
3434
+ ]
3435
+ }
3436
+ ]
3437
+ };
3438
+ }
3439
+ const bufferDefinitions = [];
3440
+ const layoutToAttribListMap = /* @__PURE__ */ new WeakMap();
3441
+ let nextShaderLocation = 0;
3442
+ for (const [key, member] of Object.entries(
3443
+ shaderInputLayout
3444
+ )) {
3445
+ if (isBuiltin(member)) {
3446
+ continue;
3447
+ }
3448
+ const matchingAttribute = attributes[key];
3449
+ if (!matchingAttribute) {
3450
+ throw new Error(
3451
+ `An attribute by the name of '${key}' was not provided to the shader.`
3452
+ );
3453
+ }
3454
+ const layout = matchingAttribute._layout;
3455
+ let attribList = layoutToAttribListMap.get(layout);
3456
+ if (!attribList) {
3457
+ usedVertexLayouts.push(layout);
3458
+ attribList = [];
3459
+ bufferDefinitions.push({
3460
+ arrayStride: layout.stride,
3461
+ stepMode: layout.stepMode,
3462
+ attributes: attribList
3463
+ });
3464
+ layoutToAttribListMap.set(layout, attribList);
3465
+ }
3466
+ nextShaderLocation = (_b = getCustomLocation(member)) != null ? _b : nextShaderLocation;
3467
+ attribList.push({
3468
+ format: matchingAttribute.format,
3469
+ offset: matchingAttribute.offset,
3470
+ shaderLocation: nextShaderLocation++
3471
+ });
3472
+ }
3473
+ return { usedVertexLayouts, bufferDefinitions };
3474
+ }
3475
+
3476
+ // src/core/vertexLayout/vertexLayout.ts
3477
+ function vertexLayout(schemaForCount, stepMode = "vertex") {
3478
+ return new TgpuVertexLayoutImpl(
3479
+ schemaForCount,
3480
+ stepMode
3481
+ );
3482
+ }
3483
+ function isVertexLayout(value) {
3484
+ return (value == null ? void 0 : value.resourceType) === "vertex-layout";
3485
+ }
3486
+ function dataToContainedAttribs(layout, data, offset) {
3487
+ if (isDecorated(data) || isLooseDecorated(data)) {
3488
+ return dataToContainedAttribs(
3489
+ layout,
3490
+ data.inner,
3491
+ roundUp(offset, customAlignmentOf(data))
3492
+ );
3493
+ }
3494
+ if (isWgslStruct(data)) {
3495
+ let memberOffset = offset;
3496
+ return Object.fromEntries(
3497
+ Object.entries(data.propTypes).map(([key, value]) => {
3498
+ memberOffset = roundUp(memberOffset, alignmentOf(value));
3499
+ const attrib = [
3500
+ key,
3501
+ dataToContainedAttribs(layout, value, memberOffset)
3502
+ ];
3503
+ memberOffset += sizeOf(value);
3504
+ return attrib;
3505
+ })
3506
+ );
3507
+ }
3508
+ if (isUnstruct(data)) {
3509
+ let memberOffset = offset;
3510
+ return Object.fromEntries(
3511
+ Object.entries(data.propTypes).map(([key, value]) => {
3512
+ memberOffset = roundUp(memberOffset, customAlignmentOf(value));
3513
+ const attrib = [
3514
+ key,
3515
+ dataToContainedAttribs(layout, value, memberOffset)
3516
+ ];
3517
+ memberOffset += sizeOf(value);
3518
+ return attrib;
3519
+ })
3520
+ );
3521
+ }
3522
+ if ("type" in data && typeof data.type === "string") {
3523
+ if (vertexFormats.includes(data.type)) {
3524
+ return {
3525
+ _layout: layout,
3526
+ // hidden property, used to determine which buffers to apply when executing the pipeline
3527
+ format: data.type,
3528
+ offset
3529
+ // biome-ignore lint/suspicious/noExplicitAny: <too many type shenanigans>
3530
+ };
3531
+ }
3532
+ const format = kindToDefaultFormatMap[data.type];
3533
+ if (format) {
3534
+ return {
3535
+ _layout: layout,
3536
+ // hidden property, used to determine which buffers to apply when executing the pipeline
3537
+ format,
3538
+ offset
3539
+ // biome-ignore lint/suspicious/noExplicitAny: <too many type shenanigans>
3540
+ };
3541
+ }
3542
+ }
3543
+ throw new Error(`Unsupported data used in vertex layout: ${String(data)}`);
3544
+ }
3545
+ var TgpuVertexLayoutImpl = class {
3546
+ constructor(schemaForCount, stepMode) {
3547
+ this.schemaForCount = schemaForCount;
3548
+ this.stepMode = stepMode;
3549
+ __publicField(this, "resourceType", "vertex-layout");
3550
+ __publicField(this, "stride");
3551
+ __publicField(this, "attrib");
3552
+ __publicField(this, "_label");
3553
+ const arraySchema = schemaForCount(0);
3554
+ this.stride = roundUp(
3555
+ sizeOf(arraySchema.elementType),
3556
+ alignmentOf(arraySchema)
3557
+ );
3558
+ this.attrib = dataToContainedAttribs(this, arraySchema.elementType, 0);
3559
+ }
3560
+ get label() {
3561
+ return this._label;
3562
+ }
3563
+ $name(label) {
3564
+ this._label = label;
3565
+ return this;
3566
+ }
3567
+ };
3568
+
3569
+ // src/core/pipeline/connectAttachmentToShader.ts
3570
+ function isColorAttachment(value) {
3571
+ return typeof (value == null ? void 0 : value.loadOp) === "string";
3572
+ }
3573
+ function connectAttachmentToShader(shaderOutputLayout, attachment) {
3574
+ if (isData(shaderOutputLayout)) {
3575
+ if (!isColorAttachment(attachment)) {
3576
+ throw new Error("Expected a single color attachment, not a record.");
3577
+ }
3578
+ return [attachment];
3579
+ }
3580
+ const result = [];
3581
+ for (const key of Object.keys(shaderOutputLayout)) {
3582
+ const matching = attachment[key];
3583
+ if (!matching) {
3584
+ throw new Error(
3585
+ `A color attachment by the name of '${key}' was not provided to the shader.`
3586
+ );
3587
+ }
3588
+ result.push(matching);
3589
+ }
3590
+ return result;
3591
+ }
3592
+
3593
+ // src/core/pipeline/connectTargetsToShader.ts
3594
+ function isColorTargetState(value) {
3595
+ return typeof (value == null ? void 0 : value.format) === "string";
3596
+ }
3597
+ function connectTargetsToShader(shaderOutputLayout, targets) {
3598
+ if (isData(shaderOutputLayout)) {
3599
+ if (!isColorTargetState(targets)) {
3600
+ throw new Error(
3601
+ "Expected a single color target configuration, not a record."
3602
+ );
3603
+ }
3604
+ return [targets];
3605
+ }
3606
+ const result = [];
3607
+ for (const key of Object.keys(shaderOutputLayout)) {
3608
+ const matchingTarget = targets[key];
3609
+ if (!matchingTarget) {
3610
+ throw new Error(
3611
+ `A color target by the name of '${key}' was not provided to the shader.`
3612
+ );
3613
+ }
3614
+ result.push(matchingTarget);
3615
+ }
3616
+ return result;
3617
+ }
3618
+
3619
+ // src/core/pipeline/renderPipeline.ts
3620
+ function INTERNAL_createRenderPipeline(options) {
3621
+ return new TgpuRenderPipelineImpl(new RenderPipelineCore(options), {});
3622
+ }
3623
+ var TgpuRenderPipelineImpl = class _TgpuRenderPipelineImpl {
3624
+ constructor(_core, _priors) {
3625
+ this._core = _core;
3626
+ this._priors = _priors;
3627
+ __publicField(this, "resourceType", "render-pipeline");
3628
+ }
3629
+ get label() {
3630
+ return this._core.label;
3631
+ }
3632
+ $name(label) {
3633
+ this._core.label = label;
3634
+ return this;
3635
+ }
3636
+ with(definition, resource) {
3637
+ var _a, _b;
3638
+ if (isBindGroupLayout(definition)) {
3639
+ return new _TgpuRenderPipelineImpl(this._core, __spreadProps(__spreadValues({}, this._priors), {
3640
+ bindGroupLayoutMap: new Map([
3641
+ ...(_a = this._priors.bindGroupLayoutMap) != null ? _a : [],
3642
+ [definition, resource]
3643
+ ])
3644
+ }));
3645
+ }
3646
+ if (isVertexLayout(definition)) {
3647
+ return new _TgpuRenderPipelineImpl(this._core, __spreadProps(__spreadValues({}, this._priors), {
3648
+ vertexLayoutMap: new Map([
3649
+ ...(_b = this._priors.vertexLayoutMap) != null ? _b : [],
3650
+ [definition, resource]
3651
+ ])
3652
+ }));
3653
+ }
3654
+ throw new Error("Unsupported value passed into .with()");
3655
+ }
3656
+ withColorAttachment(attachment) {
3657
+ return new _TgpuRenderPipelineImpl(this._core, __spreadProps(__spreadValues({}, this._priors), {
3658
+ colorAttachment: attachment
3659
+ }));
3660
+ }
3661
+ withDepthStencilAttachment(attachment) {
3662
+ return new _TgpuRenderPipelineImpl(this._core, __spreadProps(__spreadValues({}, this._priors), {
3663
+ depthStencilAttachment: attachment
3664
+ }));
3665
+ }
3666
+ draw(vertexCount, instanceCount, firstVertex, firstInstance) {
3667
+ var _a;
3668
+ const memo = this._core.unwrap();
3669
+ const { branch, fragmentFn: fragmentFn2 } = this._core.options;
3670
+ const colorAttachments = connectAttachmentToShader(
3671
+ fragmentFn2.shell.returnType,
3672
+ (_a = this._priors.colorAttachment) != null ? _a : {}
3673
+ ).map((attachment) => {
3674
+ if (isTexture(attachment.view)) {
3675
+ return __spreadProps(__spreadValues({}, attachment), {
3676
+ view: branch.unwrap(attachment.view).createView()
3677
+ });
3678
+ }
3679
+ return attachment;
3680
+ });
3681
+ const renderPassDescriptor = {
3682
+ colorAttachments
3683
+ };
3684
+ if (this._core.label !== void 0) {
3685
+ renderPassDescriptor.label = this._core.label;
3686
+ }
3687
+ if (this._priors.depthStencilAttachment !== void 0) {
3688
+ const attachment = this._priors.depthStencilAttachment;
3689
+ if (isTexture(attachment.view)) {
3690
+ renderPassDescriptor.depthStencilAttachment = __spreadProps(__spreadValues({}, attachment), {
3691
+ view: branch.unwrap(attachment.view).createView()
3692
+ });
3693
+ } else {
3694
+ renderPassDescriptor.depthStencilAttachment = attachment;
3695
+ }
3696
+ }
3697
+ const pass = branch.commandEncoder.beginRenderPass(renderPassDescriptor);
3698
+ pass.setPipeline(memo.pipeline);
3699
+ const missingBindGroups = new Set(memo.bindGroupLayouts);
3700
+ memo.bindGroupLayouts.forEach((layout, idx) => {
3701
+ var _a2;
3702
+ if (memo.catchall && idx === memo.catchall[0]) {
3703
+ pass.setBindGroup(idx, branch.unwrap(memo.catchall[1]));
3704
+ missingBindGroups.delete(layout);
3705
+ } else {
3706
+ const bindGroup = (_a2 = this._priors.bindGroupLayoutMap) == null ? void 0 : _a2.get(layout);
3707
+ if (bindGroup !== void 0) {
3708
+ missingBindGroups.delete(layout);
3709
+ pass.setBindGroup(idx, branch.unwrap(bindGroup));
3710
+ }
3711
+ }
3712
+ });
3713
+ const missingVertexLayouts = new Set(this._core.usedVertexLayouts);
3714
+ const usedVertexLayouts = this._core.usedVertexLayouts;
3715
+ usedVertexLayouts.forEach((vertexLayout2, idx) => {
3716
+ var _a2;
3717
+ const buffer = (_a2 = this._priors.vertexLayoutMap) == null ? void 0 : _a2.get(vertexLayout2);
3718
+ if (buffer) {
3719
+ missingVertexLayouts.delete(vertexLayout2);
3720
+ pass.setVertexBuffer(idx, branch.unwrap(buffer));
3721
+ }
3722
+ });
3723
+ if (missingBindGroups.size > 0) {
3724
+ throw new MissingBindGroupsError(missingBindGroups);
3725
+ }
3726
+ if (missingVertexLayouts.size > 0) {
3727
+ throw new MissingVertexBuffersError(missingVertexLayouts);
3728
+ }
3729
+ pass.draw(vertexCount, instanceCount, firstVertex, firstInstance);
3730
+ pass.end();
3731
+ }
3732
+ };
3733
+ var RenderPipelineCore = class {
3734
+ constructor(options) {
3735
+ this.options = options;
3736
+ __publicField(this, "label");
3737
+ __publicField(this, "usedVertexLayouts");
3738
+ __publicField(this, "_memo");
3739
+ __publicField(this, "_vertexBufferLayouts");
3740
+ __publicField(this, "_targets");
3741
+ const connectedAttribs = connectAttributesToShader(
3742
+ options.vertexFn.shell.attributes[0],
3743
+ options.vertexAttribs
3744
+ );
3745
+ this._vertexBufferLayouts = connectedAttribs.bufferDefinitions;
3746
+ this.usedVertexLayouts = connectedAttribs.usedVertexLayouts;
3747
+ this._targets = connectTargetsToShader(
3748
+ options.fragmentFn.shell.returnType,
3749
+ options.targets
3750
+ );
3751
+ }
3752
+ unwrap() {
3753
+ var _a, _b, _c, _d;
3754
+ if (this._memo === void 0) {
3755
+ const {
3756
+ branch,
3757
+ vertexFn: vertexFn2,
3758
+ fragmentFn: fragmentFn2,
3759
+ slotBindings,
3760
+ primitiveState,
3761
+ depthStencilState
3762
+ } = this.options;
3763
+ const { code, bindGroupLayouts, catchall } = resolve(
3764
+ {
3765
+ "~resolve": (ctx) => {
3766
+ ctx.withSlots(slotBindings, () => {
3767
+ ctx.resolve(vertexFn2);
3768
+ ctx.resolve(fragmentFn2);
3769
+ });
3770
+ return "";
3771
+ },
3772
+ toString: () => {
3773
+ var _a2;
3774
+ return `renderPipeline:${(_a2 = this.label) != null ? _a2 : "<unnamed>"}`;
3775
+ }
3776
+ },
3777
+ {
3778
+ names: branch.nameRegistry,
3779
+ jitTranspiler: branch.jitTranspiler
3780
+ }
3781
+ );
3782
+ if (catchall !== null) {
3783
+ (_b = bindGroupLayouts[catchall[0]]) == null ? void 0 : _b.$name(
3784
+ `${(_a = this.label) != null ? _a : "<unnamed>"} - Automatic Bind Group & Layout`
3785
+ );
3786
+ }
3787
+ const device = branch.device;
3788
+ const module = device.createShaderModule({
3789
+ label: `${(_c = this.label) != null ? _c : "<unnamed>"} - Shader`,
3790
+ code
3791
+ });
3792
+ const descriptor = {
3793
+ layout: device.createPipelineLayout({
3794
+ label: `${(_d = this.label) != null ? _d : "<unnamed>"} - Pipeline Layout`,
3795
+ bindGroupLayouts: bindGroupLayouts.map((l) => branch.unwrap(l))
3796
+ }),
3797
+ vertex: {
3798
+ module,
3799
+ buffers: this._vertexBufferLayouts
3800
+ },
3801
+ fragment: {
3802
+ module,
3803
+ targets: this._targets
3804
+ }
3805
+ };
3806
+ if (this.label !== void 0) {
3807
+ descriptor.label = this.label;
3808
+ }
3809
+ if (primitiveState) {
3810
+ descriptor.primitive = primitiveState;
3811
+ }
3812
+ if (depthStencilState) {
3813
+ descriptor.depthStencil = depthStencilState;
3814
+ }
3815
+ this._memo = {
3816
+ pipeline: device.createRenderPipeline(descriptor),
3817
+ bindGroupLayouts,
3818
+ catchall
3819
+ };
3820
+ }
3821
+ return this._memo;
3822
+ }
3823
+ };
3824
+
3825
+ // src/core/root/init.ts
3826
+ var WithBindingImpl = class _WithBindingImpl {
3827
+ constructor(_getRoot, _slotBindings) {
3828
+ this._getRoot = _getRoot;
3829
+ this._slotBindings = _slotBindings;
3830
+ }
3831
+ with(slot2, value) {
3832
+ return new _WithBindingImpl(this._getRoot, [
3833
+ ...this._slotBindings,
3834
+ [isAccessor(slot2) ? slot2.slot : slot2, value]
3835
+ ]);
3836
+ }
3837
+ withCompute(entryFn) {
3838
+ return new WithComputeImpl(this._getRoot(), this._slotBindings, entryFn);
3839
+ }
3840
+ withVertex(vertexFn2, attribs) {
3841
+ return new WithVertexImpl({
3842
+ branch: this._getRoot(),
3843
+ primitiveState: void 0,
3844
+ depthStencilState: void 0,
3845
+ slotBindings: this._slotBindings,
3846
+ vertexFn: vertexFn2,
3847
+ vertexAttribs: attribs
3848
+ });
3849
+ }
3850
+ };
3851
+ var WithComputeImpl = class {
3852
+ constructor(_root, _slotBindings, _entryFn) {
3853
+ this._root = _root;
3854
+ this._slotBindings = _slotBindings;
3855
+ this._entryFn = _entryFn;
3856
+ }
3857
+ createPipeline() {
3858
+ return INTERNAL_createComputePipeline(
3859
+ this._root,
3860
+ this._slotBindings,
3861
+ this._entryFn
3862
+ );
3863
+ }
3864
+ };
3865
+ var WithVertexImpl = class {
3866
+ constructor(_options) {
3867
+ this._options = _options;
3868
+ }
3869
+ withFragment(fragmentFn2, targets, _mismatch) {
3870
+ invariant(typeof fragmentFn2 !== "string", "Just type mismatch validation");
3871
+ invariant(typeof targets !== "string", "Just type mismatch validation");
3872
+ return new WithFragmentImpl(__spreadProps(__spreadValues({}, this._options), {
3873
+ fragmentFn: fragmentFn2,
3874
+ targets
3875
+ }));
3876
+ }
3877
+ };
3878
+ var WithFragmentImpl = class _WithFragmentImpl {
3879
+ constructor(_options) {
3880
+ this._options = _options;
3881
+ }
3882
+ withPrimitive(primitiveState) {
3883
+ return new _WithFragmentImpl(__spreadProps(__spreadValues({}, this._options), { primitiveState }));
3884
+ }
3885
+ withDepthStencil(depthStencilState) {
3886
+ return new _WithFragmentImpl(__spreadProps(__spreadValues({}, this._options), { depthStencilState }));
3887
+ }
3888
+ createPipeline() {
3889
+ return INTERNAL_createRenderPipeline(this._options);
3890
+ }
3891
+ };
3892
+ var TgpuRootImpl = class extends WithBindingImpl {
3893
+ constructor(device, nameRegistry, jitTranspiler, _ownDevice) {
3894
+ super(() => this, []);
3895
+ this.device = device;
3896
+ this.nameRegistry = nameRegistry;
3897
+ this.jitTranspiler = jitTranspiler;
3898
+ this._ownDevice = _ownDevice;
3899
+ __publicField(this, "~unstable");
3900
+ __publicField(this, "_disposables", []);
3901
+ __publicField(this, "_unwrappedBindGroupLayouts", new WeakMemo(
3902
+ (key) => key.unwrap(this)
3903
+ ));
3904
+ __publicField(this, "_unwrappedBindGroups", new WeakMemo(
3905
+ (key) => key.unwrap(this)
3906
+ ));
3907
+ __publicField(this, "_commandEncoder", null);
3908
+ this["~unstable"] = {
3909
+ nameRegistry: this.nameRegistry,
3910
+ commandEncoder: this.commandEncoder,
3911
+ createTexture: this.createTexture.bind(this),
3912
+ with: this.with.bind(this),
3913
+ withCompute: this.withCompute.bind(this),
3914
+ withVertex: this.withVertex.bind(this),
3915
+ flush: this.flush.bind(this)
3916
+ };
3917
+ }
3918
+ get commandEncoder() {
3919
+ if (!this._commandEncoder) {
3920
+ this._commandEncoder = this.device.createCommandEncoder();
3921
+ }
3922
+ return this._commandEncoder;
3923
+ }
3924
+ createBuffer(typeSchema, initialOrBuffer) {
3925
+ const buffer = INTERNAL_createBuffer(this, typeSchema, initialOrBuffer);
3926
+ this._disposables.push(buffer);
3927
+ return buffer;
3928
+ }
3929
+ createBindGroup(layout, entries) {
3930
+ return new TgpuBindGroupImpl(layout, entries);
3931
+ }
3932
+ destroy() {
3933
+ for (const disposable of this._disposables) {
3934
+ disposable.destroy();
3935
+ }
3936
+ if (this._ownDevice) {
3937
+ this.device.destroy();
3938
+ }
3939
+ }
3940
+ createTexture(props) {
3941
+ const texture = INTERNAL_createTexture(props, this);
3942
+ this._disposables.push(texture);
3943
+ return texture;
3944
+ }
3945
+ unwrap(resource) {
3946
+ if (isComputePipeline(resource)) {
3947
+ return resource.rawPipeline;
3948
+ }
3949
+ if (isBindGroupLayout(resource)) {
3950
+ return this._unwrappedBindGroupLayouts.getOrMake(resource);
3951
+ }
3952
+ if (isBindGroup(resource)) {
3953
+ return this._unwrappedBindGroups.getOrMake(resource);
3954
+ }
3955
+ if (isBuffer(resource)) {
3956
+ return resource.buffer;
3957
+ }
3958
+ if (isTexture(resource)) {
3959
+ return resource.unwrap();
3960
+ }
3961
+ if (isStorageTextureView(resource)) {
3962
+ return resource.unwrap();
3963
+ }
3964
+ if (isSampledTextureView(resource)) {
3965
+ return resource.unwrap();
3966
+ }
3967
+ throw new Error(`Unknown resource type: ${resource}`);
3968
+ }
3969
+ flush() {
3970
+ if (!this._commandEncoder) {
3971
+ return;
3972
+ }
3973
+ this.device.queue.submit([this._commandEncoder.finish()]);
3974
+ this._commandEncoder = null;
3975
+ }
3976
+ };
3977
+ async function init(options) {
3978
+ const {
3979
+ adapter: adapterOpt,
3980
+ device: deviceOpt,
3981
+ unstable_names: names = "random",
3982
+ unstable_jitTranspiler: jitTranspiler
3983
+ } = options != null ? options : {};
3984
+ if (!navigator.gpu) {
3985
+ throw new Error("WebGPU is not supported by this browser.");
3986
+ }
3987
+ const adapter = await navigator.gpu.requestAdapter(adapterOpt);
3988
+ if (!adapter) {
3989
+ throw new Error("Could not find a compatible GPU");
3990
+ }
3991
+ return new TgpuRootImpl(
3992
+ await adapter.requestDevice(deviceOpt),
3993
+ names === "random" ? new RandomNameRegistry() : new StrictNameRegistry(),
3994
+ jitTranspiler,
3995
+ true
3996
+ );
3997
+ }
3998
+ function initFromDevice(options) {
3999
+ const {
4000
+ device,
4001
+ unstable_names: names = "random",
4002
+ unstable_jitTranspiler: jitTranspiler
4003
+ } = options != null ? options : {};
4004
+ return new TgpuRootImpl(
4005
+ device,
4006
+ names === "random" ? new RandomNameRegistry() : new StrictNameRegistry(),
4007
+ jitTranspiler,
4008
+ false
4009
+ );
4010
+ }
4011
+
4012
+ // src/core/slot/slot.ts
4013
+ function slot(defaultValue) {
4014
+ return new TgpuSlotImpl(defaultValue);
4015
+ }
4016
+ var TgpuSlotImpl = class {
4017
+ constructor(defaultValue = void 0) {
4018
+ this.defaultValue = defaultValue;
4019
+ __publicField(this, "resourceType", "slot");
4020
+ __publicField(this, "label");
4021
+ __publicField(this, "~repr");
4022
+ }
4023
+ $name(label) {
4024
+ this.label = label;
4025
+ return this;
4026
+ }
4027
+ areEqual(a, b) {
4028
+ return Object.is(a, b);
4029
+ }
4030
+ toString() {
4031
+ var _a;
4032
+ return `slot:${(_a = this.label) != null ? _a : "<unnamed>"}`;
4033
+ }
4034
+ get value() {
4035
+ const ctx = getResolutionCtx();
4036
+ if (!ctx) {
4037
+ throw new Error(`Cannot access tgpu.slot's value outside of resolution.`);
4038
+ }
4039
+ return unwrapProxy(ctx.unwrap(this));
4040
+ }
4041
+ };
4042
+
4043
+ // src/core/slot/accessor.ts
4044
+ function accessor(schema, defaultValue) {
4045
+ return new TgpuAccessorImpl(schema, defaultValue);
4046
+ }
4047
+ var TgpuAccessorImpl = class {
4048
+ constructor(schema, defaultValue = void 0) {
4049
+ this.schema = schema;
4050
+ this.defaultValue = defaultValue;
4051
+ __publicField(this, "resourceType", "accessor");
4052
+ __publicField(this, "~repr");
4053
+ __publicField(this, "label");
4054
+ __publicField(this, "slot");
4055
+ this.slot = slot(defaultValue);
4056
+ }
4057
+ $name(label) {
4058
+ this.label = label;
4059
+ this.slot.$name(label);
4060
+ return this;
4061
+ }
4062
+ toString() {
4063
+ var _a;
4064
+ return `accessor:${(_a = this.label) != null ? _a : "<unnamed>"}`;
4065
+ }
4066
+ get value() {
4067
+ const ctx = getResolutionCtx();
4068
+ if (!ctx) {
4069
+ throw new Error(
4070
+ `Cannot access tgpu.accessor's value outside of resolution.`
4071
+ );
4072
+ }
4073
+ return new Proxy(
4074
+ {
4075
+ "~resolve": (ctx2) => ctx2.resolve(this),
4076
+ toString: () => {
4077
+ var _a;
4078
+ return `.value:${(_a = this.label) != null ? _a : "<unnamed>"}`;
4079
+ }
4080
+ },
4081
+ valueProxyHandler
4082
+ );
4083
+ }
4084
+ "~resolve"(ctx) {
4085
+ const value = ctx.unwrap(this.slot);
4086
+ if (isBufferUsage(value)) {
4087
+ return ctx.resolve(value);
4088
+ }
4089
+ if (isTgpuFn(value)) {
4090
+ return `${ctx.resolve(value)}()`;
4091
+ }
4092
+ return ctx.resolveValue(value, this.schema);
4093
+ }
4094
+ };
4095
+
4096
+ // src/core/slot/derived.ts
4097
+ function derived(compute) {
4098
+ return createDerived(compute);
4099
+ }
4100
+ function stringifyPair2([slot2, value]) {
4101
+ var _a;
4102
+ return `${(_a = slot2.label) != null ? _a : "<unnamed>"}=${value}`;
4103
+ }
4104
+ function createDerived(compute) {
4105
+ const result = {
4106
+ resourceType: "derived",
4107
+ "~compute": compute,
4108
+ "~repr": void 0,
4109
+ get value() {
4110
+ const ctx = getResolutionCtx();
4111
+ if (!ctx) {
4112
+ throw new Error(
4113
+ `Cannot access tgpu.derived's value outside of resolution.`
4114
+ );
4115
+ }
4116
+ return unwrapProxy(ctx.unwrap(this));
4117
+ },
4118
+ with(slot2, value) {
4119
+ return createBoundDerived(this, [[slot2, value]]);
4120
+ },
4121
+ toString() {
4122
+ return "derived";
4123
+ }
4124
+ };
4125
+ return result;
4126
+ }
4127
+ function createBoundDerived(innerDerived, pairs) {
4128
+ const result = {
4129
+ resourceType: "derived",
4130
+ "~repr": void 0,
4131
+ "~compute"() {
4132
+ throw new Error(
4133
+ `'~compute' should never be read on bound derived items.`
4134
+ );
4135
+ },
4136
+ "~providing": {
4137
+ inner: innerDerived,
4138
+ pairs
4139
+ },
4140
+ get value() {
4141
+ const ctx = getResolutionCtx();
4142
+ if (!ctx) {
4143
+ throw new Error(
4144
+ `Cannot access tgpu.derived's value outside of resolution.`
4145
+ );
4146
+ }
4147
+ return unwrapProxy(ctx.unwrap(this));
4148
+ },
4149
+ with(slot2, value) {
4150
+ return createBoundDerived(innerDerived, [...pairs, [slot2, value]]);
4151
+ },
4152
+ toString() {
4153
+ return `derived[${pairs.map(stringifyPair2).join(", ")}]`;
4154
+ }
4155
+ };
4156
+ return result;
4157
+ }
4158
+
4159
+ // src/core/variable/tgpuVariable.ts
4160
+ function privateVar(dataType, initialValue) {
4161
+ return new TgpuVarImpl("private", dataType, initialValue);
4162
+ }
4163
+ function workgroupVar(dataType) {
4164
+ return new TgpuVarImpl("workgroup", dataType);
4165
+ }
4166
+ var TgpuVarImpl = class {
4167
+ constructor(scope, _dataType, _initialValue) {
4168
+ this.scope = scope;
4169
+ this._dataType = _dataType;
4170
+ this._initialValue = _initialValue;
4171
+ __publicField(this, "_label");
4172
+ }
4173
+ $name(label) {
4174
+ this._label = label;
4175
+ return this;
4176
+ }
4177
+ "~resolve"(ctx) {
4178
+ const id = ctx.names.makeUnique(this._label);
4179
+ if (this._initialValue) {
4180
+ ctx.addDeclaration(
4181
+ `var<${this.scope}> ${id}: ${ctx.resolve(this._dataType)} = ${ctx.resolveValue(this._initialValue, this._dataType)};`
4182
+ );
4183
+ } else {
4184
+ ctx.addDeclaration(
4185
+ `var<${this.scope}> ${id}: ${ctx.resolve(this._dataType)};`
4186
+ );
4187
+ }
4188
+ return id;
4189
+ }
4190
+ get label() {
4191
+ return this._label;
4192
+ }
4193
+ toString() {
4194
+ var _a;
4195
+ return `var:${(_a = this.label) != null ? _a : "<unnamed>"}`;
4196
+ }
4197
+ get value() {
4198
+ if (!inGPUMode()) {
4199
+ throw new Error(`Cannot access tgpu.var's value directly in JS.`);
4200
+ }
4201
+ return new Proxy(
4202
+ {
4203
+ "~resolve": (ctx) => ctx.resolve(this),
4204
+ toString: () => {
4205
+ var _a;
4206
+ return `.value:${(_a = this.label) != null ? _a : "<unnamed>"}`;
4207
+ }
4208
+ },
4209
+ valueProxyHandler
4210
+ );
4211
+ }
4212
+ };
4213
+
4214
+ // src/index.ts
4215
+ var tgpu = {
4216
+ bindGroupLayout,
4217
+ init,
4218
+ initFromDevice,
4219
+ resolve: resolve2,
4220
+ "~unstable": {
4221
+ fn,
4222
+ fragmentFn,
4223
+ vertexFn,
4224
+ computeFn,
4225
+ vertexLayout,
4226
+ derived,
4227
+ slot,
4228
+ accessor,
4229
+ privateVar,
4230
+ workgroupVar,
4231
+ const: constant,
4232
+ declare,
4233
+ sampler,
4234
+ comparisonSampler
4235
+ }
4236
+ };
4237
+ var src_default = tgpu;
4238
+ Object.assign(tgpu, {
4239
+ __assignAst: assignAst
4240
+ });
4241
+ export {
4242
+ MissingBindGroupsError,
4243
+ MissingLinksError,
4244
+ MissingSlotValueError,
4245
+ MissingVertexBuffersError,
4246
+ NotUniformError,
4247
+ RandomNameRegistry,
4248
+ ResolutionError,
4249
+ StrictNameRegistry,
4250
+ src_default as default,
4251
+ isBuffer,
4252
+ isComparisonSampler,
4253
+ isDerived,
4254
+ isSampledTextureView,
4255
+ isSampler,
4256
+ isSlot,
4257
+ isStorageTextureView,
4258
+ isTexture,
4259
+ isTgpuFn,
4260
+ isUsableAsRender,
4261
+ isUsableAsSampled,
4262
+ isUsableAsStorage,
4263
+ isUsableAsUniform,
4264
+ isUsableAsVertex,
4265
+ tgpu,
4266
+ asMutable as unstable_asMutable,
4267
+ asReadonly as unstable_asReadonly,
4268
+ asUniform as unstable_asUniform
4269
+ };
15
4270
  //# sourceMappingURL=index.js.map