typegpu 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/{chunk-6WF2EZIT.js → chunk-6U5HPHCJ.js} +2 -2
  2. package/{chunk-B254XDWG.js → chunk-CGQB3SER.js} +2 -2
  3. package/{chunk-XEUNEHAZ.js → chunk-CRZWTZM2.js} +6 -6
  4. package/chunk-CRZWTZM2.js.map +1 -0
  5. package/chunk-ECR2EGZX.js +7 -0
  6. package/chunk-ECR2EGZX.js.map +1 -0
  7. package/chunk-PWBIFP67.js +2 -0
  8. package/chunk-PWBIFP67.js.map +1 -0
  9. package/common/index.d.ts +1 -1
  10. package/common/index.js +1 -1
  11. package/data/index.d.ts +3 -3
  12. package/data/index.js +1 -1
  13. package/index.d.ts +2 -2
  14. package/index.js +40 -40
  15. package/index.js.map +1 -1
  16. package/{matrix-C6mMH7pB.d.ts → matrix-DIfOiRyz.d.ts} +1 -1
  17. package/package.json +5 -13
  18. package/std/index.d.ts +2 -2
  19. package/std/index.js +1 -1
  20. package/std/index.js.map +1 -1
  21. package/{tgpuConstant-DzGgwe0I.d.ts → tgpuConstant-BTQFNlQH.d.ts} +13 -8
  22. package/chunk-A5APHF7K.cjs +0 -10
  23. package/chunk-A5APHF7K.cjs.map +0 -1
  24. package/chunk-LL6NPRFE.cjs +0 -7
  25. package/chunk-LL6NPRFE.cjs.map +0 -1
  26. package/chunk-M2P3FJT7.cjs +0 -2
  27. package/chunk-M2P3FJT7.cjs.map +0 -1
  28. package/chunk-PO6SIMTQ.js +0 -2
  29. package/chunk-PO6SIMTQ.js.map +0 -1
  30. package/chunk-T2GBOTUH.js +0 -7
  31. package/chunk-T2GBOTUH.js.map +0 -1
  32. package/chunk-TRAG63HY.cjs +0 -3
  33. package/chunk-TRAG63HY.cjs.map +0 -1
  34. package/chunk-U3CXOCRG.cjs +0 -2
  35. package/chunk-U3CXOCRG.cjs.map +0 -1
  36. package/chunk-XEUNEHAZ.js.map +0 -1
  37. package/common/index.cjs +0 -7
  38. package/common/index.cjs.map +0 -1
  39. package/common/index.d.cts +0 -24
  40. package/data/index.cjs +0 -2
  41. package/data/index.cjs.map +0 -1
  42. package/data/index.d.cts +0 -402
  43. package/index.cjs +0 -192
  44. package/index.cjs.map +0 -1
  45. package/index.d.cts +0 -369
  46. package/matrix-Cn2jQILV.d.cts +0 -122
  47. package/std/index.cjs +0 -2
  48. package/std/index.cjs.map +0 -1
  49. package/std/index.d.cts +0 -639
  50. package/tgpuConstant-DzGgwe0I.d.cts +0 -5196
  51. /package/{chunk-6WF2EZIT.js.map → chunk-6U5HPHCJ.js.map} +0 -0
  52. /package/{chunk-B254XDWG.js.map → chunk-CGQB3SER.js.map} +0 -0
package/index.js CHANGED
@@ -1,19 +1,19 @@
1
- import{a as Pt,b as Rn,c as Dt,d as Bt,e as ue,f as qe,g as $e,h as _n}from"./chunk-B254XDWG.js";import{a as Ae,b as br,c as Qn,d as Hn,e as Kn,i as Rt,j as Ct,k as Yn}from"./chunk-PO6SIMTQ.js";import{O as On,P as zn,Q as Qe,R as Nn,ha as qn,hb as Gt,j as Pe,k as De,l as Be,n as An,o as wr,p as Ft,q as Ln,r as Gn,s as At,t as Lt,u as Wn,v as kn,w as je,x as Mn}from"./chunk-T2GBOTUH.js";import{$a as J,Aa as z,B as we,Ba as Dn,C as O,Ca as ve,D as _,Da as E,Ea as oe,F as hn,Ga as se,Ha as Bn,L as ct,M as xn,Ma as xr,Q as wn,R as gt,Ra as wt,S as re,Sa as R,T as bn,U as ne,Ua as bt,V as ae,Va as St,W as ke,Wa as $n,Ya as W,Za as Ie,_a as Y,a as l,aa as g,ab as vt,b as w,ba as K,bb as N,c as D,ca as be,cb as Ue,d as H,da as dr,db as de,dc as En,e as B,ea as cr,eb as C,ec as L,f as T,fa as gr,fb as It,fc as q,ga as Ha,gb as V,h as mt,ha as me,hb as Fe,hc as k,i as te,ia as Me,ib as X,ic as I,j as f,ja as yr,jb as Z,k as S,ka as Tr,kb as Ut,l as ft,la as yt,m as dt,ma as Tt,mb as ze,n as ln,na as ht,nb as Cn,o as mn,oa as hr,ob as ce,p as fn,pa as fe,pc as ie,q as A,qa as Sn,qc as $t,ra as vn,rc as Ne,s as mr,sa as In,sc as Vn,t as fr,ta as Un,u as dn,ua as Fn,uc as Sr,v as cn,vc as jn,wa as Oe,x as gn,xa as Pn,y as yn,ya as Se,z as Tn,za as xt}from"./chunk-XEUNEHAZ.js";function Jn(t){return t?.[w]}var G={get(t,e){if(e in t)return Reflect.get(t,e);if(e==="toString"||e===Symbol.toStringTag||e===Symbol.toPrimitive)return()=>t.toString();if(typeof e=="symbol")return;let n=Fn(t).dataType,a=An(n,String(e));if(a.type!=="unknown")return new Proxy({[l]:!0,[T]:o=>g(`${o.resolve(t).value}.${String(e)}`,a),get[B](){return g(this,a)},toString:()=>`${String(t)}.${e}`},G)}};function ge(t){let e=t;for(;;){let r=Jn(e);if(!r)break;e=r}return e}function Ir(t,e){return new vr(t,e)}var vr=class{constructor(e,r){this.dataType=e;this.#e=r}[l]={};#e;$name(e){return S(this,e),this}[T](e){let r=e.getUniqueName(this),n=e.resolve(this.dataType).value,a=e.resolve(this.#e,this.dataType).value;return e.addDeclaration(`const ${r}: ${n} = ${a};`),g(r,this.dataType)}toString(){return`const:${f(this)??"<unnamed>"}`}get[w](){let e=this.dataType;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`const:${f(this)??"<unnamed>"}.$`},G)}get value(){return E()?this[w]:this.#e}get $(){return this.value}};function Xn(t){return new Ur(t)}var Ur=class{constructor(e){this.declaration=e}[l]=!0;externalsToApply=[];$uses(e){return this.externalsToApply.push(e),this}[T](e){let r={};for(let a of this.externalsToApply)Pt(r,a);let n=Bt(e,r,this.declaration);return e.addDeclaration(n),g("",A)}toString(){return`declare: ${this.declaration}`}};function Et(t){let e={argTypes:t.in&&Object.keys(t.in).length!==0?[qe(t.in)]:[],returnType:A,workgroupSize:[t.workgroupSize[0]??1,t.workgroupSize[1]??1,t.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>Ka(e,t.workgroupSize,$e(n,...a));return Object.assign(Object.assign(r,e),{does:r})}function Ka(t,e,r){let n=ue(r,`@compute @workgroup_size(${e.join(", ")}) `),a=t.argTypes[0];return{shell:t,$uses(s){return n.applyExternals(s),this},[l]:!0,[D]:n,$name(s){return S(n,s),ft(a)&&a.$name(`${s}_Input`),this},[T](s){return n.resolve(s,t.argTypes,t.returnType)},toString(){return`computeFn:${f(n)??"<unnamed>"}`}}}function U(t,e){let r={[l]:!0,argTypes:t,returnType:e??A,isEntry:!1};return Object.assign((a,...o)=>Ja(r,$e(a,...o)),r)}function He(t){return mt(t)&&t?.resourceType==="function"}function Ya([t,e]){return`${f(t)??"<unnamed>"}=${e}`}function Ja(t,e){let r=ue(e,""),n={shell:t,resourceType:"function",$uses(s){return r.applyExternals(s),this},[D]:r,$name(s){return S(r,s),this},with(s,i){return Zn(o,[[fe(s)?s.slot:s,i]])},[T](s){return typeof e=="string"&&(Rn(e,t.argTypes,r.applyExternals),Dt(e,t.returnType,r.applyExternals)),r.resolve(s,t.argTypes,t.returnType)}},a=xr((...s)=>Pn(()=>{try{if(typeof e=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");let i=s.map((p,m)=>Ne(t.argTypes[m],p)),u=e(...i);return Ne(t.returnType,u)}catch(i){throw i instanceof dr?i.appendToTrace(o):new dr(i,[o])}}),(...s)=>g(new Vt(o,s),t.returnType),"tgpuFnCall",t.argTypes),o=Object.assign(a,n);return o[l].implementation=e,Object.defineProperty(o,"toString",{value(){return`fn:${f(r)??"<unnamed>"}`}}),o}function Zn(t,e){let r={resourceType:"function",shell:t.shell,[H]:{inner:t,pairs:e},$uses(o){return t.$uses(o),this},[D]:t,$name(o){return t.$name(o),this},with(o,s){return Zn(a,[...e,[fe(o)?o.slot:o,s]])}},n=xr((...o)=>t(...o),(...o)=>g(new Vt(a,o),t.shell.returnType),"tgpuFnCall",t.shell.argTypes),a=Object.assign(n,r);return a[l].implementation=t[l].implementation,Object.defineProperty(a,"toString",{value(){return`fn:${f(t)??"<unnamed>"}[${e.map(Ya).join(", ")}]`}}),a[l].implementation=t[l].implementation,a}var Vt=class{[l]=!0;[B];[D];#e;#r;constructor(e,r){this.#e=e,this.#r=r,this[D]=e,this[B]=g(this,this.#e.shell.returnType)}[T](e){return e.withResetIndentLevel(()=>g(oe`${e.resolve(this.#e).value}(${this.#r})`,this.#e.shell.returnType))}toString(){return`call:${f(this)??"<unnamed>"}`}};function ea(t){let e={in:t.in,out:t.out,returnType:qe(t.out),isEntry:!0},r=(n,...a)=>Xa(e,$e(n,...a));return Object.assign(Object.assign(r,e),{does:r})}function Xa(t,e){let r=ue(e,"@fragment "),n=t.returnType;return typeof e=="string"&&Dt(e,n,o=>r.applyExternals(o)),{shell:t,outputType:n,$uses(o){return r.applyExternals(o),this},[l]:!0,[D]:r,$name(o){return S(r,o),ft(n)&&n.$name(`${o}_Output`),this},[T](o){let s=t.in?qe(t.in,o.varyingLocations).$name(`${f(this)??""}_Input`):void 0;return s&&r.applyExternals({In:s}),r.applyExternals({Out:n}),r.resolve(o,s?[s]:[],t.returnType)},toString(){return`fragmentFn:${f(r)??"<unnamed>"}`}}}var ta=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield"]);function Fr(t){if(t==="_"||t.startsWith("__")||/\s/.test(t))throw new Error(`Invalid identifier '${t}'. Choose an identifier without whitespaces or leading underscores.`);let e=t.split("_")[0];return!ta.has(e)}var _t=class{makeValid(e){return Fr(e)?e:this.makeUnique(e)}},Wt=class extends _t{lastUniqueId=0;makeUnique(e){let r;return e?(r=e.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},kt=class extends _t{_usedNames=new Set(ta);makeUnique(e){if(e===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=e;for(;this._usedNames.has(n);)r++,n=`${e}_${r}`;return this._usedNames.add(n),n}};function ra(t,e){let r=ue(e,"");return{[l]:!0,[D]:r,resourceType:"shellless-impl",[T](n){return r.resolve(n,t,void 0)},toString(){return`fn*:${f(r)??"<unnamed>"}`}}}var Mt=class{cache=new Map;get(e,r){let n=ln(e);if(!n?.ast)return;if(!r&&n.ast.params.length>0)throw new Error(`Cannot resolve '${f(e)}' directly, because it expects arguments. Either call it from another function, or wrap it in a shell`);let a=(r??[]).map(i=>Ft(i.dataType)),o=this.cache.get(e);if(o){let i=o.find(u=>u.argTypes.every((p,m)=>p===a[m]));if(i)return i.value}else o=[],this.cache.set(e,o);let s=ra(a,e);return o.push({argTypes:a,value:s}),s}};var Pr=class{[l];constructor(e){this[l]={nameRegistry:e,shelllessRepo:new Mt,memoizedResolves:new WeakMap,memoizedDerived:new WeakMap,listeners:{name:new Set}}}on(e,r){if(e==="name"){let n=this[l].listeners.name;return n.add(r),()=>n.delete(r)}throw new Error(`Unsupported event: ${e}`)}};function na(t,e){let r=t.nameRegistry.makeUnique(f(e));for(let n of t.listeners.name)n({target:e,name:r});return r}function j(t){let{names:e="random"}=t||{};return new Pr(e==="strict"?new kt:new Wt)}function Ke(t){return typeof t?.format=="string"}function aa(t,e){let r=[];if(ae(t)){if(!Ke(e))throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");return r.push(e._layout),{usedVertexLayouts:r,bufferDefinitions:[{arrayStride:e._layout.stride,stepMode:e._layout.stepMode,attributes:[{format:e.format,offset:e.offset,shaderLocation:ne(t)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[s,i]of Object.entries(t)){if(ie(i))continue;let u=e[s];if(!u)throw new Error(`An attribute by the name of '${s}' was not provided to the shader.`);let p=u._layout,m=a.get(p);m||(r.push(p),m=[],n.push({arrayStride:p.stride,stepMode:p.stepMode,attributes:m}),a.set(p,m)),o=ne(i)??o,m.push({format:u.format,offset:u.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var Za=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","vec2<bool>","vec3<bool>","vec4<bool>","mat2x2f","mat3x3f","mat4x4f","texture_external"];function eo(t){return Za.includes(t.type)}function Dr(t,[e,r]){if(!Fr(e))throw new Error(`Property key '${e}' is a reserved WGSL word. Choose a different name.`);return` ${$t(r)}${e}: ${t.resolve(r).value},
2
- `}function to(t,e){if(e[l].isAbstruct)throw new Error("Cannot resolve abstract struct types to WGSL.");let r=t.getUniqueName(e);return t.addDeclaration(`struct ${r} {
3
- ${Object.entries(e.propTypes).map(n=>Dr(t,n)).join("")}}`),r}function ro(t,e){let r=t.getUniqueName(e);return t.addDeclaration(`struct ${r} {
4
- ${Object.entries(e.propTypes).map(n=>Ke(n[1])?Dr(t,[n[0],ce[n[1].format]]):Dr(t,n)).join("")}
5
- }`),r}function no(t,e){let r=t.resolve(e.elementType).value;return e.elementCount===0?`array<${r}>`:`array<${r}, ${e.elementCount}>`}function ao(t,e){let r=t.resolve(Ke(e.elementType)?ce[e.elementType.format]:e.elementType).value;return e.elementCount===0?`array<${r}>`:`array<${r}, ${e.elementCount}>`}function Br(t,e){if(wn(e))return e.type==="unstruct"?ro(t,e):e.type==="disarray"?ao(t,e):e.type==="loose-decorated"?t.resolve(Ke(e.inner)?ce[e.inner.format]:e.inner).value:t.resolve(ce[e.type]).value;if(eo(e))return e.type;if(e.type==="struct")return to(t,e);if(e.type==="array")return no(t,e);if(e.type==="atomic")return`atomic<${Br(t,e.inner)}>`;if(e.type==="decorated")return t.resolve(e.inner).value;if(e.type==="ptr")return e.addressSpace==="storage"?`ptr<storage, ${t.resolve(e.inner).value}, ${e.access==="read-write"?"read_write":e.access}>`:`ptr<${e.addressSpace}, ${t.resolve(e.inner).value}>`;if(e.type==="abstractInt"||e.type==="abstractFloat"||e.type==="void"||e.type==="u16")throw new Error(`${e.type} has no representation in WGSL`);if(Qe(e))return`${e.type}<${e.format}, ${Mn[e.access]}>`;if(zn(e))return e.type.startsWith("texture_depth")?e.type:`${e.type}<${e.sampleType.type}>`;if(kn(e)||Wn(e))return e.type;se(e,"resolveData")}var Le=class t{constructor(e){this.bindings=e}with(e,r){return new t([...this.bindings,[fe(e)?e.slot:e,r]])}pipe(e){let r=e(this);return new t([...this.bindings,...r.bindings])}};function*oa(t){let e=0;for(;;)t.has(e)||(yield e),e++}import{BufferReader as Lr,BufferWriter as fo,getSystemEndianness as co}from"typed-binary";import{Measurer as so}from"typed-binary";function oo(t,e){let r="size"in t?t.size:t.currentByteOffset,n=e-1,a=r&n;"skipBytes"in t?t.skipBytes(e-a&n):t.add(e-a&n)}var $=oo;var sa=new WeakMap;function Ot(t){let e=sa.get(t);if(e)return e;let r=new so,n={},a;for(let o in t.propTypes){let s=t.propTypes[o];if(s===void 0)throw new Error(`Property ${o} is undefined in struct`);let i=r.size;$(r,re(t)?q(s):L(s)),a&&(a.padding=r.size-i);let u=I(s);n[o]={offset:r.size,size:u},a=n[o],r.add(u)}return a&&(a.padding=k(I(t),L(t))-r.size),sa.set(t,n),n}var io=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),$r=new WeakMap,zt={u32:"u32",vec2u:"u32",vec3u:"u32",vec4u:"u32",u16:"u16",i32:"i32",vec2i:"i32",vec3i:"i32",vec4i:"i32",f32:"f32",vec2f:"f32",vec3f:"f32",vec4f:"f32",f16:"f16",vec2h:"f16",vec3h:"f16",vec4h:"f16",mat2x2f:"f32",mat3x3f:"f32",mat4x4f:"f32"},uo={uint8:"u8",uint8x2:"u8",uint8x4:"u8",sint8:"i8",sint8x2:"i8",sint8x4:"i8",unorm8:"u8",unorm8x2:"u8",unorm8x4:"u8",snorm8:"i8",snorm8x2:"i8",snorm8x4:"i8",uint16:"u16",uint16x2:"u16",uint16x4:"u16",sint16:"i16",sint16x2:"i16",sint16x4:"i16",unorm16:"u16",unorm16x2:"u16",unorm16x4:"u16",snorm16:"i16",snorm16x2:"i16",snorm16x4:"i16",float16:"f16",float16x2:"f16",float16x4:"f16",float32:"f32",float32x2:"f32",float32x3:"f32",float32x4:"f32",uint32:"u32",uint32x2:"u32",uint32x3:"u32",uint32x4:"u32",sint32:"i32",sint32x2:"i32",sint32x3:"i32",sint32x4:"i32"},Nt={u32:"setUint32",i32:"setInt32",f32:"setFloat32",u16:"setUint16",i16:"setInt16",f16:"setFloat16",u8:"setUint8",i8:"setInt8"},po={unorm8:t=>`Math.round(${t} * 255)`,unorm8x2:t=>`Math.round(${t} * 255)`,unorm8x4:t=>`Math.round(${t} * 255)`,snorm8:t=>`Math.round(${t} * 127)`,snorm8x2:t=>`Math.round(${t} * 127)`,snorm8x4:t=>`Math.round(${t} * 127)`,unorm16:t=>`Math.round(${t} * 65535)`,unorm16x2:t=>`Math.round(${t} * 65535)`,unorm16x4:t=>`Math.round(${t} * 65535)`,snorm16:t=>`Math.round(${t} * 32767)`,snorm16x2:t=>`Math.round(${t} * 32767)`,snorm16x4:t=>`Math.round(${t} * 32767)`},ia={"unorm10-10-10-2":{writeFunction:"setUint32",generator:(t,e)=>`output.setUint32(${t}, ((${e}.x*1023&0x3FF)<<22)|((${e}.y*1023&0x3FF)<<12)|((${e}.z*1023&0x3FF)<<2)|(${e}.w*3&3), littleEndian);
6
- `},"unorm8x4-bgra":{writeFunction:"setUint8",generator:(t,e)=>{let r=["z","y","x","w"],n="";for(let a=0;a<4;a++)n+=`output.setUint8((${t} + ${a}), Math.round(${e}.${r[a]} * 255), littleEndian);
7
- `;return n}}};function qt(t,e,r,n=0){let a=["i","j","k"][n]||`i${n}`;if(hn(t)||ct(t))return qt(t.inner,e,r,n);if(_(t)||re(t)){let s=Ot(t),i="";for(let[u,p]of Object.entries(s)){let m=t.propTypes[u];m&&(i+=qt(m,`(${e} + ${p.offset})`,`${r}.${u}`,n))}return i}if(O(t)||gt(t)){let s=k(I(t.elementType),L(t)),i="";return i+=`for (let ${a} = 0; ${a} < ${t.elementCount}; ${a}++) {
8
- `,i+=qt(t.elementType,`(${e} + ${a} * ${s})`,`${r}[${a}]`,n+1),i+=`}
9
- `,i}if(cn(t)){let s=zt[t.type],i="",u=Nt[s],p=["x","y","z","w"],m=mr(t)?2:fr(t)?3:4;for(let c=0;c<m;c++)i+=`output.${u}((${e} + ${c*4}), ${r}.${p[c]}, littleEndian);
10
- `;return i}if(Tn(t)){let s=zt[t.type],i=Nt[s],u=gn(t)?2:yn(t)?3:4,p=u*u,m=k(u*4,8),c="";for(let y=0;y<p;y++){let h=Math.floor(y/u),v=y%u,x=h*m+v*4;c+=`output.${i}((${e} + ${x}), ${r}.columns[${h}].${["x","y","z","w"][v]}, littleEndian);
11
- `}return c}if(En(t)){let s=t.type;if(s in ia)return ia[s].generator(e,r);let i=uo[s],u=Nt[i],p=ce[s],m=dn(p)?4:fr(p)?3:mr(p)?2:1,c=i==="u8"||i==="i8"?1:i==="u16"||i==="i16"||i==="f16"?2:4,y=["x","y","z","w"],h=po[s],v="";for(let x=0;x<m;x++){let P=m===1?r:`${r}.${y[x]}`,F=h?h(P):P;v+=`output.${u}((${e} + ${x*c}), ${F}, littleEndian);
12
- `}return v}if(!Object.hasOwn(zt,t.type))throw new Error(`Primitive ${t.type} is unsupported by compiled writer`);let o=zt[t.type];return`output.${Nt[o]}(${e}, ${r}, littleEndian);
13
- `}function Ar(t){if(!io){console.warn("This environment does not allow eval - using default writer as fallback");return}if($r.has(t))return $r.get(t);try{let e=qt(t,"offset","value",0),r=new Function("output","offset","value","littleEndian=true",e);return $r.set(t,r),r}catch(e){console.warn(`Failed to compile writer for schema: ${t}
14
- Reason: ${e instanceof Error?e.message:String(e)}
15
- Falling back to default writer`)}}var Ge={bool(){throw new Error("Booleans are not host-shareable")},f32(t,e,r){t.writeFloat32(r)},f16(t,e,r){t.writeFloat16(r)},i32(t,e,r){t.writeInt32(r)},u32(t,e,r){t.writeUint32(r)},u16(t,e,r){t.writeUint16(r)},vec2f(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y)},vec2h(t,e,r){t.writeFloat16(r.x),t.writeFloat16(r.y)},vec2i(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y)},vec2u(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y)},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},vec3f(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y),t.writeFloat32(r.z)},vec3h(t,e,r){t.writeFloat16(r.x),t.writeFloat16(r.y),t.writeFloat16(r.z)},vec3i(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y),t.writeInt32(r.z)},vec3u(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y),t.writeUint32(r.z)},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},vec4f(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y),t.writeFloat32(r.z),t.writeFloat32(r.w)},vec4h(t,e,r){t.writeFloat16(r.x),t.writeFloat16(r.y),t.writeFloat16(r.z),t.writeFloat16(r.w)},vec4i(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y),t.writeInt32(r.z),t.writeInt32(r.w)},vec4u(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y),t.writeUint32(r.z),t.writeUint32(r.w)},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},mat2x2f(t,e,r){for(let n=0;n<r.length;++n)t.writeFloat32(r[n])},mat3x3f(t,e,r){for(let n=0;n<r.length;++n)t.writeFloat32(r[n])},mat4x4f(t,e,r){for(let n=0;n<r.length;++n)t.writeFloat32(r[n])},struct(t,e,r){let n=L(e);$(t,n);for(let[a,o]of Object.entries(e.propTypes))$(t,L(o)),Re(t,o,r[a]);$(t,n)},array(t,e,r){if(e.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=L(e);$(t,n);let a=t.currentByteOffset;for(let o=0;o<Math.min(e.elementCount,r.length);o++)$(t,n),Re(t,e.elementType,r[o]);t.seekTo(a+I(e))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(t,e,r){Ge[e.inner.type]?.(t,e,r)},decorated(t,e,r){let n=q(e);$(t,n);let a=t.currentByteOffset;Ge[e.inner?.type]?.(t,e.inner,r),t.seekTo(a+I(e))},uint8(t,e,r){t.writeUint8(r)},uint8x2(t,e,r){t.writeUint8(r.x),t.writeUint8(r.y)},uint8x4(t,e,r){t.writeUint8(r.x),t.writeUint8(r.y),t.writeUint8(r.z),t.writeUint8(r.w)},sint8(t,e,r){t.writeInt8(r)},sint8x2(t,e,r){t.writeInt8(r.x),t.writeInt8(r.y)},sint8x4(t,e,r){t.writeInt8(r.x),t.writeInt8(r.y),t.writeInt8(r.z),t.writeInt8(r.w)},unorm8(t,e,r){t.writeUint8(Math.round(r*255))},unorm8x2(t,e,r){t.writeUint8(Math.round(r.x*255)),t.writeUint8(Math.round(r.y*255))},unorm8x4(t,e,r){t.writeUint8(Math.round(r.x*255)),t.writeUint8(Math.round(r.y*255)),t.writeUint8(Math.round(r.z*255)),t.writeUint8(Math.round(r.w*255))},snorm8(t,e,r){t.writeInt8(Math.round(r*127))},snorm8x2(t,e,r){t.writeInt8(Math.round(r.x*127)),t.writeInt8(Math.round(r.y*127))},snorm8x4(t,e,r){t.writeInt8(Math.round(r.x*127)),t.writeInt8(Math.round(r.y*127)),t.writeInt8(Math.round(r.z*127)),t.writeInt8(Math.round(r.w*127))},uint16(t,e,r){t.writeUint16(r)},uint16x2(t,e,r){t.writeUint16(r.x),t.writeUint16(r.y)},uint16x4(t,e,r){t.writeUint16(r.x),t.writeUint16(r.y),t.writeUint16(r.z),t.writeUint16(r.w)},sint16(t,e,r){t.writeInt16(r)},sint16x2(t,e,r){t.writeInt16(r.x),t.writeInt16(r.y)},sint16x4(t,e,r){t.writeInt16(r.x),t.writeInt16(r.y),t.writeInt16(r.z),t.writeInt16(r.w)},unorm16(t,e,r){t.writeUint16(r*65535)},unorm16x2(t,e,r){t.writeUint16(r.x*65535),t.writeUint16(r.y*65535)},unorm16x4(t,e,r){t.writeUint16(r.x*65535),t.writeUint16(r.y*65535),t.writeUint16(r.z*65535),t.writeUint16(r.w*65535)},snorm16(t,e,r){t.writeInt16(Math.round(r*32767))},snorm16x2(t,e,r){t.writeInt16(Math.round(r.x*32767)),t.writeInt16(Math.round(r.y*32767))},snorm16x4(t,e,r){t.writeInt16(Math.round(r.x*32767)),t.writeInt16(Math.round(r.y*32767)),t.writeInt16(Math.round(r.z*32767)),t.writeInt16(Math.round(r.w*32767))},float16(t,e,r){t.writeFloat16(r)},float16x2(t,e,r){t.writeFloat16(r.x),t.writeFloat16(r.y)},float16x4(t,e,r){t.writeFloat16(r.x),t.writeFloat16(r.y),t.writeFloat16(r.z),t.writeFloat16(r.w)},float32(t,e,r){t.writeFloat32(r)},float32x2(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y)},float32x3(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y),t.writeFloat32(r.z)},float32x4(t,e,r){t.writeFloat32(r.x),t.writeFloat32(r.y),t.writeFloat32(r.z),t.writeFloat32(r.w)},uint32(t,e,r){t.writeUint32(r)},uint32x2(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y)},uint32x3(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y),t.writeUint32(r.z)},uint32x4(t,e,r){t.writeUint32(r.x),t.writeUint32(r.y),t.writeUint32(r.z),t.writeUint32(r.w)},sint32(t,e,r){t.writeInt32(r)},sint32x2(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y)},sint32x3(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y),t.writeInt32(r.z)},sint32x4(t,e,r){t.writeInt32(r.x),t.writeInt32(r.y),t.writeInt32(r.z),t.writeInt32(r.w)},"unorm10-10-10-2"(t,e,r){let n=0;n|=(r.x*1023&1023)<<22,n|=(r.y*1023&1023)<<12,n|=(r.z*1023&1023)<<2,n|=r.w*3&3,t.writeUint32(n)},"unorm8x4-bgra"(t,e,r){t.writeUint8(r.z*255),t.writeUint8(r.y*255),t.writeUint8(r.x*255),t.writeUint8(r.w*255)},disarray(t,e,r){let n=L(e);$(t,n);let a=t.currentByteOffset;for(let o=0;o<Math.min(e.elementCount,r.length);o++)$(t,n),Ge[e.elementType?.type]?.(t,e.elementType,r[o]);t.seekTo(a+I(e))},unstruct(t,e,r){let n=e.propTypes;for(let[a,o]of Object.entries(n))Ge[o.type]?.(t,o,r[a])},"loose-decorated"(t,e,r){let n=q(e);$(t,n);let a=t.currentByteOffset,o=Ge[e.inner?.type];return o?.(t,e.inner,r),t.seekTo(a+I(e)),r}};function Re(t,e,r){let n=Ge[e.type];if(!n)throw new Error(`Cannot write data of type '${e.type}'.`);n(t,e,r)}var lo={bool(){throw new Error("Booleans are not host-shareable")},f32(t){return t.readFloat32()},f16(t){return t.readFloat16()},i32(t){return t.readInt32()},u32(t){return t.readUint32()},u16(t){return t.readUint16()},vec2f(t){return W(t.readFloat32(),t.readFloat32())},vec3f(t){return N(t.readFloat32(),t.readFloat32(),t.readFloat32())},vec4f(t){return V(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32())},vec2h(t){return Ie(t.readFloat16(),t.readFloat16())},vec3h(t){return Ue(t.readFloat16(),t.readFloat16(),t.readFloat16())},vec4h(t){return Fe(t.readFloat16(),t.readFloat16(),t.readFloat16(),t.readFloat16())},vec2i(t){return Y(t.readInt32(),t.readInt32())},vec3i(t){return de(t.readInt32(),t.readInt32(),t.readInt32())},vec4i(t){return X(t.readInt32(),t.readInt32(),t.readInt32(),t.readInt32())},vec2u(t){return J(t.readUint32(),t.readUint32())},vec3u(t){return C(t.readUint32(),t.readUint32(),t.readUint32())},vec4u(t){return Z(t.readUint32(),t.readUint32(),t.readUint32(),t.readUint32())},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},mat2x2f(t){return Pe(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32())},mat3x3f(t){let e=()=>{let r=t.readFloat32();return t.readFloat32(),r};return De(t.readFloat32(),t.readFloat32(),e(),t.readFloat32(),t.readFloat32(),e(),t.readFloat32(),t.readFloat32(),e())},mat4x4f(t){return Be(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32())},struct(t,e){let r=L(e);$(t,r);let n={},a=e.propTypes;for(let[o,s]of Object.entries(a))$(t,L(s)),n[o]=M(t,s);return $(t,r),n},array(t,e){if(e.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=L(e),n=[];for(let a=0;a<e.elementCount;a++){$(t,r);let o=e.elementType,s=M(t,o);n.push(s)}return $(t,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(t,e){return M(t,e.inner)},decorated(t,e){let r=q(e);$(t,r);let n=t.currentByteOffset,a=M(t,e.inner);return t.seekTo(n+I(e)),a},uint8:t=>t.readUint8(),uint8x2:t=>J(t.readUint8(),t.readUint8()),uint8x4:t=>Z(t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8()),sint8:t=>t.readInt8(),sint8x2:t=>Y(t.readInt8(),t.readInt8()),sint8x4:t=>X(t.readInt8(),t.readInt8(),t.readInt8(),t.readInt8()),unorm8:t=>t.readUint8()/255,unorm8x2:t=>W(t.readUint8()/255,t.readUint8()/255),unorm8x4:t=>V(t.readUint8()/255,t.readUint8()/255,t.readUint8()/255,t.readUint8()/255),snorm8:t=>t.readInt8()/127,snorm8x2:t=>W(t.readInt8()/127,t.readInt8()/127),snorm8x4:t=>V(t.readInt8()/127,t.readInt8()/127,t.readInt8()/127,t.readInt8()/127),uint16:t=>t.readUint16(),uint16x2:t=>J(t.readUint16(),t.readUint16()),uint16x4:t=>Z(t.readUint16(),t.readUint16(),t.readUint16(),t.readUint16()),sint16:t=>t.readInt16(),sint16x2:t=>Y(t.readInt16(),t.readInt16()),sint16x4:t=>X(t.readInt16(),t.readInt16(),t.readInt16(),t.readInt16()),unorm16:t=>t.readUint16()/65535,unorm16x2:t=>W(t.readUint16()/65535,t.readUint16()/65535),unorm16x4:t=>V(t.readUint16()/65535,t.readUint16()/65535,t.readUint16()/65535,t.readUint16()/65535),snorm16:t=>t.readInt16()/32767,snorm16x2:t=>W(t.readInt16()/32767,t.readInt16()/32767),snorm16x4:t=>V(t.readInt16()/32767,t.readInt16()/32767,t.readInt16()/32767,t.readInt16()/32767),float16(t){return t.readFloat16()},float16x2:t=>W(t.readFloat16(),t.readFloat16()),float16x4:t=>V(t.readFloat16(),t.readFloat16(),t.readFloat16(),t.readFloat16()),float32:t=>t.readFloat32(),float32x2:t=>W(t.readFloat32(),t.readFloat32()),float32x3:t=>N(t.readFloat32(),t.readFloat32(),t.readFloat32()),float32x4:t=>V(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32()),uint32:t=>t.readUint32(),uint32x2:t=>J(t.readUint32(),t.readUint32()),uint32x3:t=>C(t.readUint32(),t.readUint32(),t.readUint32()),uint32x4:t=>Z(t.readUint32(),t.readUint32(),t.readUint32(),t.readUint32()),sint32:t=>t.readInt32(),sint32x2:t=>Y(t.readInt32(),t.readInt32()),sint32x3:t=>de(t.readInt32(),t.readInt32(),t.readInt32()),sint32x4:t=>X(t.readInt32(),t.readInt32(),t.readInt32(),t.readInt32()),"unorm10-10-10-2"(t){let e=t.readUint32(),r=(e>>22)/1023,n=(e>>12&1023)/1023,a=(e>>2&1023)/1023,o=(e&3)/3;return V(r,n,a,o)},"unorm8x4-bgra"(t){let e=t.readByte()/255,r=t.readByte()/255,n=t.readByte()/255,a=t.readByte()/255;return V(n,r,e,a)},unstruct(t,e){let r={},n=e.propTypes;for(let[a,o]of Object.entries(n))r[a]=M(t,o);return r},disarray(t,e){let r=L(e),n=[];for(let a=0;a<e.elementCount;a++)$(t,r),n.push(M(t,e.elementType));return $(t,r),n},"loose-decorated"(t,e){$(t,q(e));let r=t.currentByteOffset,n=M(t,e.inner);return t.seekTo(r+I(e)),n}};function M(t,e){let r=lo[e.type];if(!r)throw new Error(`Cannot read data of type '${e.type}'.`);return r(t,e)}import{BufferWriter as mo}from"typed-binary";function ua(t,e){let r=I(t);if(r===0||e===void 0||e===null)return[];let n=new ArrayBuffer(r),a=new mo(n),o=[];function s(p,m,c,y){if(m!=null){if(_(p)||re(p)){let h=Ot(p);for(let[v,x]of Object.entries(h)){let P=p.propTypes[v];if(!P)continue;let F=m[v];F!==void 0&&s(P,F,c+x.offset,x.padding??y)}return}if(O(p)||gt(p)){let h=p,v=k(I(h.elementType),L(h.elementType));if(!Array.isArray(m))throw new Error("Partial value for array must be an array");let x=m??[];x.sort((P,F)=>P.idx-F.idx);for(let{idx:P,value:F}of x)s(h.elementType,F,c+P*v,v-I(h.elementType))}else{let h=I(p);a.seekTo(c),Re(a,p,m),o.push({start:c,end:c+h,padding:y})}}}if(s(t,e,0),o.length===0)return[];let i=[],u=o[0];for(let p=1;p<o.length;p++){let m=o[p];if(!m||!u)throw new Error("Internal error: missing segment");m.start===u.end+(u.padding??0)?(u.end=m.end,u.padding=m.padding):(i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),u=m)}if(!u)throw new Error("Internal error: missing segment");return i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),i}function ye(t){return!!t?.usableAsStorage}var Ye=class t extends Error{constructor(e){super(`Resource '${f(e)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,t.prototype)}};function jt(t){return!!t.usableAsUniform}var fa={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Je=class{constructor(e,r){this.usage=e;this.buffer=r;this[l]={dataType:r.dataType},this[D]=r}resourceType="buffer-usage";[l];[D];$name(e){return this.buffer.$name(e),this}[T](e){let r=this.buffer.dataType,n=e.getUniqueName(this),{group:a,binding:o}=e.allocateFixedEntry(this.usage==="uniform"?{uniform:r}:{storage:r,access:this.usage},this.buffer),s=fa[this.usage];return e.addDeclaration(`@group(${a}) @binding(${o}) var<${s}> ${n}: ${e.resolve(r).value};`),g(n,r)}toString(){return`${this.usage}:${f(this)??"<unnamed>"}`}get[w](){let e=this.buffer.dataType;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.usage}:${f(this)??"<unnamed>"}.$`},G)}get $(){let e=ve(),r=Se();if(e.type==="normal")throw new Tr(r?`Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:".$ and .value are inaccessible during normal JS execution. Try `.read()`");return e.type==="codegen"?this[w]:e.type==="simulate"?(e.buffers.has(this.buffer)||e.buffers.set(this.buffer,Ne(this.buffer.dataType,this.buffer.initial)),e.buffers.get(this.buffer)):se(e,"bufferUsage.ts#TgpuFixedBufferImpl/$")}get value(){return this.$}set $(e){let r=ve(),n=Se();if(r.type==="normal")throw new Tr(n?`Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:".$ and .value are inaccessible during normal JS execution. Try `.write()`");if(r.type==="codegen")throw new Error("Unreachable bufferUsage.ts#TgpuFixedBufferImpl/$");if(r.type==="simulate"){r.buffers.set(this.buffer,e);return}se(r,"bufferUsage.ts#TgpuFixedBufferImpl/$")}set value(e){this.$=e}},Xe=class{constructor(e,r,n){this.usage=e;this.dataType=r;this[l]={dataType:r},this.#e=n,S(this,n.key)}[l];resourceType="buffer-usage";#e;[T](e){let r=this.dataType,n=e.getUniqueName(this),a=e.allocateLayoutEntry(this.#e.layout),o=fa[this.usage];return e.addDeclaration(`@group(${a}) @binding(${this.#e.idx}) var<${o}> ${n}: ${e.resolve(r).value};`),g(n,r)}toString(){return`${this.usage}:${f(this)??"<unnamed>"}`}get[w](){let e=this.dataType;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.usage}:${f(this)??"<unnamed>"}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to buffer values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}},pa=new WeakMap;function da(t){if(!ye(t))throw new Error(`Cannot pass ${t} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let e=pa.get(t);return e||(e=new Je("mutable",t),pa.set(t,e)),e}var la=new WeakMap;function ca(t){if(!ye(t))throw new Error(`Cannot pass ${t} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let e=la.get(t);return e||(e=new Je("readonly",t),la.set(t,e)),e}var ma=new WeakMap;function ga(t){if(!jt(t))throw new Error(`Cannot pass ${t} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`);let e=ma.get(t);return e||(e=new Je("uniform",t),ma.set(t,e)),e}var go={uniform:ga,mutable:da,readonly:ca};function Ze(t,e,r){return we(e)?new Qt(t,e,r):new Qt(t,e,r,["storage","uniform"])}function pe(t){return t.resourceType==="buffer"}function yo(t){return!!t.usableAsVertex}var To=co(),Qt=class{constructor(e,r,n,a){this._group=e;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;Oe(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}[l]=!0;resourceType="buffer";flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC;_buffer=null;_ownBuffer;_destroyed=!1;_hostBuffer;initial;usableAsUniform=!1;usableAsStorage=!1;usableAsVertex=!1;usableAsIndex=!1;get buffer(){let e=this._group.device;if(this._destroyed)throw new Error("This buffer has been destroyed");return this._buffer||(this._buffer=e.createBuffer({size:I(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:f(this)??"<unnamed>"}),this.initial&&(this._writeToTarget(this._buffer.getMappedRange(),this.initial),this._buffer.unmap())),this._buffer}get destroyed(){return this._destroyed}$name(e){return S(this,e),this._buffer&&(this._buffer.label=e),this}$usage(...e){for(let r of e){if(this._disallowedUsages?.includes(r))throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${r}`);this.flags|=r==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=r==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=r==="vertex"?GPUBufferUsage.VERTEX:0,this.flags|=r==="index"?GPUBufferUsage.INDEX:0,this.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex",this.usableAsIndex=this.usableAsIndex||r==="index"}return this}$addFlags(e){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return e&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):e&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=e,this)}compileWriter(){Ar(this.dataType)}_writeToTarget(e,r){let n=Ar(this.dataType);if(n)try{n(new DataView(e),0,r,To==="little");return}catch(a){console.error(`Error when using compiled writer for buffer ${f(this)??"<unnamed>"} - this is likely a bug, please submit an issue at https://github.com/software-mansion/TypeGPU/issues
16
- Using fallback writer instead.`,a)}Re(new fo(e),this.dataType,r)}write(e){let r=this.buffer,n=this._group.device;if(r.mapState==="mapped"){let o=r.getMappedRange();this._writeToTarget(o,e);return}let a=I(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(a)),this._group.flush(),this._writeToTarget(this._hostBuffer,e),n.queue.writeBuffer(r,0,this._hostBuffer,0,a)}writePartial(e){let r=this.buffer,n=this._group.device,a=ua(this.dataType,e);if(r.mapState==="mapped"){let o=r.getMappedRange(),s=new Uint8Array(o);for(let i of a)s.set(i.data,i.data.byteOffset)}else for(let o of a)n.queue.writeBuffer(r,o.data.byteOffset,o.data,0,o.data.byteLength)}clear(){let e=this.buffer,r=this._group.device;if(e.mapState==="mapped"){new Uint8Array(e.getMappedRange()).fill(0);return}this._group.flush();let n=r.createCommandEncoder();n.clearBuffer(e),r.queue.submit([n.finish()])}copyFrom(e){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=I(this.dataType);this._group.commandEncoder.copyBufferToBuffer(e.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let e=this.buffer,r=this._group.device;if(e.mapState==="mapped"){let s=e.getMappedRange();return M(new Lr(s),this.dataType)}if(e.usage&GPUBufferUsage.MAP_READ){await e.mapAsync(GPUMapMode.READ);let s=e.getMappedRange(),i=M(new Lr(s),this.dataType);return e.unmap(),i}let n=r.createBuffer({size:I(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(e,0,n,0,I(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,I(this.dataType));let o=M(new Lr(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(e){return go[e]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${f(this)??"<unnamed>"}`}};function ya(t,e){return new Kt(At(),t,e)}function Ta(t,e){return new Kt(Lt(),t,e)}function et(t){let e=t;return e?.resourceType==="sampler"&&!!e[l]}function tt(t){let e=t;return e?.resourceType==="sampler-comparison"&&!!e[l]}var Ht=class{constructor(e,r){this.schema=e;this.#e=r,this.resourceType=e.type==="sampler_comparison"?"sampler-comparison":"sampler",S(this,r.key)}[l]={unwrap:void 0};resourceType;#e;[T](e){let r=e.getUniqueName(this),n=e.allocateLayoutEntry(this.#e.layout);return e.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${e.resolve(this.schema).value};`),g(r,this.schema)}get[w](){let e=this.schema;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.")}get value(){return this.$}toString(){return`${this.resourceType}:${f(this)??"<unnamed>"}`}},Kt=class{constructor(e,r,n){this.schema=e;this.#t=r,this.#n=n,this.resourceType=e.type==="sampler_comparison"?"sampler-comparison":"sampler",this[l]={unwrap:()=>(this.#r||(this.#r=this.#n.device.createSampler({...this.#t,label:f(this)??"<unnamed>"})),this.#r)},this.#e=r.minFilter==="linear"||r.magFilter==="linear"||r.mipmapFilter==="linear"}[l];resourceType;#e;#r=null;#t;#n;[T](e){let r=e.getUniqueName(this),{group:n,binding:a}=e.allocateFixedEntry(this.schema.type==="sampler_comparison"?{sampler:"comparison"}:{sampler:this.#e?"filtering":"non-filtering"},this);return e.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${e.resolve(this.schema).value};`),g(r,this.schema)}get[w](){let e=this.schema;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.")}get value(){return this.$}$name(e){return S(this,e),this}toString(){return`${this.resourceType}:${f(this)??"<unnamed>"}`}};var Yt=class{constructor(e,r){this.schema=e;this.#e=r,S(this,r.key)}resourceType="external-texture";[l]=!0;#e;[T](e){let r=e.getUniqueName(this),n=e.allocateLayoutEntry(this.#e.layout);return e.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${e.resolve(this.schema).value};`),g(r,On())}get[w](){let e=this.schema;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`textureExternal:${f(this)??"<unnamed>"}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}toString(){return`textureExternal:${f(this)??"<unnamed>"}`}};function Jt(t){return"displayWidth"in t&&"displayHeight"in t?{width:t.displayWidth,height:t.displayHeight}:{width:t.width,height:t.height}}var Gr=new WeakMap;function ha(t){let e=Gr.get(t);return e||(e=new Map,Gr.set(t,e)),e}function xa(t){let e=Gr.get(t);e&&e.clear()}function wa(t,e,r=0,n){if(e.dimension!=="2d")throw new Error("Cannot generate mipmaps for non-2D textures: only 2D textures are currently supported.");let a=n??e.mipLevelCount-r,o=br(e.format,t);if(![...o.sampleTypes].some(i=>i==="float"||i==="unfilterable-float"))throw new Error(`Cannot generate mipmaps for format '${e.format}': only float and unfilterable-float formats are currently supported.`);if(!o.canRenderAttachment)throw new Error(`Cannot generate mipmaps for format '${e.format}': format does not support render attachments.`);for(let i=0;i<e.depthOrArrayLayers;i++)for(let u=r;u<r+a-1;u++){let p=u,m=u+1;xo(t,e,p,m,i)}}function ba(t,e,r,n){if(e.dimension==="3d")throw new Error("Cannot resample to 3D textures: only 2D textures are currently supported.");let a=Ae[e.format];if(![...a.sampleTypes].some(s=>s==="float"||s==="unfilterable-float"))throw new Error(`Cannot resample to format '${e.format}': only float and unfilterable-float formats are currently supported.`);if(!a.canRenderAttachment)throw new Error(`Cannot resample to format '${e.format}': format does not support render attachments.`);return ho(t,e,r,n)}function ho(t,e,r,n=0){let o=[...Ae[e.format].sampleTypes].includes("float"),s=`${o?"filterable":"unfilterable"}`,i=ha(t),u=i.get(s);if(!u){let F=t.createShaderModule({code:`
1
+ import{a as Pt,b as $n,c as Dt,d as Bt,e as pe,f as je,g as Le,h as Cn}from"./chunk-CGQB3SER.js";import{a as Re,b as br,c as Nn,d as qn,e as jn,i as Gt,j as Ct,k as Qn}from"./chunk-PWBIFP67.js";import{Q as Wn,R as Mn,S as He,T as kn,j as Be,ja as On,jb as Rt,k as Ae,l as $e,n as Dn,o as Ft,p as Bn,q as An,r as E,s as ge,t as wr,u as $t,v as Lt,w as En,x as Vn,y as Qe,z as _n}from"./chunk-ECR2EGZX.js";import{$a as vt,Aa as N,B as Se,Ba as Un,C as z,Ca as Ue,D as _,Da as W,Ea as se,F as yn,Fa as ie,Ga as Fn,L as ct,La as xr,M as Tn,Q as hn,Qa as wt,R as gt,Ra as G,S as re,T as xn,Ta as bt,U as ne,Ua as St,V as ae,Va as Pn,W as ke,Xa as M,Ya as Fe,Za as Y,_a as J,a as p,aa as g,ab as q,b as S,ba as oe,bb as Pe,c as D,ca as ve,cb as ce,cc as Rn,d as K,da as dr,db as C,dc as $,e as L,ea as cr,eb as It,ec as j,f as h,fa as gr,fb as V,ga as Na,gb as De,gc as k,h as mt,ha as fe,hb as X,hc as I,i as te,ia as Oe,ib as Z,j as c,ja as yr,jb as Ut,k as v,ka as Tr,l as ft,la as yt,lb as Ne,m as dt,ma as Tt,mb as Ln,n as un,na as ht,nb as ye,o as pn,oa as hr,oc as ue,p as ln,pa as de,pc as At,q as A,qa as wn,qc as qe,ra as bn,rc as Gn,s as mr,sa as Sn,t as fr,ta as vn,tc as Sr,u as mn,uc as zn,v as fn,wa as ze,x as dn,xa as In,y as cn,ya as Ie,z as gn,za as xt}from"./chunk-CRZWTZM2.js";function Hn(e){return new vr(e)}var vr=class{constructor(t){this.declaration=t}[p]=!0;externalsToApply=[];$uses(t){return this.externalsToApply.push(t),this}[h](t){let r={};for(let a of this.externalsToApply)Pt(r,a);let n=Bt(t,r,this.declaration);return t.addDeclaration(n),g("",A)}toString(){return`declare: ${this.declaration}`}};function Et(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[je(e.in)]:[],returnType:A,workgroupSize:[e.workgroupSize[0]??1,e.workgroupSize[1]??1,e.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>qa(t,e.workgroupSize,Le(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function qa(e,t,r){let n=pe(r,`@compute @workgroup_size(${t.join(", ")}) `),a=e.argTypes[0];return{shell:e,$uses(s){return n.applyExternals(s),this},[p]:!0,[D]:n,$name(s){return v(n,s),ft(a)&&a.$name(`${s}_Input`),this},[h](s){return n.resolve(s,e.argTypes,e.returnType)},toString(){return`computeFn:${c(n)??"<unnamed>"}`}}}function U(e,t){let r={[p]:!0,argTypes:e,returnType:t??A,isEntry:!1};return Object.assign((a,...o)=>Qa(r,Le(a,...o)),r)}function Ke(e){return mt(e)&&e?.resourceType==="function"}function ja([e,t]){return`${c(e)??"<unnamed>"}=${t}`}function Qa(e,t){let r=pe(t,""),n={shell:e,resourceType:"function",$uses(s){return r.applyExternals(s),this},[D]:r,$name(s){return v(r,s),this},with(s,i){return Kn(o,[[de(s)?s.slot:s,i]])},[h](s){return typeof t=="string"&&($n(t,e.argTypes,r.applyExternals),Dt(t,e.returnType,r.applyExternals)),r.resolve(s,e.argTypes,e.returnType)}},a=xr((...s)=>In(()=>{try{if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");let i=s.map((l,m)=>qe(e.argTypes[m],l)),u=t(...i);return qe(e.returnType,u)}catch(i){throw i instanceof dr?i.appendToTrace(o):new dr(i,[o])}}),(...s)=>g(new Vt(o,s),e.returnType),"tgpuFnCall",e.argTypes),o=Object.assign(a,n);return o[p].implementation=t,Object.defineProperty(o,"toString",{value(){return`fn:${c(r)??"<unnamed>"}`}}),o}function Kn(e,t){let r={resourceType:"function",shell:e.shell,[K]:{inner:e,pairs:t},$uses(o){return e.$uses(o),this},[D]:e,$name(o){return e.$name(o),this},with(o,s){return Kn(a,[...t,[de(o)?o.slot:o,s]])}},n=xr((...o)=>e(...o),(...o)=>g(new Vt(a,o),e.shell.returnType),"tgpuFnCall",e.shell.argTypes),a=Object.assign(n,r);return a[p].implementation=e[p].implementation,Object.defineProperty(a,"toString",{value(){return`fn:${c(e)??"<unnamed>"}[${t.map(ja).join(", ")}]`}}),a[p].implementation=e[p].implementation,a}var Vt=class{[p]=!0;[L];[D];#e;#r;constructor(t,r){this.#e=t,this.#r=r,this[D]=t,this[L]=g(this,this.#e.shell.returnType)}[h](t){return t.withResetIndentLevel(()=>g(se`${t.resolve(this.#e).value}(${this.#r})`,this.#e.shell.returnType))}toString(){return`call:${c(this)??"<unnamed>"}`}};function Yn(e){let t={in:e.in,out:e.out,returnType:je(e.out),isEntry:!0},r=(n,...a)=>Ha(t,Le(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Ha(e,t){let r=pe(t,"@fragment "),n=e.returnType;return typeof t=="string"&&Dt(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,$uses(o){return r.applyExternals(o),this},[p]:!0,[D]:r,$name(o){return v(r,o),ft(n)&&n.$name(`${o}_Output`),this},[h](o){let s=e.in?je(e.in,o.varyingLocations).$name(`${c(this)??""}_Input`):void 0;return s&&r.applyExternals({In:s}),r.applyExternals({Out:n}),r.resolve(o,s?[s]:[],e.returnType)},toString(){return`fragmentFn:${c(r)??"<unnamed>"}`}}}var Jn=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield"]);function Ir(e){if(e==="_"||e.startsWith("__")||/\s/.test(e))throw new Error(`Invalid identifier '${e}'. Choose an identifier without whitespaces or leading underscores.`);let t=e.split("_")[0];return!Jn.has(t)}var _t=class{makeValid(t){return Ir(t)?t:this.makeUnique(t)}},Wt=class extends _t{lastUniqueId=0;makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},Mt=class extends _t{_usedNames=new Set(Jn);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 Xn(e,t){let r=pe(t,"");return{[p]:!0,[D]:r,resourceType:"shellless-impl",[h](n){return r.resolve(n,e,void 0)},toString(){return`fn*:${c(r)??"<unnamed>"}`}}}var kt=class{cache=new Map;get(t,r){let n=un(t);if(!n?.ast)return;if(!r&&n.ast.params.length>0)throw new Error(`Cannot resolve '${c(t)}' directly, because it expects arguments. Either call it from another function, or wrap it in a shell`);let a=(r??[]).map(i=>Ft(i.dataType)),o=this.cache.get(t);if(o){let i=o.find(u=>u.argTypes.every((l,m)=>l===a[m]));if(i)return i.value}else o=[],this.cache.set(t,o);let s=Xn(a,t);return o.push({argTypes:a,value:s}),s}};var Ur=class{[p];constructor(t){this[p]={nameRegistry:t,shelllessRepo:new kt,memoizedResolves:new WeakMap,memoizedDerived:new WeakMap,listeners:{name:new Set}}}on(t,r){if(t==="name"){let n=this[p].listeners.name;return n.add(r),()=>n.delete(r)}throw new Error(`Unsupported event: ${t}`)}};function Zn(e,t){let r=e.nameRegistry.makeUnique(c(t));for(let n of e.listeners.name)n({target:t,name:r});return r}function Q(e){let{names:t="random"}=e||{};return new Ur(t==="strict"?new Mt:new Wt)}function Ye(e){return typeof e?.format=="string"}function ea(e,t){let r=[];if(ae(e)){if(!Ye(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:ne(e)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[s,i]of Object.entries(e)){if(ue(i))continue;let u=t[s];if(!u)throw new Error(`An attribute by the name of '${s}' was not provided to the shader.`);let l=u._layout,m=a.get(l);m||(r.push(l),m=[],n.push({arrayStride:l.stride,stepMode:l.stepMode,attributes:m}),a.set(l,m)),o=ne(i)??o,m.push({format:u.format,offset:u.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var Ka=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","vec2<bool>","vec3<bool>","vec4<bool>","mat2x2f","mat3x3f","mat4x4f","texture_external"];function Ya(e){return Ka.includes(e.type)}function Fr(e,[t,r]){if(!Ir(t))throw new Error(`Property key '${t}' is a reserved WGSL word. Choose a different name.`);return` ${At(r)}${t}: ${e.resolve(r).value},
2
+ `}function Ja(e,t){if(t[p].isAbstruct)throw new Error("Cannot resolve abstract struct types to WGSL.");let r=e.getUniqueName(t);return e.addDeclaration(`struct ${r} {
3
+ ${Object.entries(t.propTypes).map(n=>Fr(e,n)).join("")}}`),r}function Xa(e,t){let r=e.getUniqueName(t);return e.addDeclaration(`struct ${r} {
4
+ ${Object.entries(t.propTypes).map(n=>Ye(n[1])?Fr(e,[n[0],ye[n[1].format]]):Fr(e,n)).join("")}
5
+ }`),r}function Za(e,t){let r=e.resolve(t.elementType).value;return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function eo(e,t){let r=e.resolve(Ye(t.elementType)?ye[t.elementType.format]:t.elementType).value;return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Pr(e,t){if(hn(t))return t.type==="unstruct"?Xa(e,t):t.type==="disarray"?eo(e,t):t.type==="loose-decorated"?e.resolve(Ye(t.inner)?ye[t.inner.format]:t.inner).value:e.resolve(ye[t.type]).value;if(Ya(t))return t.type;if(t.type==="struct")return Ja(e,t);if(t.type==="array")return Za(e,t);if(t.type==="atomic")return`atomic<${Pr(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner).value;if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner).value}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner).value}>`;if(t.type==="abstractInt"||t.type==="abstractFloat"||t.type==="void"||t.type==="u16")throw new Error(`${t.type} has no representation in WGSL`);if(He(t))return`${t.type}<${t.format}, ${_n[t.access]}>`;if(Mn(t))return t.type.startsWith("texture_depth")?t.type:`${t.type}<${t.sampleType.type}>`;if(Vn(t)||En(t))return t.type;ie(t,"resolveData")}var Ge=class e{constructor(t){this.bindings=t}with(t,r){return new e([...this.bindings,[de(t)?t.slot:t,r]])}pipe(t){let r=t(this);return new e([...this.bindings,...r.bindings])}};function*ta(e){let t=0;for(;;)e.has(t)||(yield t),t++}import{BufferReader as Ar,BufferWriter as uo,getSystemEndianness as po}from"typed-binary";import{Measurer as ro}from"typed-binary";function to(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 B=to;var ra=new WeakMap;function Ot(e){let t=ra.get(e);if(t)return t;let r=new ro,n={},a;for(let o in e.propTypes){let s=e.propTypes[o];if(s===void 0)throw new Error(`Property ${o} is undefined in struct`);let i=r.size;B(r,re(e)?j(s):$(s)),a&&(a.padding=r.size-i);let u=I(s);n[o]={offset:r.size,size:u},a=n[o],r.add(u)}return a&&(a.padding=k(I(e),$(e))-r.size),ra.set(e,n),n}var no=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),Dr=new WeakMap,zt={u32:"u32",vec2u:"u32",vec3u:"u32",vec4u:"u32",u16:"u16",i32:"i32",vec2i:"i32",vec3i:"i32",vec4i:"i32",f32:"f32",vec2f:"f32",vec3f:"f32",vec4f:"f32",f16:"f16",vec2h:"f16",vec3h:"f16",vec4h:"f16",mat2x2f:"f32",mat3x3f:"f32",mat4x4f:"f32"},ao={uint8:"u8",uint8x2:"u8",uint8x4:"u8",sint8:"i8",sint8x2:"i8",sint8x4:"i8",unorm8:"u8",unorm8x2:"u8",unorm8x4:"u8",snorm8:"i8",snorm8x2:"i8",snorm8x4:"i8",uint16:"u16",uint16x2:"u16",uint16x4:"u16",sint16:"i16",sint16x2:"i16",sint16x4:"i16",unorm16:"u16",unorm16x2:"u16",unorm16x4:"u16",snorm16:"i16",snorm16x2:"i16",snorm16x4:"i16",float16:"f16",float16x2:"f16",float16x4:"f16",float32:"f32",float32x2:"f32",float32x3:"f32",float32x4:"f32",uint32:"u32",uint32x2:"u32",uint32x3:"u32",uint32x4:"u32",sint32:"i32",sint32x2:"i32",sint32x3:"i32",sint32x4:"i32"},Nt={u32:"setUint32",i32:"setInt32",f32:"setFloat32",u16:"setUint16",i16:"setInt16",f16:"setFloat16",u8:"setUint8",i8:"setInt8"},oo={unorm8:e=>`Math.round(${e} * 255)`,unorm8x2:e=>`Math.round(${e} * 255)`,unorm8x4:e=>`Math.round(${e} * 255)`,snorm8:e=>`Math.round(${e} * 127)`,snorm8x2:e=>`Math.round(${e} * 127)`,snorm8x4:e=>`Math.round(${e} * 127)`,unorm16:e=>`Math.round(${e} * 65535)`,unorm16x2:e=>`Math.round(${e} * 65535)`,unorm16x4:e=>`Math.round(${e} * 65535)`,snorm16:e=>`Math.round(${e} * 32767)`,snorm16x2:e=>`Math.round(${e} * 32767)`,snorm16x4:e=>`Math.round(${e} * 32767)`},na={"unorm10-10-10-2":{writeFunction:"setUint32",generator:(e,t)=>`output.setUint32(${e}, ((${t}.x*1023&0x3FF)<<22)|((${t}.y*1023&0x3FF)<<12)|((${t}.z*1023&0x3FF)<<2)|(${t}.w*3&3), littleEndian);
6
+ `},"unorm8x4-bgra":{writeFunction:"setUint8",generator:(e,t)=>{let r=["z","y","x","w"],n="";for(let a=0;a<4;a++)n+=`output.setUint8((${e} + ${a}), Math.round(${t}.${r[a]} * 255), littleEndian);
7
+ `;return n}}};function qt(e,t,r,n=0){let a=["i","j","k"][n]||`i${n}`;if(yn(e)||ct(e))return qt(e.inner,t,r,n);if(_(e)||re(e)){let s=Ot(e),i="";for(let[u,l]of Object.entries(s)){let m=e.propTypes[u];m&&(i+=qt(m,`(${t} + ${l.offset})`,`${r}.${u}`,n))}return i}if(z(e)||gt(e)){let s=k(I(e.elementType),$(e)),i="";return i+=`for (let ${a} = 0; ${a} < ${e.elementCount}; ${a}++) {
8
+ `,i+=qt(e.elementType,`(${t} + ${a} * ${s})`,`${r}[${a}]`,n+1),i+=`}
9
+ `,i}if(fn(e)){let s=zt[e.type],i="",u=Nt[s],l=["x","y","z","w"],m=mr(e)?2:fr(e)?3:4;for(let y=0;y<m;y++)i+=`output.${u}((${t} + ${y*4}), ${r}.${l[y]}, littleEndian);
10
+ `;return i}if(gn(e)){let s=zt[e.type],i=Nt[s],u=dn(e)?2:cn(e)?3:4,l=u*u,m=k(u*4,8),y="";for(let f=0;f<l;f++){let T=Math.floor(f/u),w=f%u,x=T*m+w*4;y+=`output.${i}((${t} + ${x}), ${r}.columns[${T}].${["x","y","z","w"][w]}, littleEndian);
11
+ `}return y}if(Rn(e)){let s=e.type;if(s in na)return na[s].generator(t,r);let i=ao[s],u=Nt[i],l=ye[s],m=mn(l)?4:fr(l)?3:mr(l)?2:1,y=i==="u8"||i==="i8"?1:i==="u16"||i==="i16"||i==="f16"?2:4,f=["x","y","z","w"],T=oo[s],w="";for(let x=0;x<m;x++){let P=m===1?r:`${r}.${f[x]}`,F=T?T(P):P;w+=`output.${u}((${t} + ${x*y}), ${F}, littleEndian);
12
+ `}return w}if(!Object.hasOwn(zt,e.type))throw new Error(`Primitive ${e.type} is unsupported by compiled writer`);let o=zt[e.type];return`output.${Nt[o]}(${t}, ${r}, littleEndian);
13
+ `}function Br(e){if(!no){console.warn("This environment does not allow eval - using default writer as fallback");return}if(Dr.has(e))return Dr.get(e);try{let t=qt(e,"offset","value",0),r=new Function("output","offset","value","littleEndian=true",t);return Dr.set(e,r),r}catch(t){console.warn(`Failed to compile writer for schema: ${e}
14
+ Reason: ${t instanceof Error?t.message:String(t)}
15
+ Falling back to default writer`)}}var Ce={bool(){throw new Error("Booleans are not host-shareable")},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)},u16(e,t,r){e.writeUint16(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)},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},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)},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},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)},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},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=$(t);B(e,n);for(let[a,o]of Object.entries(t.propTypes))B(e,$(o)),Ee(e,o,r[a]);B(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=$(t);B(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)B(e,n),Ee(e,t.elementType,r[o]);e.seekTo(a+I(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){Ce[t.inner.type]?.(e,t,r)},decorated(e,t,r){let n=j(t);B(e,n);let a=e.currentByteOffset;Ce[t.inner?.type]?.(e,t.inner,r),e.seekTo(a+I(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(Math.round(r*255))},unorm8x2(e,t,r){e.writeUint8(Math.round(r.x*255)),e.writeUint8(Math.round(r.y*255))},unorm8x4(e,t,r){e.writeUint8(Math.round(r.x*255)),e.writeUint8(Math.round(r.y*255)),e.writeUint8(Math.round(r.z*255)),e.writeUint8(Math.round(r.w*255))},snorm8(e,t,r){e.writeInt8(Math.round(r*127))},snorm8x2(e,t,r){e.writeInt8(Math.round(r.x*127)),e.writeInt8(Math.round(r.y*127))},snorm8x4(e,t,r){e.writeInt8(Math.round(r.x*127)),e.writeInt8(Math.round(r.y*127)),e.writeInt8(Math.round(r.z*127)),e.writeInt8(Math.round(r.w*127))},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.writeInt16(Math.round(r*32767))},snorm16x2(e,t,r){e.writeInt16(Math.round(r.x*32767)),e.writeInt16(Math.round(r.y*32767))},snorm16x4(e,t,r){e.writeInt16(Math.round(r.x*32767)),e.writeInt16(Math.round(r.y*32767)),e.writeInt16(Math.round(r.z*32767)),e.writeInt16(Math.round(r.w*32767))},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.y*1023&1023)<<12,n|=(r.z*1023&1023)<<2,n|=r.w*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){let n=$(t);B(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)B(e,n),Ce[t.elementType?.type]?.(e,t.elementType,r[o]);e.seekTo(a+I(t))},unstruct(e,t,r){let n=t.propTypes;for(let[a,o]of Object.entries(n))Ce[o.type]?.(e,o,r[a])},"loose-decorated"(e,t,r){let n=j(t);B(e,n);let a=e.currentByteOffset,o=Ce[t.inner?.type];return o?.(e,t.inner,r),e.seekTo(a+I(t)),r}};function Ee(e,t,r){let n=Ce[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var so={bool(){throw new Error("Booleans are not host-shareable")},f32(e){return e.readFloat32()},f16(e){return e.readFloat16()},i32(e){return e.readInt32()},u32(e){return e.readUint32()},u16(e){return e.readUint16()},vec2f(e){return M(e.readFloat32(),e.readFloat32())},vec3f(e){return q(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return V(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Fe(e.readFloat16(),e.readFloat16())},vec3h(e){return Pe(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return De(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return Y(e.readInt32(),e.readInt32())},vec3i(e){return ce(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return X(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return J(e.readUint32(),e.readUint32())},vec3u(e){return C(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return Z(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},mat2x2f(e){return Be(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return Ae(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return $e(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=$(t);B(e,r);let n={},a=t.propTypes;for(let[o,s]of Object.entries(a))B(e,$(s)),n[o]=O(e,s);return B(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=$(t),n=[];for(let a=0;a<t.elementCount;a++){B(e,r);let o=t.elementType,s=O(e,o);n.push(s)}return B(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return O(e,t.inner)},decorated(e,t){let r=j(t);B(e,r);let n=e.currentByteOffset,a=O(e,t.inner);return e.seekTo(n+I(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>J(e.readUint8(),e.readUint8()),uint8x4:e=>Z(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>Y(e.readInt8(),e.readInt8()),sint8x4:e=>X(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>M(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>V(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>e.readInt8()/127,snorm8x2:e=>M(e.readInt8()/127,e.readInt8()/127),snorm8x4:e=>V(e.readInt8()/127,e.readInt8()/127,e.readInt8()/127,e.readInt8()/127),uint16:e=>e.readUint16(),uint16x2:e=>J(e.readUint16(),e.readUint16()),uint16x4:e=>Z(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>Y(e.readInt16(),e.readInt16()),sint16x4:e=>X(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>M(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>V(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>e.readInt16()/32767,snorm16x2:e=>M(e.readInt16()/32767,e.readInt16()/32767),snorm16x4:e=>V(e.readInt16()/32767,e.readInt16()/32767,e.readInt16()/32767,e.readInt16()/32767),float16(e){return e.readFloat16()},float16x2:e=>M(e.readFloat16(),e.readFloat16()),float16x4:e=>V(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>M(e.readFloat32(),e.readFloat32()),float32x3:e=>q(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>V(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>J(e.readUint32(),e.readUint32()),uint32x3:e=>C(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>Z(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>Y(e.readInt32(),e.readInt32()),sint32x3:e=>ce(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>X(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 V(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 V(n,r,t,a)},unstruct(e,t){let r={},n=t.propTypes;for(let[a,o]of Object.entries(n))r[a]=O(e,o);return r},disarray(e,t){let r=$(t),n=[];for(let a=0;a<t.elementCount;a++)B(e,r),n.push(O(e,t.elementType));return B(e,r),n},"loose-decorated"(e,t){B(e,j(t));let r=e.currentByteOffset,n=O(e,t.inner);return e.seekTo(r+I(t)),n}};function O(e,t){let r=so[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as io}from"typed-binary";function aa(e,t){let r=I(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new io(n),o=[];function s(l,m,y,f){if(m!=null){if(_(l)||re(l)){let T=Ot(l);for(let[w,x]of Object.entries(T)){let P=l.propTypes[w];if(!P)continue;let F=m[w];F!==void 0&&s(P,F,y+x.offset,x.padding??f)}return}if(z(l)||gt(l)){let T=l,w=k(I(T.elementType),$(T.elementType));if(!Array.isArray(m))throw new Error("Partial value for array must be an array");let x=m??[];x.sort((P,F)=>P.idx-F.idx);for(let{idx:P,value:F}of x)s(T.elementType,F,y+P*w,w-I(T.elementType))}else{let T=I(l);a.seekTo(y),Ee(a,l,m),o.push({start:y,end:y+T,padding:f})}}}if(s(e,t,0),o.length===0)return[];let i=[],u=o[0];for(let l=1;l<o.length;l++){let m=o[l];if(!m||!u)throw new Error("Internal error: missing segment");m.start===u.end+(u.padding??0)?(u.end=m.end,u.padding=m.padding):(i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),u=m)}if(!u)throw new Error("Internal error: missing segment");return i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),i}function Te(e){return!!e?.usableAsStorage}var Je=class e extends Error{constructor(t){super(`Resource '${c(t)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function jt(e){return!!e.usableAsUniform}var ua={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Xe=class{constructor(t,r){this.usage=t;this.buffer=r;this[p]={dataType:r.dataType},this[D]=r}resourceType="buffer-usage";[p];[D];$name(t){return this.buffer.$name(t),this}[h](t){let r=this.buffer.dataType,n=t.getUniqueName(this),{group:a,binding:o}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:r}:{storage:r,access:this.usage},this.buffer),s=ua[this.usage];return t.addDeclaration(`@group(${a}) @binding(${o}) var<${s}> ${n}: ${t.resolve(r).value};`),g(n,r)}toString(){return`${this.usage}:${c(this)??"<unnamed>"}`}get[S](){let t=this.buffer.dataType;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.usage}:${c(this)??"<unnamed>"}.$`},E)}get $(){let t=Ue(),r=Ie();if(t.type==="normal")throw new Tr(r?`Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:".$ and .value are inaccessible during normal JS execution. Try `.read()`");return t.type==="codegen"?this[S]:t.type==="simulate"?(t.buffers.has(this.buffer)||t.buffers.set(this.buffer,qe(this.buffer.dataType,this.buffer.initial)),t.buffers.get(this.buffer)):ie(t,"bufferUsage.ts#TgpuFixedBufferImpl/$")}get value(){return this.$}set $(t){let r=Ue(),n=Ie();if(r.type==="normal")throw new Tr(n?`Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:".$ and .value are inaccessible during normal JS execution. Try `.write()`");if(r.type==="codegen")throw new Error("Unreachable bufferUsage.ts#TgpuFixedBufferImpl/$");if(r.type==="simulate"){r.buffers.set(this.buffer,t);return}ie(r,"bufferUsage.ts#TgpuFixedBufferImpl/$")}set value(t){this.$=t}},Ze=class{constructor(t,r,n){this.usage=t;this.dataType=r;this[p]={dataType:r},this.#e=n,v(this,n.key)}[p];resourceType="buffer-usage";#e;[h](t){let r=this.dataType,n=t.getUniqueName(this),a=t.allocateLayoutEntry(this.#e.layout),o=ua[this.usage];return t.addDeclaration(`@group(${a}) @binding(${this.#e.idx}) var<${o}> ${n}: ${t.resolve(r).value};`),g(n,r)}toString(){return`${this.usage}:${c(this)??"<unnamed>"}`}get[S](){let t=this.dataType;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.usage}:${c(this)??"<unnamed>"}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to buffer values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}},oa=new WeakMap;function pa(e){if(!Te(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=oa.get(e);return t||(t=new Xe("mutable",e),oa.set(e,t)),t}var sa=new WeakMap;function la(e){if(!Te(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=sa.get(e);return t||(t=new Xe("readonly",e),sa.set(e,t)),t}var ia=new WeakMap;function ma(e){if(!jt(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=ia.get(e);return t||(t=new Xe("uniform",e),ia.set(e,t)),t}var lo={uniform:ma,mutable:pa,readonly:la};function et(e,t,r){return Se(t)?new Qt(e,t,r):new Qt(e,t,r,["storage","uniform"])}function le(e){return e.resourceType==="buffer"}function mo(e){return!!e.usableAsVertex}var fo=po(),Qt=class{constructor(t,r,n,a){this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;this.#e=t.device,ze(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}[p]=!0;resourceType="buffer";flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC;#e;_buffer=null;_ownBuffer;_destroyed=!1;_hostBuffer;initial;usableAsUniform=!1;usableAsStorage=!1;usableAsVertex=!1;usableAsIndex=!1;get buffer(){if(this._destroyed)throw new Error("This buffer has been destroyed");return this._buffer||(this._buffer=this.#e.createBuffer({size:I(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:c(this)??"<unnamed>"}),this.initial&&(this._writeToTarget(this._buffer.getMappedRange(),this.initial),this._buffer.unmap())),this._buffer}get destroyed(){return this._destroyed}$name(t){return v(this,t),this._buffer&&(this._buffer.label=t),this}$usage(...t){for(let r of t){if(this._disallowedUsages?.includes(r))throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${r}`);this.flags|=r==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=r==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=r==="vertex"?GPUBufferUsage.VERTEX:0,this.flags|=r==="index"?GPUBufferUsage.INDEX:0,this.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex",this.usableAsIndex=this.usableAsIndex||r==="index"}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)}compileWriter(){Br(this.dataType)}_writeToTarget(t,r){let n=Br(this.dataType);if(n)try{n(new DataView(t),0,r,fo==="little");return}catch(a){console.error(`Error when using compiled writer for buffer ${c(this)??"<unnamed>"} - this is likely a bug, please submit an issue at https://github.com/software-mansion/TypeGPU/issues
16
+ Using fallback writer instead.`,a)}Ee(new uo(t),this.dataType,r)}write(t){let r=this.buffer;if(r.mapState==="mapped"){let a=r.getMappedRange();this._writeToTarget(a,t);return}let n=I(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(n)),this._writeToTarget(this._hostBuffer,t),this.#e.queue.writeBuffer(r,0,this._hostBuffer,0,n)}writePartial(t){let r=this.buffer,n=aa(this.dataType,t);if(r.mapState==="mapped"){let a=r.getMappedRange(),o=new Uint8Array(a);for(let s of n)o.set(s.data,s.data.byteOffset)}else for(let a of n)this.#e.queue.writeBuffer(r,a.data.byteOffset,a.data,0,a.data.byteLength)}clear(){let t=this.buffer;if(t.mapState==="mapped"){new Uint8Array(t.getMappedRange()).fill(0);return}let r=this.#e.createCommandEncoder();r.clearBuffer(t),this.#e.queue.submit([r.finish()])}copyFrom(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=I(this.dataType),n=this.#e.createCommandEncoder();n.copyBufferToBuffer(t.buffer,0,this.buffer,0,r),this.#e.queue.submit([n.finish()])}async read(){let t=this.buffer;if(t.mapState==="mapped"){let o=t.getMappedRange();return O(new Ar(o),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let o=t.getMappedRange(),s=O(new Ar(o),this.dataType);return t.unmap(),s}let r=this.#e.createBuffer({size:I(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),n=this.#e.createCommandEncoder();n.copyBufferToBuffer(t,0,r,0,I(this.dataType)),this.#e.queue.submit([n.finish()]),await r.mapAsync(GPUMapMode.READ,0,I(this.dataType));let a=O(new Ar(r.getMappedRange()),this.dataType);return r.unmap(),r.destroy(),a}as(t){return lo[t]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${c(this)??"<unnamed>"}`}};function fa(e,t){return new Kt($t(),e,t)}function da(e,t){return new Kt(Lt(),e,t)}function tt(e){let t=e;return t?.resourceType==="sampler"&&!!t[p]}function rt(e){let t=e;return t?.resourceType==="sampler-comparison"&&!!t[p]}var Ht=class{constructor(t,r){this.schema=t;this.#e=r,this.resourceType=t.type==="sampler_comparison"?"sampler-comparison":"sampler",v(this,r.key)}[p]={unwrap:void 0};resourceType;#e;[h](t){let r=t.getUniqueName(this),n=t.allocateLayoutEntry(this.#e.layout);return t.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${t.resolve(this.schema).value};`),g(r,this.schema)}get[S](){let t=this.schema;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.")}get value(){return this.$}toString(){return`${this.resourceType}:${c(this)??"<unnamed>"}`}},Kt=class{constructor(t,r,n){this.schema=t;this.#t=r,this.#n=n,this.resourceType=t.type==="sampler_comparison"?"sampler-comparison":"sampler",this[p]={unwrap:()=>(this.#r||(this.#r=this.#n.device.createSampler({...this.#t,label:c(this)??"<unnamed>"})),this.#r)},this.#e=r.minFilter==="linear"||r.magFilter==="linear"||r.mipmapFilter==="linear"}[p];resourceType;#e;#r=null;#t;#n;[h](t){let r=t.getUniqueName(this),{group:n,binding:a}=t.allocateFixedEntry(this.schema.type==="sampler_comparison"?{sampler:"comparison"}:{sampler:this.#e?"filtering":"non-filtering"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${t.resolve(this.schema).value};`),g(r,this.schema)}get[S](){let t=this.schema;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.")}get value(){return this.$}$name(t){return v(this,t),this}toString(){return`${this.resourceType}:${c(this)??"<unnamed>"}`}};var Yt=class{constructor(t,r){this.schema=t;this.#e=r,v(this,r.key)}resourceType="external-texture";[p]=!0;#e;[h](t){let r=t.getUniqueName(this),n=t.allocateLayoutEntry(this.#e.layout);return t.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${t.resolve(this.schema).value};`),g(r,Wn())}get[S](){let t=this.schema;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`textureExternal:${c(this)??"<unnamed>"}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}toString(){return`textureExternal:${c(this)??"<unnamed>"}`}};function Jt(e){let{videoWidth:t,videoHeight:r}=e;if(t&&r)return{width:t,height:r};let{naturalWidth:n,naturalHeight:a}=e;if(n&&a)return{width:n,height:a};let{codedWidth:o,codedHeight:s}=e;if(o&&s)return{width:o,height:s};let{width:i,height:u}=e||HTMLCanvasElement||OffscreenCanvas||HTMLImageElement||ImageData;if(!i||!u)throw new Error("Cannot determine dimensions of the provided image source.");return{width:i,height:u}}var $r=new WeakMap;function ca(e){let t=$r.get(e);return t||(t=new Map,$r.set(e,t)),t}function ga(e){let t=$r.get(e);t&&t.clear()}function ya(e,t,r=0,n){if(t.dimension!=="2d")throw new Error("Cannot generate mipmaps for non-2D textures: only 2D textures are currently supported.");let a=n??t.mipLevelCount-r,o=br(t.format,e);if(![...o.sampleTypes].some(i=>i==="float"||i==="unfilterable-float"))throw new Error(`Cannot generate mipmaps for format '${t.format}': only float and unfilterable-float formats are currently supported.`);if(!o.canRenderAttachment)throw new Error(`Cannot generate mipmaps for format '${t.format}': format does not support render attachments.`);for(let i=0;i<t.depthOrArrayLayers;i++)for(let u=r;u<r+a-1;u++){let l=u,m=u+1;go(e,t,l,m,i)}}function Ta(e,t,r,n){if(t.dimension==="3d")throw new Error("Cannot resample to 3D textures: only 2D textures are currently supported.");let a=Re[t.format];if(![...a.sampleTypes].some(s=>s==="float"||s==="unfilterable-float"))throw new Error(`Cannot resample to format '${t.format}': only float and unfilterable-float formats are currently supported.`);if(!a.canRenderAttachment)throw new Error(`Cannot resample to format '${t.format}': format does not support render attachments.`);return co(e,t,r,n)}function co(e,t,r,n=0){let o=[...Re[t.format].sampleTypes].includes("float"),s=`${o?"filterable":"unfilterable"}`,i=ca(e),u=i.get(s);if(!u){let F=e.createShaderModule({code:`
17
17
  struct VertexOutput {
18
18
  @builtin(position) pos: vec4f,
19
19
  @location(0) uv: vec2f,
@@ -29,7 +29,7 @@ fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
29
29
  output.uv = uv[vertexIndex];
30
30
  return output;
31
31
  }
32
- `}),_e=t.createSampler({magFilter:o?"linear":"nearest",minFilter:o?"linear":"nearest"}),We=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:o?"filtering":"non-filtering"}}]}),lr=t.createPipelineLayout({bindGroupLayouts:[We]}),Qa=t.createShaderModule({code:`
32
+ `}),R=e.createSampler({magFilter:o?"linear":"nearest",minFilter:o?"linear":"nearest"}),Me=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:o?"filtering":"non-filtering"}}]}),lr=e.createPipelineLayout({bindGroupLayouts:[Me]}),za=e.createShaderModule({code:`
33
33
  @group(0) @binding(0) var inputTexture: texture_2d<f32>;
34
34
  @group(0) @binding(1) var inputSampler: sampler;
35
35
 
@@ -38,7 +38,7 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
38
38
  ${o?"return textureSample(inputTexture, inputSampler, uv);":`let texelCoord = vec2u(uv * vec2f(textureDimensions(inputTexture)));
39
39
  return textureLoad(inputTexture, texelCoord, 0);`}
40
40
  }
41
- `});u={vertexShader:F,fragmentShader:Qa,bindGroupLayout:We,pipelineLayout:lr,sampler:_e},i.set(s,u)}let p=t.createTexture({size:[...Object.values(Jt(r))],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST}),{width:m,height:c}=Jt(r);t.queue.copyExternalImageToTexture({source:r},{texture:p},[m,c,1]);let y=t.createTexture({size:[e.width,e.height,1],format:e.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),h=t.createRenderPipeline({layout:u.pipelineLayout,vertex:{module:u.vertexShader},fragment:{module:u.fragmentShader,targets:[{format:e.format}]},primitive:{topology:"triangle-list"}}),v=t.createBindGroup({layout:u.bindGroupLayout,entries:[{binding:0,resource:p.createView()},{binding:1,resource:u.sampler}]}),x=t.createCommandEncoder(),P=x.beginRenderPass({colorAttachments:[{view:y.createView(),loadOp:"clear",storeOp:"store"}]});P.setPipeline(h),P.setBindGroup(0,v),P.draw(3),P.end(),x.copyTextureToTexture({texture:y},{texture:e,origin:{x:0,y:0,z:n}},{width:e.width,height:e.height,depthOrArrayLayers:1}),t.queue.submit([x.finish()]),p.destroy(),y.destroy()}function xo(t,e,r,n,a){let s=[...br(e.format,t).sampleTypes].includes("float"),i=`${s?"filterable":"unfilterable"}`,u=ha(t),p=u.get(i);if(!p){let P=t.createShaderModule({code:`
41
+ `});u={vertexShader:F,fragmentShader:za,bindGroupLayout:Me,pipelineLayout:lr,sampler:R},i.set(s,u)}let l=e.createTexture({size:[...Object.values(Jt(r))],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST}),{width:m,height:y}=Jt(r);e.queue.copyExternalImageToTexture({source:r},{texture:l},[m,y,1]);let f=e.createTexture({size:[t.width,t.height,1],format:t.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),T=e.createRenderPipeline({layout:u.pipelineLayout,vertex:{module:u.vertexShader},fragment:{module:u.fragmentShader,targets:[{format:t.format}]},primitive:{topology:"triangle-list"}}),w=e.createBindGroup({layout:u.bindGroupLayout,entries:[{binding:0,resource:l.createView()},{binding:1,resource:u.sampler}]}),x=e.createCommandEncoder(),P=x.beginRenderPass({colorAttachments:[{view:f.createView(),loadOp:"clear",storeOp:"store"}]});P.setPipeline(T),P.setBindGroup(0,w),P.draw(3),P.end(),x.copyTextureToTexture({texture:f},{texture:t,origin:{x:0,y:0,z:n}},{width:t.width,height:t.height,depthOrArrayLayers:1}),e.queue.submit([x.finish()]),l.destroy(),f.destroy()}function go(e,t,r,n,a){let s=[...br(t.format,e).sampleTypes].includes("float"),i=`${s?"filterable":"unfilterable"}`,u=ca(e),l=u.get(i);if(!l){let P=e.createShaderModule({code:`
42
42
  struct VertexOutput {
43
43
  @builtin(position) pos: vec4f,
44
44
  @location(0) uv: vec2f,
@@ -54,7 +54,7 @@ fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
54
54
  output.uv = uv[vertexIndex];
55
55
  return output;
56
56
  }
57
- `}),F=t.createShaderModule({code:`
57
+ `}),F=e.createShaderModule({code:`
58
58
  @group(0) @binding(0) var inputTexture: texture_2d<f32>;
59
59
  @group(0) @binding(1) var inputSampler: sampler;
60
60
 
@@ -62,24 +62,24 @@ fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
62
62
  fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
63
63
  return textureSample(inputTexture, inputSampler, uv);
64
64
  }
65
- `}),_e=t.createSampler({magFilter:s?"linear":"nearest",minFilter:s?"linear":"nearest"}),We=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:s?"float":"unfilterable-float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:s?"filtering":"non-filtering"}}]}),lr=t.createPipelineLayout({bindGroupLayouts:[We]});p={vertexShader:P,fragmentShader:F,bindGroupLayout:We,pipelineLayout:lr,sampler:_e},u.set(i,p)}let m=t.createRenderPipeline({layout:p.pipelineLayout,vertex:{module:p.vertexShader},fragment:{module:p.fragmentShader,targets:[{format:e.format}]},primitive:{topology:"triangle-list"}}),c=e.createView({baseMipLevel:r,dimension:"2d",mipLevelCount:1,...a!==void 0&&{baseArrayLayer:a,arrayLayerCount:1}}),y=e.createView({baseMipLevel:n,dimension:"2d",mipLevelCount:1,...a!==void 0&&{baseArrayLayer:a,arrayLayerCount:1}}),h=t.createBindGroup({layout:p.bindGroupLayout,entries:[{binding:0,resource:c},{binding:1,resource:p.sampler}]}),v=t.createCommandEncoder(),x=v.beginRenderPass({colorAttachments:[{view:y,loadOp:"clear",storeOp:"store"}]});x.setPipeline(m),x.setBindGroup(0,h),x.draw(3),x.end(),t.queue.submit([v.finish()])}function wo(t){return{dimension:t.dimension??"2d",sampleType:Ae[t.format].channelType,multisampled:(t.sampleCount??1)!==1}}function bo(t){return t==="depth24plus-stencil8"||t==="depth32float-stencil8"?["depth","stencil"]:t==="depth16unorm"||t==="depth24plus"||t==="depth32float"?["depth"]:t==="stencil8"?["stencil"]:["color"]}function Sa(t,e){return new Rr(t,e)}function ee(t){return t?.resourceType==="texture"&&!!t[l]}function nt(t){return t?.resourceType==="texture-view"&&!!t[l]}var Rr=class{constructor(e,r){this.props=e;let n=e.format;this.#o=r,this.#e=Ae[n],this.#r=e.size[0]*(e.size[1]??1)*(e.size[2]??1)*this.#e.texelSize,this.aspects=bo(n),this[l]={unwrap:()=>{if(this.#t)throw new Error("This texture has been destroyed");return this.#a||(this.#a=r.device.createTexture({label:f(this)??"<unnamed>",format:e.format,size:e.size,usage:this.#n,dimension:e.dimension??"2d",viewFormats:e.viewFormats??[],mipLevelCount:e.mipLevelCount??1,sampleCount:e.sampleCount??1})),this.#a}}}[l];resourceType="texture";aspects;usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;#e;#r;#t=!1;#n=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;#a=null;#o;$name(e){return S(this,e),this}$usage(...e){let r=e.includes("storage"),n=e.includes("sampled"),a=e.includes("render");return this.#n|=n?GPUTextureUsage.TEXTURE_BINDING:0,this.#n|=r?GPUTextureUsage.STORAGE_BINDING:0,this.#n|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||=r,this.usableAsSampled||=n,this.usableAsRender||=a,this}createView(e,r){return new Cr(e??je(wo(this.props)),this,r)}#s(e=0){let r=2**e,[n,a,o]=[Math.max(1,Math.floor((this.props.size[0]??1)/r)),Math.max(1,Math.floor((this.props.size[1]??1)/r)),Math.max(1,Math.floor((this.props.size[2]??1)/r))];this.#o.device.queue.writeTexture({texture:this[l].unwrap(),mipLevel:e},new Uint8Array(n*a*o*this.#e.texelSize),{bytesPerRow:this.#e.texelSize*n,rowsPerImage:a},[n,a,o])}clear(e="all"){if(e==="all"){let r=this.props.mipLevelCount??1;for(let n=0;n<r;n++)this.#s(n)}else this.#s(e)}generateMipmaps(e=0,r){if(this.usableAsRender===!1)throw new Error("generateMipmaps called without specifying 'render' usage. Add it via the $usage('render') method.");let n=r??(this.props.mipLevelCount??1)-e;if(n<=1){console.warn(`generateMipmaps is a no-op: would generate ${n} mip levels (base: ${e}, total: ${this.props.mipLevelCount??1})`);return}if(e>=(this.props.mipLevelCount??1))throw new Error(`Base mip level ${e} is out of range. Texture has ${this.props.mipLevelCount??1} mip levels.`);wa(this.#o.device,this[l].unwrap(),e,n)}write(e,r=0){if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){this.#u(e,r);return}let n=this.props.dimension??"2d";if(!Array.isArray(e)){this.#i(e,n==="3d"?0:void 0);return}let o=this.props.size[2]??1;e.length>o&&console.warn(`Too many image sources provided. Expected ${o} layers, got ${e.length}. Extra sources will be ignored.`);for(let s=0;s<Math.min(e.length,o);s++){let i=e[s];i&&this.#i(i,s)}}#u(e,r){let n=Math.max(1,this.props.size[0]>>r),a=Math.max(1,(this.props.size[1]??1)>>r),o=Math.max(1,(this.props.size[2]??1)>>r),s=n*a*o*this.#e.texelSize,i=e.byteLength??e.byteLength;if(i!==s)throw new Error(`Buffer size mismatch. Expected ${s} bytes for mip level ${r}, got ${i} bytes.`);this.#o.device.queue.writeTexture({texture:this[l].unwrap(),mipLevel:r},e,{bytesPerRow:this.#e.texelSize*n,rowsPerImage:a},[n,a,o])}#i(e,r){let n=this.props.size[0],a=this.props.size[1]??1,{width:o,height:s}=Jt(e);if(o!==n||s!==a){ba(this.#o.device,this[l].unwrap(),e,r);return}this.#o.device.queue.copyExternalImageToTexture({source:e},{texture:this[l].unwrap(),...r!==void 0&&{origin:{x:0,y:0,z:r}}},r!==void 0?[n,a,1]:this.props.size)}copyFrom(e){if(e.props.format!==this.props.format)throw new Error(`Texture format mismatch. Source texture has format ${e.props.format}, target texture has format ${this.props.format}`);if(e.props.size[0]!==this.props.size[0]||(e.props.size[1]??1)!==(this.props.size[1]??1)||(e.props.size[2]??1)!==(this.props.size[2]??1))throw new Error(`Texture size mismatch. Source texture has size ${e.props.size.join("x")}, target texture has size ${this.props.size.join("x")}`);let r=this.#o.device.createCommandEncoder();r.copyTextureToTexture({texture:e[l].unwrap()},{texture:this[l].unwrap()},e.props.size),this.#o.device.queue.submit([r.finish()])}get destroyed(){return this.#t}destroy(){this.#t||(this.#t=!0,this.#a?.destroy())}},Cr=class{constructor(e,r,n){this.schema=e;this.#e=r,this.#t=n,this[l]={unwrap:()=>{if(!this.#r){let a=this.schema,o;Qe(a)?o={label:f(this)??"<unnamed>",format:this.#t?.format??a.format,dimension:a.dimension}:o={label:f(this)??"<unnamed>",format:this.#t?.format??this.#e.props.format,dimension:a.dimension},this.#t?.mipLevelCount!==void 0&&(o.mipLevelCount=this.#t.mipLevelCount),this.#t?.arrayLayerCount!==void 0&&(o.arrayLayerCount=this.#t.arrayLayerCount),this.#r=this.#e[l].unwrap().createView(o)}return this.#r}}}[l];resourceType="texture-view";#e;#r;#t;$name(e){return S(this,e),this.#r&&(this.#r.label=e),this}get[w](){let e=this.schema;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to texture view values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}toString(){return`textureView:${f(this)??"<unnamed>"}`}[T](e){let r=e.getUniqueName(this),{group:n,binding:a}=e.allocateFixedEntry(Qe(this.schema)?{storageTexture:this.schema}:{texture:this.schema,sampleType:this.#t?.sampleType??this.schema.bindingSampleType[0]},this);return e.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${e.resolve(this.schema).value};`),g(r,this.schema)}},rt=class{constructor(e,r){this.schema=e;this.#e=r,S(this,r.key)}[l]={unwrap:void 0};resourceType="texture-view";#e;toString(){return`textureView:${f(this)??"<unnamed>"}`}[T](e){let r=e.getUniqueName(this),n=e.allocateLayoutEntry(this.#e.layout);return e.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${e.resolve(this.schema).value};`),g(r,this.schema)}get[w](){let e=this.schema;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},G)}get $(){if(E())return this[w];throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}};function Er(t){return!!t?.usableAsSampled}function So(t){return!!t?.usableAsRender}var Xt=class t extends Error{constructor(e){super(`Resource '${f(e)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,t.prototype)}};function vo(t){let e={};for(let[r,n]of Object.entries(t)){if(n===null){e[r]=null;continue}if("texture"in n&&typeof n.texture=="string"){let a=n.texture;e[r]={...n,texture:je({dimension:n.viewDimension??"2d",sampleType:a==="sint"?bt:a==="uint"?R:St,multisampled:n.multisampled??!1})}}else if("storageTexture"in n&&typeof n.storageTexture=="string"){let a={readonly:"read-only",writeonly:"write-only",mutable:"read-write"};e[r]={...n,storageTexture:je({access:a[n.access??"writeonly"],format:n.storageTexture,dimension:n.viewDimension??"2d"})}}else"externalTexture"in n&&Object.keys(n.externalTexture).length===0?e[r]={...n,externalTexture:{type:"texture_external",dimension:"2d"}}:e[r]=n}return e}function Zt(t){let e=vo(t);return new _r(e)}function er(t){return!!t&&t.resourceType==="bind-group-layout"}function Te(t){return!!t&&t.resourceType==="bind-group"}var Vr=class t extends Error{constructor(e,r){super(`Bind group '${e??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,t.prototype)}},va=["compute","fragment"],at=["compute","vertex","fragment"],_r=class{constructor(e){this.entries=e;let r=0;for(let[n,a]of Object.entries(e)){if(a===null){r++;continue}let o={layout:this,key:n,idx:r};if("uniform"in a&&(this.bound[n]=new Xe("uniform",a.uniform,o)),"storage"in a){let s="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Xe(a.access??"readonly",s,o)}"texture"in a&&(this.bound[n]=new rt(a.texture,o)),"storageTexture"in a&&(this.bound[n]=new rt(a.storageTexture,o)),"externalTexture"in a&&(this.bound[n]=new Yt(a.externalTexture,o)),"sampler"in a&&(this.bound[n]=new Ht(a.sampler==="comparison"?Lt():At(),o)),Object.defineProperty(this.value,n,{get:()=>this.bound[n].value}),r++}}[l]=!0;_index;resourceType="bind-group-layout";bound={};value={};$=this.value;get[w](){return this.$}toString(){return`bindGroupLayout:${f(this)??"<unnamed>"}`}get index(){return this._index}$name(e){return S(this,e),this}$idx(e){return this._index=e,this}unwrap(e){return e.device.createBindGroupLayout({label:f(this)??"<unnamed>",entries:Object.values(this.entries).map((n,a)=>{if(n===null)return null;let o=n.visibility,s={binding:a,visibility:0};if("uniform"in n)o=o??at,s.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?va:at),s.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??at,s.sampler={type:n.sampler};else if("texture"in n){o=o??at;let{multisampled:i,dimension:u,bindingSampleType:p}=n.texture;s.texture={sampleType:n.sampleType??p[0],viewDimension:u,multisampled:i}}else if("storageTexture"in n){o=o??va;let{dimension:i,access:u,format:p}=n.storageTexture;s.storageTexture={access:u,format:p,viewDimension:i}}else"externalTexture"in n&&(o=o??at,s.externalTexture={});return o?.includes("compute")&&(s.visibility|=GPUShaderStage.COMPUTE),o?.includes("vertex")&&(s.visibility|=GPUShaderStage.VERTEX),o?.includes("fragment")&&(s.visibility|=GPUShaderStage.FRAGMENT),s}).filter(n=>n!==null)})}},Ce=class{constructor(e,r){this.layout=e;this.entries=r;for(let n of Object.keys(e.entries))if(e.entries[n]!==null&&!(n in r))throw new Vr(f(e),n)}resourceType="bind-group";unwrap(e){return e.device.createBindGroup({label:f(this.layout)??"<unnamed>",layout:e.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([n,a],o)=>{if(a===null)return null;let s=this.entries[n];if(s===void 0)throw new Error(`'${n}' is a resource required to populate bind group layout '${f(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let i;if(pe(s)){if(!jt(s))throw new gr(s);i={buffer:e.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("storage"in a){let i;if(pe(s)){if(!ye(s))throw new Ye(s);i={buffer:e.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("texture"in a){let i;if(ee(s)){if(!Er(s))throw new Xt(s);i=e.unwrap(s.createView(a.texture))}else nt(s)?i=e.unwrap(s):i=s;return{binding:o,resource:i}}if("storageTexture"in a){let i;if(ee(s)){if(!ye(s))throw new Ye(s);i=e.unwrap(s.createView(a.storageTexture))}else nt(s)?i=e.unwrap(s):i=s;return{binding:o,resource:i}}if("sampler"in a)return tt(s)||et(s)?{binding:o,resource:e.unwrap(s)}:{binding:o,resource:s};if("externalTexture"in a)return{binding:o,resource:s};throw new Error(`Malformed bind group entry: ${ze(s)}`)}).filter(n=>n!==null)})}};function he(t){return new Wr(t)}var Wr=class{constructor(e=void 0){this.defaultValue=e}[l]=!0;resourceType="slot";$name(e){return S(this,e),this}areEqual(e,r){return Object.is(e,r)}toString(){return`slot:${f(this)??"<unnamed>"}`}get[w](){let e=z();if(!e)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return ge(e.unwrap(this))}get value(){return this[w]}get $(){return this.value}};function Ee(t,e){return new ot("private",t,e)}function kr(t){return new ot("workgroup",t)}function Io(t){return t instanceof ot}var ot=class{[l]={};#e;#r;#t;constructor(e,r,n){this.#e=e,this.#r=r,this.#t=n}[T](e){let r=e.getUniqueName(this),n=`var<${this.#e}> ${r}: ${e.resolve(this.#r).value}`;return this.#t?e.addDeclaration(`${n} = ${e.resolve(this.#t,this.#r).value};`):e.addDeclaration(`${n};`),g(r,this.#r)}$name(e){return S(this,e),this}toString(){return`var:${f(this)??"<unnamed>"}`}get[w](){let e=this.#r;return new Proxy({[l]:!0,get[B](){return g(this,e)},[T]:r=>r.resolve(this),toString:()=>`var:${f(this)??"<unnamed>"}.$`},G)}get $(){let e=ve(),r=Se();if(e.type==="normal")throw new yr(r?`Cannot access variable '${f(this)??"<unnamed>"}'. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:"TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");return e.type==="codegen"?this[w]:e.type==="simulate"?(e.vars[this.#e].has(this)||e.vars[this.#e].set(this,this.#t),e.vars[this.#e].get(this)):se(e,"tgpuVariable.ts#TgpuVarImpl/$")}set $(e){let r=ve(),n=Se();if(r.type==="normal")throw new yr(n?`Cannot access ${String(this)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:"TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");if(r.type==="codegen")throw new Error("Unreachable tgpuVariable.ts#TgpuVarImpl/$");if(r.type==="simulate"){r.vars[this.#e].set(this,e);return}se(r,"tgpuVariable.ts#TgpuVarImpl/$")}get value(){return this.$}set value(e){this.$=e}};var Ia=Ee(R,0).$name("dataBlockIndex"),Ua=Ee(R,0).$name("dataByteIndex"),Fa=he().$name("dataBuffer"),Uo=U([],R)`() {
65
+ `}),R=e.createSampler({magFilter:s?"linear":"nearest",minFilter:s?"linear":"nearest"}),Me=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:s?"float":"unfilterable-float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:s?"filtering":"non-filtering"}}]}),lr=e.createPipelineLayout({bindGroupLayouts:[Me]});l={vertexShader:P,fragmentShader:F,bindGroupLayout:Me,pipelineLayout:lr,sampler:R},u.set(i,l)}let m=e.createRenderPipeline({layout:l.pipelineLayout,vertex:{module:l.vertexShader},fragment:{module:l.fragmentShader,targets:[{format:t.format}]},primitive:{topology:"triangle-list"}}),y=t.createView({baseMipLevel:r,dimension:"2d",mipLevelCount:1,...a!==void 0&&{baseArrayLayer:a,arrayLayerCount:1}}),f=t.createView({baseMipLevel:n,dimension:"2d",mipLevelCount:1,...a!==void 0&&{baseArrayLayer:a,arrayLayerCount:1}}),T=e.createBindGroup({layout:l.bindGroupLayout,entries:[{binding:0,resource:y},{binding:1,resource:l.sampler}]}),w=e.createCommandEncoder(),x=w.beginRenderPass({colorAttachments:[{view:f,loadOp:"clear",storeOp:"store"}]});x.setPipeline(m),x.setBindGroup(0,T),x.draw(3),x.end(),e.queue.submit([w.finish()])}function yo(e){return{dimension:e.dimension??"2d",sampleType:Re[e.format].channelType,multisampled:(e.sampleCount??1)!==1}}function To(e){return e==="depth24plus-stencil8"||e==="depth32float-stencil8"?["depth","stencil"]:e==="depth16unorm"||e==="depth24plus"||e==="depth32float"?["depth"]:e==="stencil8"?["stencil"]:["color"]}function ha(e,t){return new Lr(e,t)}function ee(e){return e?.resourceType==="texture"&&!!e[p]}function he(e){return e?.resourceType==="texture-view"&&!!e[p]}var Lr=class{constructor(t,r){this.props=t;let n=t.format;this.#o=r,this.#e=Re[n],this.#r=t.size[0]*(t.size[1]??1)*(t.size[2]??1)*this.#e.texelSize,this.aspects=To(n),this[p]={unwrap:()=>{if(this.#t)throw new Error("This texture has been destroyed");return this.#a||(this.#a=r.device.createTexture({label:c(this)??"<unnamed>",format:t.format,size:t.size,usage:this.#n,dimension:t.dimension??"2d",viewFormats:t.viewFormats??[],mipLevelCount:t.mipLevelCount??1,sampleCount:t.sampleCount??1})),this.#a}}}[p];resourceType="texture";aspects;usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;#e;#r;#t=!1;#n=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;#a=null;#o;$name(t){return v(this,t),this}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this.#n|=n?GPUTextureUsage.TEXTURE_BINDING:0,this.#n|=r?GPUTextureUsage.STORAGE_BINDING:0,this.#n|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||=r,this.usableAsSampled||=n,this.usableAsRender||=a,this}createView(t,r){return new Rr(t??Qe(yo(this.props)),this,r)}#s(t=0){let r=2**t,[n,a,o]=[Math.max(1,Math.floor((this.props.size[0]??1)/r)),Math.max(1,Math.floor((this.props.size[1]??1)/r)),Math.max(1,Math.floor((this.props.size[2]??1)/r))];this.#o.device.queue.writeTexture({texture:this[p].unwrap(),mipLevel:t},new Uint8Array(n*a*o*this.#e.texelSize),{bytesPerRow:this.#e.texelSize*n,rowsPerImage:a},[n,a,o])}clear(t="all"){if(t==="all"){let r=this.props.mipLevelCount??1;for(let n=0;n<r;n++)this.#s(n)}else this.#s(t)}generateMipmaps(t=0,r){if(this.usableAsRender===!1)throw new Error("generateMipmaps called without specifying 'render' usage. Add it via the $usage('render') method.");let n=r??(this.props.mipLevelCount??1)-t;if(n<=1){console.warn(`generateMipmaps is a no-op: would generate ${n} mip levels (base: ${t}, total: ${this.props.mipLevelCount??1})`);return}if(t>=(this.props.mipLevelCount??1))throw new Error(`Base mip level ${t} is out of range. Texture has ${this.props.mipLevelCount??1} mip levels.`);ya(this.#o.device,this[p].unwrap(),t,n)}write(t,r=0){if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){this.#u(t,r);return}let n=this.props.dimension??"2d";if(!Array.isArray(t)){this.#i(t,n==="3d"?0:void 0);return}let o=this.props.size[2]??1;t.length>o&&console.warn(`Too many image sources provided. Expected ${o} layers, got ${t.length}. Extra sources will be ignored.`);for(let s=0;s<Math.min(t.length,o);s++){let i=t[s];i&&this.#i(i,s)}}#u(t,r){let n=Math.max(1,this.props.size[0]>>r),a=Math.max(1,(this.props.size[1]??1)>>r),o=Math.max(1,(this.props.size[2]??1)>>r),s=n*a*o*this.#e.texelSize,i=t.byteLength??t.byteLength;if(i!==s)throw new Error(`Buffer size mismatch. Expected ${s} bytes for mip level ${r}, got ${i} bytes.`);this.#o.device.queue.writeTexture({texture:this[p].unwrap(),mipLevel:r},t,{bytesPerRow:this.#e.texelSize*n,rowsPerImage:a},[n,a,o])}#i(t,r){let n=this.props.size[0],a=this.props.size[1]??1,{width:o,height:s}=Jt(t);if(o!==n||s!==a){Ta(this.#o.device,this[p].unwrap(),t,r);return}this.#o.device.queue.copyExternalImageToTexture({source:t},{texture:this[p].unwrap(),...r!==void 0&&{origin:{x:0,y:0,z:r}}},r!==void 0?[n,a,1]:this.props.size)}copyFrom(t){if(t.props.format!==this.props.format)throw new Error(`Texture format mismatch. Source texture has format ${t.props.format}, target texture has format ${this.props.format}`);if(t.props.size[0]!==this.props.size[0]||(t.props.size[1]??1)!==(this.props.size[1]??1)||(t.props.size[2]??1)!==(this.props.size[2]??1))throw new Error(`Texture size mismatch. Source texture has size ${t.props.size.join("x")}, target texture has size ${this.props.size.join("x")}`);let r=this.#o.device.createCommandEncoder();r.copyTextureToTexture({texture:t[p].unwrap()},{texture:this[p].unwrap()},t.props.size),this.#o.device.queue.submit([r.finish()])}get destroyed(){return this.#t}destroy(){this.#t||(this.#t=!0,this.#a?.destroy())}},Rr=class{constructor(t,r,n){this.schema=t;this.#e=r,this.#t=n,this[p]={unwrap:()=>{if(!this.#r){let a=this.schema,o;He(a)?o={label:c(this)??"<unnamed>",format:this.#t?.format??a.format,dimension:a.dimension}:o={label:c(this)??"<unnamed>",format:this.#t?.format??this.#e.props.format,dimension:a.dimension},this.#t?.mipLevelCount!==void 0&&(o.mipLevelCount=this.#t.mipLevelCount),this.#t?.arrayLayerCount!==void 0&&(o.arrayLayerCount=this.#t.arrayLayerCount),this.#r=this.#e[p].unwrap().createView(o)}return this.#r}}}[p];resourceType="texture-view";#e;#r;#t;$name(t){return v(this,t),this.#r&&(this.#r.label=t),this}get[S](){let t=this.schema;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to texture view values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}toString(){return`textureView:${c(this)??"<unnamed>"}`}[h](t){let r=t.getUniqueName(this),{group:n,binding:a}=t.allocateFixedEntry(He(this.schema)?{storageTexture:this.schema}:{texture:this.schema,sampleType:this.#t?.sampleType??this.schema.bindingSampleType[0]},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${t.resolve(this.schema).value};`),g(r,this.schema)}},nt=class{constructor(t,r){this.schema=t;this.#e=r,v(this,r.key)}[p]={unwrap:void 0};resourceType="texture-view";#e;toString(){return`textureView:${c(this)??"<unnamed>"}`}[h](t){let r=t.getUniqueName(this),n=t.allocateLayoutEntry(this.#e.layout);return t.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r}: ${t.resolve(this.schema).value};`),g(r,this.schema)}get[S](){let t=this.schema;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`${this.toString()}.$`},E)}get $(){if(W())return this[S];throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead")}get value(){return this.$}};function Gr(e){return!!e?.usableAsSampled}function ho(e){return!!e?.usableAsRender}var Xt=class e extends Error{constructor(t){super(`Resource '${c(t)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function xo(e){let t={};for(let[r,n]of Object.entries(e)){if(n===null){t[r]=null;continue}if("texture"in n&&typeof n.texture=="string"){let a=n.texture;t[r]={...n,texture:Qe({dimension:n.viewDimension??"2d",sampleType:a==="sint"?bt:a==="uint"?G:St,multisampled:n.multisampled??!1})}}else if("storageTexture"in n&&typeof n.storageTexture=="string"){let a={readonly:"read-only",writeonly:"write-only",mutable:"read-write"};t[r]={...n,storageTexture:Qe({access:a[n.access??"writeonly"],format:n.storageTexture,dimension:n.viewDimension??"2d"})}}else"externalTexture"in n&&Object.keys(n.externalTexture).length===0?t[r]={...n,externalTexture:{type:"texture_external",dimension:"2d"}}:t[r]=n}return t}function Zt(e){let t=xo(e);return new Er(t)}function er(e){return!!e&&e.resourceType==="bind-group-layout"}function xe(e){return!!e&&e.resourceType==="bind-group"}var Cr=class e extends Error{constructor(t,r){super(`Bind group '${t??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},xa=["compute","fragment"],at=["compute","vertex","fragment"],Er=class{constructor(t){this.entries=t;let r=0;for(let[n,a]of Object.entries(t)){if(a===null){r++;continue}let o={layout:this,key:n,idx:r};if("uniform"in a&&(this.bound[n]=new Ze("uniform",a.uniform,o)),"storage"in a){let s="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Ze(a.access??"readonly",s,o)}"texture"in a&&(this.bound[n]=new nt(a.texture,o)),"storageTexture"in a&&(this.bound[n]=new nt(a.storageTexture,o)),"externalTexture"in a&&(this.bound[n]=new Yt(a.externalTexture,o)),"sampler"in a&&(this.bound[n]=new Ht(a.sampler==="comparison"?Lt():$t(),o)),Object.defineProperty(this.value,n,{get:()=>this.bound[n].value}),r++}}[p]=!0;_index;resourceType="bind-group-layout";bound={};value={};$=this.value;get[S](){return this.$}toString(){return`bindGroupLayout:${c(this)??"<unnamed>"}`}get index(){return this._index}$name(t){return v(this,t),this}$idx(t){return this._index=t,this}unwrap(t){return t.device.createBindGroupLayout({label:c(this)??"<unnamed>",entries:Object.values(this.entries).map((n,a)=>{if(n===null)return null;let o=n.visibility,s={binding:a,visibility:0};if("uniform"in n)o=o??at,s.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?xa:at),s.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??at,s.sampler={type:n.sampler};else if("texture"in n){o=o??at;let{multisampled:i,dimension:u,bindingSampleType:l}=n.texture;s.texture={sampleType:n.sampleType??l[0],viewDimension:u,multisampled:i}}else if("storageTexture"in n){o=o??xa;let{dimension:i,access:u,format:l}=n.storageTexture;s.storageTexture={access:u,format:l,viewDimension:i}}else"externalTexture"in n&&(o=o??at,s.externalTexture={});return o?.includes("compute")&&(s.visibility|=GPUShaderStage.COMPUTE),o?.includes("vertex")&&(s.visibility|=GPUShaderStage.VERTEX),o?.includes("fragment")&&(s.visibility|=GPUShaderStage.FRAGMENT),s}).filter(n=>n!==null)})}},Ve=class{constructor(t,r){this.layout=t;this.entries=r;for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new Cr(c(t),n)}resourceType="bind-group";unwrap(t){return t.device.createBindGroup({label:c(this.layout)??"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([n,a],o)=>{if(a===null)return null;let s=this.entries[n];if(s===void 0)throw new Error(`'${n}' is a resource required to populate bind group layout '${c(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let i;if(le(s)){if(!jt(s))throw new gr(s);i={buffer:t.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("storage"in a){let i;if(le(s)){if(!Te(s))throw new Je(s);i={buffer:t.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("texture"in a){let i;if(ee(s)){if(!Gr(s))throw new Xt(s);i=t.unwrap(s.createView(a.texture))}else he(s)?i=t.unwrap(s):i=s;return{binding:o,resource:i}}if("storageTexture"in a){let i;if(ee(s)){if(!Te(s))throw new Je(s);i=t.unwrap(s.createView(a.storageTexture))}else he(s)?i=t.unwrap(s):i=s;return{binding:o,resource:i}}if("sampler"in a)return rt(s)||tt(s)?{binding:o,resource:t.unwrap(s)}:{binding:o,resource:s};if("externalTexture"in a)return{binding:o,resource:s};throw new Error(`Malformed bind group entry: ${Ne(s)}`)}).filter(n=>n!==null)})}};function we(e){return new Vr(e)}var Vr=class{constructor(t=void 0){this.defaultValue=t}[p]=!0;resourceType="slot";$name(t){return v(this,t),this}areEqual(t,r){return Object.is(t,r)}toString(){return`slot:${c(this)??"<unnamed>"}`}get[S](){let t=N();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return ge(t.unwrap(this))}get value(){return this[S]}get $(){return this.value}};function _e(e,t){return new ot("private",e,t)}function _r(e){return new ot("workgroup",e)}function wo(e){return e instanceof ot}var ot=class{[p]={};#e;#r;#t;constructor(t,r,n){this.#e=t,this.#r=r,this.#t=n}[h](t){let r=t.getUniqueName(this),n=`var<${this.#e}> ${r}: ${t.resolve(this.#r).value}`;return this.#t?t.addDeclaration(`${n} = ${t.resolve(this.#t,this.#r).value};`):t.addDeclaration(`${n};`),g(r,this.#r)}$name(t){return v(this,t),this}toString(){return`var:${c(this)??"<unnamed>"}`}get[S](){let t=this.#r;return new Proxy({[p]:!0,get[L](){return g(this,t)},[h]:r=>r.resolve(this),toString:()=>`var:${c(this)??"<unnamed>"}.$`},E)}get $(){let t=Ue(),r=Ie();if(t.type==="normal")throw new yr(r?`Cannot access variable '${c(this)??"<unnamed>"}'. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:"TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");return t.type==="codegen"?this[S]:t.type==="simulate"?(t.vars[this.#e].has(this)||t.vars[this.#e].set(this,this.#t),t.vars[this.#e].get(this)):ie(t,"tgpuVariable.ts#TgpuVarImpl/$")}set $(t){let r=Ue(),n=Ie();if(r.type==="normal")throw new yr(n?`Cannot access ${String(this)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation`:"TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");if(r.type==="codegen")throw new Error("Unreachable tgpuVariable.ts#TgpuVarImpl/$");if(r.type==="simulate"){r.vars[this.#e].set(this,t);return}ie(r,"tgpuVariable.ts#TgpuVarImpl/$")}get value(){return this.$}set value(t){this.$=t}};var wa=_e(G,0).$name("dataBlockIndex"),ba=_e(G,0).$name("dataByteIndex"),Sa=we().$name("dataBuffer"),bo=U([],G)`() {
66
66
  let i = dataByteIndex;
67
67
  dataByteIndex = dataByteIndex + 1u;
68
68
  return i;
69
- }`.$uses({dataByteIndex:Ua}).$name("nextByteIndex"),d="dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]",Pa={f32:U([St])`(n) => {
69
+ }`.$uses({dataByteIndex:ba}).$name("nextByteIndex"),d="dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]",va={f32:U([St])`(n) => {
70
70
  ${d} = bitcast<u32>(n);
71
- }`,f16:U([$n])`(n) => {
71
+ }`,f16:U([Pn])`(n) => {
72
72
  ${d} = pack2x16float(vec2f(f32(n), 0.0));
73
73
  }`,i32:U([bt])`(n) => {
74
74
  ${d} = bitcast<u32>(n);
75
- }`,u32:U([R])`(n) => {
75
+ }`,u32:U([G])`(n) => {
76
76
  ${d} = n;
77
77
  }`,bool:U([wt])`(b) => {
78
78
  ${d} = u32(b);
79
- }`,vec2f:U([W])`(v) => {
79
+ }`,vec2f:U([M])`(v) => {
80
80
  ${d} = bitcast<u32>(v.x);
81
81
  ${d} = bitcast<u32>(v.y);
82
- }`,vec3f:U([N])`(v) => {
82
+ }`,vec3f:U([q])`(v) => {
83
83
  ${d} = bitcast<u32>(v.x);
84
84
  ${d} = bitcast<u32>(v.y);
85
85
  ${d} = bitcast<u32>(v.z);
@@ -88,18 +88,18 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
88
88
  ${d} = bitcast<u32>(v.y);
89
89
  ${d} = bitcast<u32>(v.z);
90
90
  ${d} = bitcast<u32>(v.w);
91
- }`,vec2h:U([Ie])`(v) => {
91
+ }`,vec2h:U([Fe])`(v) => {
92
92
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
93
- }`,vec3h:U([Ue])`(v) => {
93
+ }`,vec3h:U([Pe])`(v) => {
94
94
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
95
95
  ${d} = pack2x16float(vec2f(f32(v.z), 0.0));
96
- }`,vec4h:U([Fe])`(v) => {
96
+ }`,vec4h:U([De])`(v) => {
97
97
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
98
98
  ${d} = pack2x16float(vec2f(f32(v.z), f32(v.w)));
99
99
  }`,vec2i:U([Y])`(v) => {
100
100
  ${d} = bitcast<u32>(v.x);
101
101
  ${d} = bitcast<u32>(v.y);
102
- }`,vec3i:U([de])`(v) => {
102
+ }`,vec3i:U([ce])`(v) => {
103
103
  ${d} = bitcast<u32>(v.x);
104
104
  ${d} = bitcast<u32>(v.y);
105
105
  ${d} = bitcast<u32>(v.z);
@@ -132,12 +132,12 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
132
132
  ${d} = u32(v.y);
133
133
  ${d} = u32(v.z);
134
134
  ${d} = u32(v.w);
135
- }`,mat2x2f:U([Pe])`(m) => {
135
+ }`,mat2x2f:U([Be])`(m) => {
136
136
  ${d} = bitcast<u32>(m[0][0]);
137
137
  ${d} = bitcast<u32>(m[0][1]);
138
138
  ${d} = bitcast<u32>(m[1][0]);
139
139
  ${d} = bitcast<u32>(m[1][1]);
140
- }`,mat3x3f:U([De])`(m) => {
140
+ }`,mat3x3f:U([Ae])`(m) => {
141
141
  ${d} = bitcast<u32>(m[0][0]);
142
142
  ${d} = bitcast<u32>(m[0][1]);
143
143
  ${d} = bitcast<u32>(m[0][2]);
@@ -150,7 +150,7 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
150
150
  ${d} = bitcast<u32>(m[2][1]);
151
151
  ${d} = bitcast<u32>(m[2][2]);
152
152
  ${d} = 0u;
153
- }`,mat4x4f:U([Be])`(m) => {
153
+ }`,mat4x4f:U([$e])`(m) => {
154
154
  ${d} = bitcast<u32>(m[0][0]);
155
155
  ${d} = bitcast<u32>(m[0][1]);
156
156
  ${d} = bitcast<u32>(m[0][2]);
@@ -167,26 +167,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
167
167
  ${d} = bitcast<u32>(m[3][1]);
168
168
  ${d} = bitcast<u32>(m[3][2]);
169
169
  ${d} = bitcast<u32>(m[3][3]);
170
- }`};for(let[t,e]of Object.entries(Pa))e.$name(`serialize${t[0].toLocaleUpperCase()}${t.slice(1)}`).$uses({dataBlockIndex:Ia,nextByteIndex:Uo,dataBuffer:Fa});function Da(t){return`(${t.map((e,r)=>`_arg_${r}`).join(", ")})`}function Ba(t,e){let r=Pa[t.type];if(r)return r.with(Fa,e);if(_(t)){let n=Object.keys(t.propTypes),a=Object.values(t.propTypes),o=$a(a,e);return U([t])`(arg) {\n propsSerializer(${n.map(s=>`arg.${s}`).join(", ")});\n}`.$uses({propsSerializer:o}).$name(`${f(t)??"struct"}Serializer`)}if(O(t)){let n=t.elementType,a=t.elementCount,o=Ba(n,e);return U([t])`(arg) {\n${Array.from({length:a},(s,i)=>` elementSerializer(arg[${i}]);`).join(`
171
- `)}\n}`.$uses({elementSerializer:o}).$name("arraySerializer")}throw new Error(`Cannot serialize data of type ${t.type}`)}function $a(t,e){let r={},n=U(t),a=Da(t),o=t.map((s,i)=>(r[`serializer${i}`]=Ba(s,e),` serializer${i}(_arg_${i});`)).join(`
172
- `);return n`${a} {\n${o}\n}`.$uses(r).$name("compoundSerializer")}function Aa(t,e,r,n,a){let o=e.map(I).reduce((u,p)=>u+p,0);if(o>a.logSizeLimit)throw new Error(`Logged data needs to fit in ${a.logSizeLimit} bytes (one of the logs requires ${o} bytes). Consider increasing the limit by passing appropriate options to tgpu.init().`);let s=$a(e,r).$name(`log${t}serializer`),i=Da(e);return U(e)`${i} {
170
+ }`};for(let[e,t]of Object.entries(va))t.$name(`serialize${e[0].toLocaleUpperCase()}${e.slice(1)}`).$uses({dataBlockIndex:wa,nextByteIndex:bo,dataBuffer:Sa});function Ia(e){return`(${e.map((t,r)=>`_arg_${r}`).join(", ")})`}function Ua(e,t){let r=va[e.type];if(r)return r.with(Sa,t);if(_(e)){let n=Object.keys(e.propTypes),a=Object.values(e.propTypes),o=Fa(a,t);return U([e])`(arg) {\n propsSerializer(${n.map(s=>`arg.${s}`).join(", ")});\n}`.$uses({propsSerializer:o}).$name(`${c(e)??"struct"}Serializer`)}if(z(e)){let n=e.elementType,a=e.elementCount,o=Ua(n,t);return U([e])`(arg) {\n${Array.from({length:a},(s,i)=>` elementSerializer(arg[${i}]);`).join(`
171
+ `)}\n}`.$uses({elementSerializer:o}).$name("arraySerializer")}throw new Error(`Cannot serialize data of type ${e.type}`)}function Fa(e,t){let r={},n=U(e),a=Ia(e),o=e.map((s,i)=>(r[`serializer${i}`]=Ua(s,t),` serializer${i}(_arg_${i});`)).join(`
172
+ `);return n`${a} {\n${o}\n}`.$uses(r).$name("compoundSerializer")}function Pa(e,t,r,n,a){let o=t.map(I).reduce((u,l)=>u+l,0);if(o>a.logSizeLimit)throw new Error(`Logged data needs to fit in ${a.logSizeLimit} bytes (one of the logs requires ${o} bytes). Consider increasing the limit by passing appropriate options to tgpu.init().`);let s=Fa(t,r).$name(`log${e}serializer`),i=Ia(t);return U(t)`${i} {
173
173
  dataBlockIndex = atomicAdd(&indexBuffer, 1);
174
174
  if (dataBlockIndex >= ${a.logCountLimit}) {
175
175
  return;
176
176
  }
177
- dataBuffer[dataBlockIndex].id = ${t};
177
+ dataBuffer[dataBlockIndex].id = ${e};
178
178
  dataByteIndex = 0;
179
179
 
180
180
  compoundSerializer${i};
181
- }`.$uses({indexBuffer:n,dataBuffer:r,dataBlockIndex:Ia,dataByteIndex:Ua,compoundSerializer:s}).$name(`log${t}`)}var La=["log","debug","info","warn","error","clear"];var Fo={logCountLimit:64,logSizeLimit:252,messagePrefix:" GPU "},Ga=g("/* console.log() */",A),tr=class{get logResources(){}generateLog(){return console.warn("'console.log' is currently only supported in compute pipelines."),Ga}},rr=class{#e;#r;#t=1;#n;#a;constructor(e){this.#e={...Fo,...e[l].logOptions},this.#r=new Map;let r=Vn({id:R,serializedData:Sr(R,Math.ceil(this.#e.logSizeLimit/4))}).$name("SerializedLogData");this.#a=e.createMutable(Sr(r,this.#e.logCountLimit)).$name("dataBuffer"),this.#n=e.createMutable(Nn(R)).$name("indexBuffer")}generateLog(e,r,n){if(!La.includes(r))return console.warn(`Unsupported log method '${r}' was used in TGSL.`),Ga;let a=Ln(n),o=this.#t++,s=a.filter(p=>p.dataType!==ke),i=Aa(o,s.map(p=>p.dataType),this.#a,this.#n,this.#e),u=a.map(p=>p.dataType===ke?p.value:p.dataType);return this.#r.set(o,{op:r,argTypes:u}),g(oe`${e.resolve(i).value}(${s})`,A)}get logResources(){return this.#t===1?void 0:{dataBuffer:this.#a,indexBuffer:this.#n,options:this.#e,logIdToMeta:this.#r}}};var Ra="#CATCHALL#",Or=class{_stack=[];_itemDepth=0;get itemDepth(){return this._itemDepth}get topItem(){let e=this._stack[this._stack.length-1];if(!e||e.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return e}get topFunctionScope(){return this._stack.findLast(e=>e.type==="functionScope")}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}popItem(){this.pop("item")}pushSlotBindings(e){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(e)})}popSlotBindings(){this.pop("slotBinding")}pushFunctionScope(e,r,n,a){let o={type:"functionScope",args:e,argAliases:r,returnType:n,externalMap:a,reportedReturnTypes:new Set};return this._stack.push(o),o}popFunctionScope(){this.pop("functionScope")}pushBlockScope(){this._stack.push({type:"blockScope",declarations:new Map})}popBlockScope(){this.pop("blockScope")}pop(e){let r=this._stack[this._stack.length-1];if(!r||e&&r.type!==e)throw new Error(`Internal error, expected a ${e} layer to be on top.`);this._stack.pop(),e==="item"&&this._itemDepth--}readSlot(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="item")n.usedSlots.add(e);else if(n?.type==="slotBinding"){let a=n.bindingMap.get(e);if(a!==void 0)return a}else if(!(n?.type==="functionScope"||n?.type==="blockScope"))throw new Error("Unknown layer type.")}return e.defaultValue}getSnippetById(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="functionScope"){let a=n.args.find(s=>s.value===e);if(a!==void 0)return a;if(n.argAliases[e])return n.argAliases[e];let o=n.externalMap[e];return o!=null?Gn(o):void 0}if(n?.type==="blockScope"){let a=n.declarations.get(e);if(a!==void 0)return a}}}defineBlockVariable(e,r){if(r.dataType.type==="unknown")throw Error(`Tried to define variable '${e}' of unknown type`);for(let n=this._stack.length-1;n>=0;--n){let a=this._stack[n];if(a?.type==="blockScope"){a.declarations.set(e,r);return}}throw new Error("No block scope found to define a variable in.")}},nr=[""," "," "," "," "," "," "," "," "],Mr=nr.length-1,zr=class{identLevel=0;get pre(){return nr[this.identLevel]??nr[Mr].repeat(this.identLevel/Mr)+nr[this.identLevel%Mr]}indent(){let e=this.pre;return this.identLevel++,e}dedent(){return this.identLevel--,this.pre}withResetLevel(e){let r=this.identLevel;this.identLevel=0;try{return e()}finally{this.identLevel=r}}},st=class{#e;#r;_indentController=new zr;_itemStateStack=new Or;#t=[];_declarations=[];_varyingLocations;#n=new WeakSet;#a;get varyingLocations(){return this._varyingLocations}[l]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];enableExtensions;expectedType;constructor(e){this.enableExtensions=e.enableExtensions,this.#r=e.shaderGenerator??Gt,this.#a=e.root?new rr(e.root):new tr,this.#e=e.namespace[l]}getUniqueName(e){return na(this.#e,e)}makeNameValid(e){return this.#e.nameRegistry.makeValid(e)}get pre(){return this._indentController.pre}get topFunctionReturnType(){let e=this._itemStateStack.topFunctionScope;return K(e,"Internal error, expected function scope to be present."),e.returnType}get shelllessRepo(){return this.#e.shelllessRepo}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}withResetIndentLevel(e){return this._indentController.withResetLevel(e)}getById(e){let r=this._itemStateStack.getSnippetById(e);return r===void 0?null:r}defineVariable(e,r){this._itemStateStack.defineBlockVariable(e,r)}reportReturnType(e){let r=this._itemStateStack.topFunctionScope;K(r,"Internal error, expected function scope to be present."),r.reportedReturnTypes.add(e)}pushBlockScope(){this._itemStateStack.pushBlockScope()}popBlockScope(){this._itemStateStack.popBlockScope()}generateLog(e,r){return this.#a.generateLog(this,e,r)}get logResources(){return this.#a.logResources}fnToWgsl(e){let r=this._itemStateStack.pushFunctionScope(e.args,e.argAliases,e.returnType,e.externalMap);try{this.#r.initGenerator(this);let n=this.#r.functionDefinition(e.body),a=e.returnType;if(!a){let o=[...r.reportedReturnTypes];if(o.length===0)a=A;else{let s=Bn(o);s&&!s.hasImplicitConversions&&(a=s.targetType)}if(!a)throw new Error(`Expected function to have a single return type, got [${o.join(", ")}]. Cast explicitly to the desired type.`);a=Ft(a)}return{head:Po(this,e.args,a),body:n,returnType:a}}finally{this._itemStateStack.popFunctionScope()}}addDeclaration(e){this._declarations.push(e)}allocateLayoutEntry(e){let r=this.bindGroupLayoutsToPlaceholderMap,n=r.get(e);return n||(n=`#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`,r.set(e,n)),n}allocateFixedEntry(e,r){let n=this.fixedBindings.length;return this.fixedBindings.push({layoutEntry:e,resource:r}),{group:Ra,binding:n}}readSlot(e){let r=this._itemStateStack.readSlot(e);if(r===void 0)throw new cr(e);return r}withSlots(e,r){this._itemStateStack.pushSlotBindings(e);try{return r()}finally{this._itemStateStack.popSlotBindings()}}withVaryingLocations(e,r){this._varyingLocations=e;try{return r()}finally{this._varyingLocations=void 0}}unwrap(e){if(hr(e))return this.withSlots(e[H].pairs,()=>this.unwrap(e[H].inner));let r=e;for(;;)if(Tt(r))r=this.readSlot(r);else if(ht(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(e){let r=this.#e.memoizedDerived.get(e)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([i,u])=>i.areEqual(this._itemStateStack.readSlot(i),u)))return o.result;this.pushMode(new Sn);let n;try{n=e["~compute"]()}finally{this.popMode("normal")}let a=new Map;for(let o of this._itemStateStack.topItem.usedSlots)a.set(o,this._itemStateStack.readSlot(o));return r.push({slotToValueMap:a,result:n}),this.#e.memoizedDerived.set(e,r),n}catch(n){throw n instanceof be?n.appendToTrace(e):new be(n,[e])}finally{this._itemStateStack.popItem()}}_getOrInstantiate(e){let r=this.#e.memoizedResolves.get(e)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([i,u])=>i.areEqual(this._itemStateStack.readSlot(i),u)))return o.result;let n;if(ae(e))n=g(Br(this,e),A);else if(ht(e)||Tt(e))n=this.resolve(this.unwrap(e));else if(Un(e))n=e[T](this);else if(dt(e)){let o=this.#e.shelllessRepo.get(e,void 0);if(!o)throw new Error(`Couldn't resolve ${e.name}. Make sure it's a function that accepts no arguments, or call it from another TypeGPU function.`);return this.withResetIndentLevel(()=>this.resolve(o))}else throw new TypeError(`Unresolvable internal value: ${ze(e)}`);let a=new Map;for(let o of this._itemStateStack.topItem.usedSlots)a.set(o,this._itemStateStack.readSlot(o));return r.push({slotToValueMap:a,result:n}),this.#e.memoizedResolves.set(e,r),n}catch(n){throw n instanceof be?n.appendToTrace(e):new be(n,[e])}finally{this._itemStateStack.popItem()}}resolve(e,r,n=!1){if(He(e)||dt(e)){if(this.#n.has(e)&&!this.#e.memoizedResolves.has(e))throw new Error(`Recursive function ${e} detected. Recursion is not allowed on the GPU.`);this.#n.add(e)}if(hr(e))return this.withSlots(e[H].pairs,()=>this.resolve(e[H].inner,r,n));if(mt(e)||dt(e)){if(this._itemStateStack.itemDepth===0)try{this.pushMode(new vn);let a=xt(this,()=>this._getOrInstantiate(e));return g(`${[...this._declarations].join(`
181
+ }`.$uses({indexBuffer:n,dataBuffer:r,dataBlockIndex:wa,dataByteIndex:ba,compoundSerializer:s}).$name(`log${e}`)}var Da=["log","debug","info","warn","error","clear"];var So={logCountLimit:64,logSizeLimit:252,messagePrefix:" GPU "},Ba=g("/* console.log() */",A),tr=class{get logResources(){}generateLog(){return console.warn("'console.log' is currently only supported in compute pipelines."),Ba}},rr=class{#e;#r;#t=1;#n;#a;constructor(t){this.#e={...So,...t[p].logOptions},this.#r=new Map;let r=Gn({id:G,serializedData:Sr(G,Math.ceil(this.#e.logSizeLimit/4))}).$name("SerializedLogData");this.#a=t.createMutable(Sr(r,this.#e.logCountLimit)).$name("dataBuffer"),this.#n=t.createMutable(kn(G)).$name("indexBuffer")}generateLog(t,r,n){if(!Da.includes(r))return console.warn(`Unsupported log method '${r}' was used in TGSL.`),Ba;let a=Bn(n),o=this.#t++,s=a.filter(l=>l.dataType!==ke),i=Pa(o,s.map(l=>l.dataType),this.#a,this.#n,this.#e),u=a.map(l=>l.dataType===ke?l.value:l.dataType);return this.#r.set(o,{op:r,argTypes:u}),g(se`${t.resolve(i).value}(${s})`,A)}get logResources(){return this.#t===1?void 0:{dataBuffer:this.#a,indexBuffer:this.#n,options:this.#e,logIdToMeta:this.#r}}};var Aa="#CATCHALL#",Mr=class{_stack=[];_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}get topFunctionScope(){return this._stack.findLast(t=>t.type==="functionScope")}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}popItem(){this.pop("item")}pushSlotBindings(t){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(t)})}popSlotBindings(){this.pop("slotBinding")}pushFunctionScope(t,r,n,a){let o={type:"functionScope",args:t,argAliases:r,returnType:n,externalMap:a,reportedReturnTypes:new Set};return this._stack.push(o),o}popFunctionScope(){this.pop("functionScope")}pushBlockScope(){this._stack.push({type:"blockScope",declarations:new Map})}popBlockScope(){this.pop("blockScope")}pop(t){let r=this._stack[this._stack.length-1];if(!r||t&&r.type!==t)throw new Error(`Internal error, expected a ${t} layer to be on top.`);this._stack.pop(),t==="item"&&this._itemDepth--}readSlot(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="item")n.usedSlots.add(t);else if(n?.type==="slotBinding"){let a=n.bindingMap.get(t);if(a!==void 0)return a}else if(!(n?.type==="functionScope"||n?.type==="blockScope"))throw new Error("Unknown layer type.")}return t.defaultValue}getSnippetById(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="functionScope"){let a=n.args.find(s=>s.value===t);if(a!==void 0)return a;if(n.argAliases[t])return n.argAliases[t];let o=n.externalMap[t];return o!=null?An(o):void 0}if(n?.type==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return a}}}defineBlockVariable(t,r){if(r.dataType.type==="unknown")throw Error(`Tried to define variable '${t}' of unknown type`);for(let n=this._stack.length-1;n>=0;--n){let a=this._stack[n];if(a?.type==="blockScope"){a.declarations.set(t,r);return}}throw new Error("No block scope found to define a variable in.")}},nr=[""," "," "," "," "," "," "," "," "],Wr=nr.length-1,kr=class{identLevel=0;get pre(){return nr[this.identLevel]??nr[Wr].repeat(this.identLevel/Wr)+nr[this.identLevel%Wr]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}withResetLevel(t){let r=this.identLevel;this.identLevel=0;try{return t()}finally{this.identLevel=r}}},st=class{#e;#r;_indentController=new kr;_itemStateStack=new Mr;#t=[];_declarations=[];_varyingLocations;#n=new WeakSet;#a;get varyingLocations(){return this._varyingLocations}[p]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];enableExtensions;expectedType;constructor(t){this.enableExtensions=t.enableExtensions,this.#r=t.shaderGenerator??Rt,this.#a=t.root?new rr(t.root):new tr,this.#e=t.namespace[p]}getUniqueName(t){return Zn(this.#e,t)}makeNameValid(t){return this.#e.nameRegistry.makeValid(t)}get pre(){return this._indentController.pre}get topFunctionReturnType(){let t=this._itemStateStack.topFunctionScope;return oe(t,"Internal error, expected function scope to be present."),t.returnType}get shelllessRepo(){return this.#e.shelllessRepo}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}withResetIndentLevel(t){return this._indentController.withResetLevel(t)}getById(t){let r=this._itemStateStack.getSnippetById(t);return r===void 0?null:r}defineVariable(t,r){this._itemStateStack.defineBlockVariable(t,r)}reportReturnType(t){let r=this._itemStateStack.topFunctionScope;oe(r,"Internal error, expected function scope to be present."),r.reportedReturnTypes.add(t)}pushBlockScope(){this._itemStateStack.pushBlockScope()}popBlockScope(){this._itemStateStack.popBlockScope()}generateLog(t,r){return this.#a.generateLog(this,t,r)}get logResources(){return this.#a.logResources}fnToWgsl(t){let r=this._itemStateStack.pushFunctionScope(t.args,t.argAliases,t.returnType,t.externalMap);try{this.#r.initGenerator(this);let n=this.#r.functionDefinition(t.body),a=t.returnType;if(!a){let o=[...r.reportedReturnTypes];if(o.length===0)a=A;else{let s=Fn(o);s&&!s.hasImplicitConversions&&(a=s.targetType)}if(!a)throw new Error(`Expected function to have a single return type, got [${o.join(", ")}]. Cast explicitly to the desired type.`);a=Ft(a)}return{head:vo(this,t.args,a),body:n,returnType:a}}finally{this._itemStateStack.popFunctionScope()}}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:Aa,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new cr(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.popSlotBindings()}}withVaryingLocations(t,r){this._varyingLocations=t;try{return r()}finally{this._varyingLocations=void 0}}unwrap(t){if(hr(t))return this.withSlots(t[K].pairs,()=>this.unwrap(t[K].inner));let r=t;for(;;)if(Tt(r))r=this.readSlot(r);else if(ht(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(t){let r=this.#e.memoizedDerived.get(t)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([i,u])=>i.areEqual(this._itemStateStack.readSlot(i),u)))return o.result;this.pushMode(new wn);let n;try{n=t["~compute"]()}finally{this.popMode("normal")}let a=new Map;for(let o of this._itemStateStack.topItem.usedSlots)a.set(o,this._itemStateStack.readSlot(o));return r.push({slotToValueMap:a,result:n}),this.#e.memoizedDerived.set(t,r),n}catch(n){throw n instanceof ve?n.appendToTrace(t):new ve(n,[t])}finally{this._itemStateStack.popItem()}}_getOrInstantiate(t){let r=this.#e.memoizedResolves.get(t)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([i,u])=>i.areEqual(this._itemStateStack.readSlot(i),u)))return o.result;let n;if(ae(t))n=g(Pr(this,t),A);else if(ht(t)||Tt(t))n=this.resolve(this.unwrap(t));else if(vn(t))n=t[h](this);else if(dt(t)){let o=this.#e.shelllessRepo.get(t,void 0);if(!o)throw new Error(`Couldn't resolve ${t.name}. Make sure it's a function that accepts no arguments, or call it from another TypeGPU function.`);return this.withResetIndentLevel(()=>this.resolve(o))}else throw new TypeError(`Unresolvable internal value: ${Ne(t)}`);let a=new Map;for(let o of this._itemStateStack.topItem.usedSlots)a.set(o,this._itemStateStack.readSlot(o));return r.push({slotToValueMap:a,result:n}),this.#e.memoizedResolves.set(t,r),n}catch(n){throw n instanceof ve?n.appendToTrace(t):new ve(n,[t])}finally{this._itemStateStack.popItem()}}resolve(t,r){if(Ke(t)||dt(t)){if(this.#n.has(t)&&!this.#e.memoizedResolves.has(t))throw new Error(`Recursive function ${t} detected. Recursion is not allowed on the GPU.`);this.#n.add(t)}if(hr(t))return this.withSlots(t[K].pairs,()=>this.resolve(t[K].inner,r));if(mt(t)||dt(t)){if(this._itemStateStack.itemDepth===0)try{this.pushMode(new bn);let n=xt(this,()=>this._getOrInstantiate(t));return g(`${[...this._declarations].join(`
182
182
 
183
- `)}${a.value}`,A)}finally{this.popMode("codegen")}return this._getOrInstantiate(e)}if(typeof e=="number"){let a=n?r:wr(e).dataType,o=r??wr(e).dataType;if(K(a,"Schema has to be defined for resolving numbers"),K(o.type!=="unknown","Schema has to be known for resolving numbers"),a.type==="abstractInt")return g(`${e}`,o);if(a.type==="u32")return g(`${e}u`,o);if(a.type==="i32")return g(`${e}i`,o);let s=e.toExponential(),i=a.type==="abstractFloat"&&Number.isInteger(e)?`${e}.`:`${e}`,u=s.length<i.length?s:i;return a.type==="f32"?g(`${u}f`,o):a.type==="f16"?g(`${u}h`,o):g(u,o)}if(typeof e=="boolean")return g(e?"true":"false",wt);if(typeof e=="string")return g(e,A);if(r&&O(r)){if(!Array.isArray(e))throw new yt(`Cannot coerce ${e} into value of type '${r}'`);if(r.elementCount!==e.length)throw new yt(`Cannot create value of type '${r}' from an array of length: ${e.length}`);let a=this.resolve(r.elementType);return g(oe`array<${a}, ${r.elementCount}>(${e.map(o=>g(o,r.elementType))})`,r)}if(Array.isArray(e))return g(oe`array(${e.map(a=>this.resolve(a))})`,ke);if(r&&_(r))return g(oe`${this.resolve(r)}(${Object.entries(r.propTypes).map(([a,o])=>g(e[a],o))})`,r);throw new yt(`Value ${e} (as json: ${ze(e)}) is not resolvable${r?` to type ${r.type}`:""}`)}pushMode(e){this.#t.push(e)}popMode(e){let r=this.#t.pop();e!==void 0&&K(r?.type===e,"Unexpected mode")}get mode(){return this.#t[this.#t.length-1]??Dn}};function le(t,e){let r=new st(e),a=(e.config?r.withSlots(e.config(new Le([])).bindings,()=>r.resolve(t)):r.resolve(t)).value,o=r.bindGroupLayoutsToPlaceholderMap,s=[],i=new Set([...o.keys()].map(y=>y.index).filter(y=>y!==void 0)),u=oa(i),p=r.fixedBindings.map((y,h)=>[String(h),y.layoutEntry]),m=()=>{let y=u.next().value,h=Zt(Object.fromEntries(p));return s[y]=h,a=a.replaceAll(Ra,String(y)),[y,new Ce(h,Object.fromEntries(r.fixedBindings.map((v,x)=>[String(x),v.resource])))]},c=p.length>0?m():void 0;for(let[y,h]of o.entries()){let v=y.index??u.next().value;s[v]=y,a=a.replaceAll(h,String(v))}return e.enableExtensions&&e.enableExtensions.length>0&&(a=`${e.enableExtensions.map(h=>`enable ${h};`).join(`
183
+ `)}${n.value}`,A)}finally{this.popMode("codegen")}return this._getOrInstantiate(t)}if(typeof t=="number"){let n=r??Dn(t).dataType;if(oe(n.type!=="unknown","Schema has to be known for resolving numbers"),n.type==="abstractInt")return g(`${t}`,n);if(n.type==="u32")return g(`${t}u`,n);if(n.type==="i32")return g(`${t}i`,n);let a=t.toExponential(),o=n.type==="abstractFloat"&&Number.isInteger(t)?`${t}.`:`${t}`,s=a.length<o.length?a:o;return n.type==="f32"?g(`${s}f`,n):n.type==="f16"?g(`${s}h`,n):g(s,n)}if(typeof t=="boolean")return g(t?"true":"false",wt);if(typeof t=="string")return g(t,A);if(r&&z(r)){if(!Array.isArray(t))throw new yt(`Cannot coerce ${t} into value of type '${r}'`);if(r.elementCount!==t.length)throw new yt(`Cannot create value of type '${r}' from an array of length: ${t.length}`);let n=this.resolve(r.elementType);return g(se`array<${n}, ${r.elementCount}>(${t.map(a=>g(a,r.elementType))})`,r)}if(Array.isArray(t))return g(se`array(${t.map(n=>this.resolve(n))})`,ke);if(r&&_(r))return g(se`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>g(t[n],a))})`,r);throw new yt(`Value ${t} (as json: ${Ne(t)}) is not resolvable${r?` to type ${r.type}`:""}`)}pushMode(t){this.#t.push(t)}popMode(t){let r=this.#t.pop();t!==void 0&&oe(r?.type===t,"Unexpected mode")}get mode(){return this.#t[this.#t.length-1]??Un}};function me(e,t){let r=new st(t),a=(t.config?r.withSlots(t.config(new Ge([])).bindings,()=>r.resolve(e)):r.resolve(e)).value,o=r.bindGroupLayoutsToPlaceholderMap,s=[],i=new Set([...o.keys()].map(f=>f.index).filter(f=>f!==void 0)),u=ta(i),l=r.fixedBindings.map((f,T)=>[String(T),f.layoutEntry]),m=()=>{let f=u.next().value,T=Zt(Object.fromEntries(l));return s[f]=T,a=a.replaceAll(Aa,String(f)),[f,new Ve(T,Object.fromEntries(r.fixedBindings.map((w,x)=>[String(x),w.resource])))]},y=l.length>0?m():void 0;for(let[f,T]of o.entries()){let w=f.index??u.next().value;s[w]=f,a=a.replaceAll(T,String(w))}return t.enableExtensions&&t.enableExtensions.length>0&&(a=`${t.enableExtensions.map(T=>`enable ${T};`).join(`
184
184
  `)}
185
185
 
186
- ${a}`),{code:a,usedBindGroupLayouts:s,catchall:c,logResources:r.logResources}}function Po(t,e,r){let n=e.map(a=>`${a.value}: ${t.resolve(a.dataType).value}`).join(", ");return r.type!=="void"?`(${n}) -> ${$t(r)}${t.resolve(r).value} `:`(${n}) `}function Nr(t){let e=t;return e?.resourceType==="compute-pipeline"&&!!e[l]}function qr(t){let e=t;return e?.resourceType==="render-pipeline"&&!!e[l]}function Ca(t){return qr(t)||Nr(t)}function jr(t){let{externals:e,shaderGenerator:r,template:n,names:a="random",config:o,enableExtensions:s}=t,i={};Pt(i,e??{});let u={[l]:!0,[T](m){return g(Bt(m,i,n??""),A)},toString:()=>"<root>"},p=Object.values(e).filter(Ca);if(p.length>1)throw new Error(`Found ${p.length} pipelines but can only resolve one at a time.`);return le(u,{namespace:typeof a=="string"?j({names:a}):a,enableExtensions:s,shaderGenerator:r,config:o,root:p[0]?.[l].branch})}function Ea(t){return jr(t).code}function Va(t){let e=z()??new st({namespace:j(),shaderGenerator:Gt}),r=[1,1,1],n=[1,1,1],a=[r[0]*n[0],r[1]*n[1],r[2]*n[2]],o=new Map,s=Array.from({length:r[0]},()=>Array.from({length:r[1]},()=>Array.from({length:r[2]},()=>new Map))),i=Array.from({length:a[0]},()=>Array.from({length:a[1]},()=>Array.from({length:a[2]},()=>new Map))),u=Array.from({length:a[0]},(p,m)=>Array.from({length:a[1]},(c,y)=>Array.from({length:a[2]},(h,v)=>{let x=Math.floor(m/n[0]),P=Math.floor(y/n[1]),F=Math.floor(v/n[2]);return new In(o,{private:i[m][y][v],workgroup:s[x][P][F]})})));e.pushMode(u[0][0][0]);try{return{value:xt(e,t),buffers:o,privateVars:i,workgroupVars:s}}finally{e.popMode("simulate")}}function _a(t,e,r,n){return new Qr(t,e,r,n)}function it(t){let e=t;return e?.resourceType==="query-set"&&!!e[l]}var Qr=class{constructor(e,r,n,a){this._group=e;this.type=r;this.count=n;this.rawQuerySet=a;this._ownQuerySet=!a,this._querySet=a||null}resourceType="query-set";_querySet=null;_ownQuerySet;_destroyed=!1;_available=!0;_readBuffer=null;_resolveBuffer=null;get querySet(){if(this._destroyed)throw new Error("This QuerySet has been destroyed.");return this.rawQuerySet?this.rawQuerySet:this._querySet?this._querySet:(this._querySet=this._group.device.createQuerySet({type:this.type,count:this.count}),this._querySet)}get destroyed(){return this._destroyed}get available(){return this._available}get[l](){let e=this;return{get readBuffer(){return e._readBuffer||(e._readBuffer=e._group.device.createBuffer({size:e.count*BigUint64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),e._readBuffer},get resolveBuffer(){return e._resolveBuffer||(e._resolveBuffer=e._group.device.createBuffer({size:e.count*BigUint64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC})),e._resolveBuffer}}}$name(e){return S(this,e),this._querySet&&(this._querySet.label=e),this}resolve(){if(this._destroyed)throw new Error("This QuerySet has been destroyed.");if(!this._available)throw new Error("This QuerySet is busy resolving or reading.");let e=this._group.device.createCommandEncoder();e.resolveQuerySet(this.querySet,0,this.count,this[l].resolveBuffer,0),this._group.device.queue.submit([e.finish()])}async read(){if(this._group.flush(),!this._resolveBuffer)throw new Error("QuerySet must be resolved before reading.");this._available=!1;try{let e=this._group.device.createCommandEncoder();e.copyBufferToBuffer(this[l].resolveBuffer,0,this[l].readBuffer,0,this.count*BigUint64Array.BYTES_PER_ELEMENT),this._group.device.queue.submit([e.finish()]),await this._group.device.queue.onSubmittedWorkDone();let r=this[l].readBuffer;await r.mapAsync(GPUMapMode.READ);let n=new BigUint64Array(r.getMappedRange().slice());return r.unmap(),Array.from(n)}finally{this._available=!0}}destroy(){this._destroyed||(this._destroyed=!0,this._querySet&&this._ownQuerySet&&this._querySet.destroy(),this._readBuffer?.destroy(),this._resolveBuffer?.destroy(),this._readBuffer=this._resolveBuffer=null)}};var ut=class{constructor(e){this._make=e}_map=new WeakMap;getOrMake(e,...r){if(this._map.has(e))return this._map.get(e);let n=this._make(e,...r);return this._map.set(e,n),n}};function Do(t){return t instanceof xe}var xe=class{constructor(e,r){this.resourceType=e;this.buffer=r;this[D]=r,this.#e=this.buffer.as(this.resourceType)}[l]=!0;[D];#e;$name(e){return S(this[D],e),this}write(e){this.buffer.write(e)}writePartial(e){this.buffer.writePartial(e)}read(){return this.buffer.read()}get[w](){return this.#e.$}get $(){return this.#e.$}get value(){return this.$}[T](e){return e.resolve(this.#e)}};var b=t=>Qn(t??0),Q=t=>Hn(t??0),Ve=t=>Kn(t??0),Bo={f32:t=>b(t[0]),f16:t=>Ve(t[0]).x,i32:t=>Q(t[0]),u32:t=>t[0]??0,bool:t=>!!t[0],vec2f:t=>W(b(t[0]),b(t[1])),vec3f:t=>N(b(t[0]),b(t[1]),b(t[2])),vec4f:t=>V(b(t[0]),b(t[1]),b(t[2]),b(t[3])),vec2h(t){let e=Ve(t[0]);return Ie(e.x,e.y)},vec3h(t){let e=Ve(t[0]),r=Ve(t[1]);return Ue(e.x,e.y,r.x)},vec4h(t){let e=Ve(t[0]),r=Ve(t[1]);return Fe(e.x,e.y,r.x,r.y)},vec2i:t=>Y(Q(t[0]),Q(t[1])),vec3i:t=>de(Q(t[0]),Q(t[1]),Q(t[2])),vec4i:t=>X(Q(t[0]),Q(t[1]),Q(t[2]),Q(t[3])),vec2u:t=>J(t[0]??0,t[1]??0),vec3u:t=>C(t[0]??0,t[1]??0,t[2]??0),vec4u:t=>Z(t[0]??0,t[1]??0,t[2]??0,t[3]??0),"vec2<bool>":t=>vt(!!t[0],!!t[1]),"vec3<bool>":t=>It(!!t[0],!!t[1],!!t[2]),"vec4<bool>":t=>Ut(!!t[0],!!t[1],!!t[2],!!t[3]),mat2x2f:t=>Pe(b(t[0]),b(t[1]),b(t[2]),b(t[3])),mat3x3f:t=>De(b(t[0]),b(t[1]),b(t[2]),b(t[4]),b(t[5]),b(t[6]),b(t[8]),b(t[9]),b(t[10])),mat4x4f:t=>Be(b(t[0]),b(t[1]),b(t[2]),b(t[3]),b(t[4]),b(t[5]),b(t[6]),b(t[7]),b(t[8]),b(t[9]),b(t[10]),b(t[11]),b(t[12]),b(t[13]),b(t[14]),b(t[15]))};function $o(t,e){let r=Bo[e.type];if(r)return r(t);if(_(e)){let n=Object.keys(e.propTypes),a=Object.values(e.propTypes),o=Hr(t,a);return Object.fromEntries(n.map((s,i)=>[s,o[i]]))}if(O(e)){let n=e.elementType,a=e.elementCount;return Hr(t,Array.from({length:a},()=>n))}throw new Error(`Cannot deserialize data of type ${e.type}`)}function Hr(t,e){let r=0;return e.map(n=>{if(!we(n))return n;let a=Math.ceil(I(n)/4),o=$o(t.subarray(r,r+a),n);return r+=a,o})}function Ao(t,e){return Hr(t,e).map(Cn)}function pt(t){let{indexBuffer:e,dataBuffer:r,logIdToMeta:n,options:a}=t;r.read().then(o=>{o.filter(s=>s.id).forEach(({id:s,serializedData:i})=>{let{argTypes:u,op:p}=n.get(s),m=Ao(new Uint32Array(i),u);m.length===0&&m.push(""),console[p](`%c${a.messagePrefix}%c ${m[0]}`,"background: #936ff5; color: white;","color: inherit; background: none",...m.slice(1))})}),e.read().then(o=>{o>a.logCountLimit&&console.warn(`Log count limit per dispatch (${a.logCountLimit}) exceeded by ${o-a.logCountLimit} calls. Consider increasing the limit by passing appropriate options to tgpu.init().`)}),r.buffer.clear(),e.buffer.clear()}function ar(t,e,r){if(!r.enabledFeatures.has("timestamp-query"))throw new Error('Performance callback requires the "timestamp-query" feature to be enabled on GPU device.');return t.timestampWrites?{...t,performanceCallback:e}:{...t,performanceCallback:e,hasAutoQuerySet:!0,timestampWrites:{querySet:r.createQuerySet("timestamp",2),beginningOfPassWriteIndex:0,endOfPassWriteIndex:1}}}function or(t,e,r){if(!r.enabledFeatures.has("timestamp-query"))throw new Error('Timestamp writes require the "timestamp-query" feature to be enabled on GPU device.');t.hasAutoQuerySet&&t.timestampWrites&&t.timestampWrites.querySet.destroy();let n={querySet:e.querySet};return e.beginningOfPassWriteIndex!==void 0&&(n.beginningOfPassWriteIndex=e.beginningOfPassWriteIndex),e.endOfPassWriteIndex!==void 0&&(n.endOfPassWriteIndex=e.endOfPassWriteIndex),{...t,hasAutoQuerySet:!1,timestampWrites:n}}function sr(t,e){if(!t.timestampWrites)return{};let{querySet:r,beginningOfPassWriteIndex:n,endOfPassWriteIndex:a}=t.timestampWrites,o={querySet:it(r)?e.unwrap(r):r};return n!==void 0&&(o.beginningOfPassWriteIndex=n),a!==void 0&&(o.endOfPassWriteIndex=a),{timestampWrites:o}}function lt({root:t,priors:e}){let r=e.timestampWrites?.querySet,n=e.performanceCallback;if(!r)throw new Error("Cannot dispatch workgroups with performance callback without a query set.");if(!it(r))throw new Error("Performance callback with raw GPUQuerySet is not supported. Use TgpuQuerySet instead.");t.commandEncoder.resolveQuerySet(t.unwrap(r),0,r.count,r[l].resolveBuffer,0),t.flush(),t.device.queue.onSubmittedWorkDone().then(async()=>{if(!r.available)return;let a=await r.read(),o=a[e.timestampWrites?.beginningOfPassWriteIndex??0],s=a[e.timestampWrites?.endOfPassWriteIndex??1];if(o===void 0||s===void 0)throw new Error("QuerySet did not return valid timestamps.");await n(o,s)})}function Wa(t,e,r){return new Kr(new Yr(t,e,r),{})}var Kr=class t{constructor(e,r){this._core=e;this._priors=r;this[l]={get rawPipeline(){return e.unwrap().pipeline},get priors(){return r},get branch(){return e.branch}},this[D]=e}[l];resourceType="compute-pipeline";[D];[T](e){return e.resolve(this._core)}toString(){return`computePipeline:${f(this)??"<unnamed>"}`}get rawPipeline(){return this._core.unwrap().pipeline}with(e,r){return Te(e)?new t(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[e.layout,e]])}):new t(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[e,r]])})}withPerformanceCallback(e){let r=ar(this._priors,e,this._core.branch);return new t(this._core,r)}withTimestampWrites(e){let r=or(this._priors,e,this._core.branch);return new t(this._core,r)}dispatchWorkgroups(e,r,n){let a=this._core.unwrap(),{branch:o}=this._core,s={label:f(this._core)??"<unnamed>",...sr(this._priors,o)},i=o.commandEncoder.beginComputePass(s);i.setPipeline(a.pipeline);let u=new Set(a.usedBindGroupLayouts);if(a.usedBindGroupLayouts.forEach((p,m)=>{if(a.catchall&&m===a.catchall[0])i.setBindGroup(m,o.unwrap(a.catchall[1])),u.delete(p);else{let c=this._priors.bindGroupLayoutMap?.get(p);c!==void 0&&(u.delete(p),i.setBindGroup(m,o.unwrap(c)))}}),u.size>0)throw new me(u);i.dispatchWorkgroups(e,r,n),i.end(),a.logResources&&pt(a.logResources),this._priors.performanceCallback&&lt({root:o,priors:this._priors})}$name(e){return S(this._core,e),this}},Yr=class{constructor(e,r,n){this.branch=e;this._slotBindings=r;this._entryFn=n}[l]=!0;_memo;[T](e){return e.withSlots(this._slotBindings,()=>(e.resolve(this._entryFn),g("",A)))}toString(){return"computePipelineCore"}unwrap(){if(this._memo===void 0){let e=this.branch.device,r=Rt.filter(c=>this.branch.enabledFeatures.has(Ct[c])),n,a,o=j({names:this.branch.nameRegistrySetting});if(te?.enabled){let c=performance.mark("typegpu:resolution:start");n=le(this,{namespace:o,enableExtensions:r,shaderGenerator:this.branch.shaderGenerator,root:this.branch}),a=performance.measure("typegpu:resolution",{start:c.name})}else n=le(this,{namespace:o,enableExtensions:r,shaderGenerator:this.branch.shaderGenerator,root:this.branch});let{code:s,usedBindGroupLayouts:i,catchall:u,logResources:p}=n;u!==void 0&&i[u[0]]?.$name(`${f(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let m=e.createShaderModule({label:`${f(this)??"<unnamed>"} - Shader`,code:s});this._memo={pipeline:e.createComputePipeline({label:f(this)??"<unnamed>",layout:e.createPipelineLayout({label:`${f(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:i.map(c=>this.branch.unwrap(c))}),compute:{module:m}}),usedBindGroupLayouts:i,catchall:u,logResources:p},te?.enabled&&(async()=>{let c=performance.mark("typegpu:compile-start");await e.queue.onSubmittedWorkDone();let y=performance.measure("typegpu:compiled",{start:c.name});te?.record("resolution",{resolveDuration:a?.duration,compileDuration:y.duration,wgslSize:s.length})})()}return this._memo}};function Zr(t,e="vertex"){return new Xr(t,e)}function ur(t){return t?.resourceType==="vertex-layout"}var Jr=Symbol("defaultAttribEntry");function ir(t,e,r,n,a){if(ct(e)||bn(e)){let o=ne(e);return o!==void 0&&(n[a??Jr]=o),ir(t,e.inner,k(r,q(e)),n)}if(_(e)){let o=r,s=e.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=k(o,L(u));let p=[i,ir(t,u,o,n,i)];return o+=I(u),p}))}if(re(e)){let o=r,s=e.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=k(o,q(u));let p=[i,ir(t,u,o,n,i)];return o+=I(u),p}))}if("type"in e&&typeof e.type=="string"){if(mn.includes(e.type))return{_layout:t,format:e.type,offset:r};let o=fn[e.type];if(o)return{_layout:t,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(e)}`)}var Xr=class{constructor(e,r){this.schemaForCount=e;this.stepMode=r;let n=e(0);this.stride=k(I(n.elementType),L(n)),this.attrib=ir(this,n.elementType,0,this._customLocationMap)}[l]=!0;resourceType="vertex-layout";stride;attrib;_customLocationMap={};get vertexLayout(){if(this._customLocationMap[Jr]!==void 0){if(typeof this.attrib.format!="string"||typeof this.attrib.offset!="number")throw new Error("Single attribute vertex layouts must have a format and offset.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[{format:this.attrib.format,offset:this.attrib.offset,shaderLocation:this._customLocationMap[Jr]}]}}if(!Object.keys(this.attrib).every(r=>this._customLocationMap[r]!==void 0))throw new Error("All attributes must have custom locations in order to unwrap a vertex layout.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[...Object.entries(this.attrib).map(([r,n])=>({format:n.format,offset:n.offset,shaderLocation:this._customLocationMap[r]}))]}}$name(e){return S(this,e),this}};function Lo(t){return typeof t?.loadOp=="string"}function ka(t,e){if(ae(t)){if(!Lo(e))throw new Error("Expected a single color attachment, not a record.");return[e]}let r=[];for(let n of Object.keys(t)){let a=t[n];if(ie(a))continue;let o=e[n];if(!o)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(o)}return r}function Go(t){return typeof t?.format=="string"}function Ma(t,e){if(ae(t)){if(xn(t))return[];if(!Go(e))throw new Error("Expected a single color target configuration, not a record.");return[e]}let r=[];for(let n of Object.keys(t)){let a=t[n];if(ie(a))continue;let o=e[n];if(!o)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(o)}return r}function rn(t){return new en(new tn(t),{})}var en=class t{[l];resourceType="render-pipeline";[D];hasIndexBuffer=!1;constructor(e,r){this[l]={core:e,priors:r,branch:e.options.branch},this[D]=e}[T](e){return e.resolve(this[l].core)}toString(){return`renderPipeline:${f(this)??"<unnamed>"}`}$name(e){return S(this[l].core,e),this}with(e,r){let n=this[l];if(Te(e))return new t(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[e.layout,e]])});if(er(e))return new t(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[e,r]])});if(ur(e))return new t(n.core,{...n.priors,vertexLayoutMap:new Map([...n.priors.vertexLayoutMap??[],[e,r]])});throw new Error("Unsupported value passed into .with()")}withPerformanceCallback(e){let r=this[l],n=ar(r.priors,e,r.core.options.branch);return new t(r.core,n)}withTimestampWrites(e){let r=this[l],n=or(r.priors,e,r.core.options.branch);return new t(r.core,n)}withColorAttachment(e){let r=this[l];return new t(r.core,{...r.priors,colorAttachment:e})}withDepthStencilAttachment(e){let r=this[l];return new t(r.core,{...r.priors,depthStencilAttachment:e})}withIndexBuffer(e,r,n,a){let o=this[l];if(Oe(e)){if(typeof r!="string")throw new Error("If a GPUBuffer is passed, indexFormat must be provided.");return new t(o.core,{...o.priors,indexBuffer:{buffer:e,indexFormat:r,offsetBytes:n,sizeBytes:a}})}let s={u32:"uint32",u16:"uint16"},i=e.dataType.elementType;return new t(o.core,{...o.priors,indexBuffer:{buffer:e,indexFormat:s[i.type],offsetBytes:r!==void 0?r*I(i):void 0,sizeBytes:a!==void 0?a*I(i):void 0}})}setupRenderPass(){let e=this[l],r=e.core.unwrap(),{branch:n,fragmentFn:a}=e.core.options,o=a?ka(a.shell.out,e.priors.colorAttachment??{}).map(c=>ee(c.view)?{...c,view:n.unwrap(c.view).createView()}:c):[null],s={label:f(e.core)??"<unnamed>",colorAttachments:o,...sr(e.priors,n)};if(e.priors.depthStencilAttachment!==void 0){let c=e.priors.depthStencilAttachment;ee(c.view)?s.depthStencilAttachment={...c,view:n.unwrap(c.view).createView()}:s.depthStencilAttachment=c}let i=n.commandEncoder.beginRenderPass(s);i.setPipeline(r.pipeline);let u=new Set(r.usedBindGroupLayouts);r.usedBindGroupLayouts.forEach((c,y)=>{if(r.catchall&&y===r.catchall[0])i.setBindGroup(y,n.unwrap(r.catchall[1])),u.delete(c);else{let h=e.priors.bindGroupLayoutMap?.get(c);h!==void 0&&(u.delete(c),i.setBindGroup(y,n.unwrap(h)))}});let p=new Set(e.core.usedVertexLayouts);if(e.core.usedVertexLayouts.forEach((c,y)=>{let h=e.priors.vertexLayoutMap?.get(c);h&&(p.delete(c),i.setVertexBuffer(y,n.unwrap(h)))}),u.size>0)throw new me(u);if(p.size>0)throw new Me(p);return i}draw(e,r,n,a){let o=this[l],s=this.setupRenderPass(),{logResources:i}=o.core.unwrap(),{branch:u}=o.core.options;s.draw(e,r,n,a),s.end(),i&&pt(i),o.priors.performanceCallback?lt({root:u,priors:o.priors}):u.flush()}drawIndexed(e,r,n,a,o){let s=this[l];if(!s.priors.indexBuffer)throw new Error("No index buffer set for this render pipeline.");let{buffer:i,indexFormat:u,offsetBytes:p,sizeBytes:m}=s.priors.indexBuffer,c=this.setupRenderPass(),{logResources:y}=s.core.unwrap(),{branch:h}=s.core.options;Oe(i)?c.setIndexBuffer(i,u,p,m):c.setIndexBuffer(h.unwrap(i),u,p,m),c.drawIndexed(e,r,n,a,o),c.end(),y&&pt(y),s.priors.performanceCallback?lt({root:h,priors:s.priors}):h.flush()}},tn=class{constructor(e){this.options=e;let r=aa(e.vertexFn.shell.in??{},e.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=e.fragmentFn&&e.targets?Ma(e.fragmentFn.shell.out,e.targets):[null]}[l]=!0;usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;[T](e){let{vertexFn:r,fragmentFn:n,slotBindings:a}=this.options,o=Ro(r.shell.out,n?.shell.in,f(r)??"<unnamed>",f(n)??"<unnamed>");return e.withVaryingLocations(o,()=>e.withSlots(a,()=>(e.resolve(r),n&&e.resolve(n),g("",A))))}toString(){return"renderPipelineCore"}unwrap(){if(this._memo===void 0){let{branch:e,primitiveState:r,depthStencilState:n,multisampleState:a}=this.options,o=e.device,s=Rt.filter(F=>e.enabledFeatures.has(Ct[F])),i,u,p=j({names:e.nameRegistrySetting});if(te?.enabled){let F=performance.mark("typegpu:resolution:start");i=le(this,{namespace:p,enableExtensions:s,shaderGenerator:e.shaderGenerator,root:e}),u=performance.measure("typegpu:resolution",{start:F.name})}else i=le(this,{namespace:p,enableExtensions:s,shaderGenerator:e.shaderGenerator,root:e});let{code:m,usedBindGroupLayouts:c,catchall:y,logResources:h}=i;y!==void 0&&c[y[0]]?.$name(`${f(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let v=o.createShaderModule({label:`${f(this)??"<unnamed>"} - Shader`,code:m}),x={layout:o.createPipelineLayout({label:`${f(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:c.map(F=>e.unwrap(F))}),vertex:{module:v,buffers:this._vertexBufferLayouts}},P=f(this);P!==void 0&&(x.label=P),this.options.fragmentFn&&(x.fragment={module:v,targets:this._targets}),r&&(we(r.stripIndexFormat)?x.primitive={...r,stripIndexFormat:{u32:"uint32",u16:"uint16"}[r.stripIndexFormat.type]}:x.primitive=r),n&&(x.depthStencil=n),a&&(x.multisample=a),this._memo={pipeline:o.createRenderPipeline(x),usedBindGroupLayouts:c,catchall:y,logResources:h},te?.enabled&&(async()=>{let F=performance.mark("typegpu:compile-start");await o.queue.onSubmittedWorkDone();let _e=performance.measure("typegpu:compiled",{start:F.name});te?.record("resolution",{resolveDuration:u?.duration,compileDuration:_e.duration,wgslSize:m.length})})()}return this._memo}};function Ro(t,e,r,n){let a={},o=new Set;function s(u,p){a[u]=p,o.add(p)}for(let[u,p]of Object.entries(t)){let m=ne(p);m!==void 0&&s(u,m)}for(let[u,p]of Object.entries(e??{})){let m=ne(p);m!==void 0&&(a[u]===void 0?s(u,m):a[u]!==m&&console.warn(`Mismatched location between vertexFn (${r}) output (${a[u]}) and fragmentFn (${n}) input (${m}) for the key "${u}", using the location set on vertex output.`))}let i=0;for(let u of Object.keys(t??{}))if(!(ie(t[u])||a[u]!==void 0)){for(;o.has(i);)i++;s(u,i)}return a}function Co(t){if(t.includes(0))throw new Error("Size and workgroupSize cannot contain zeroes.");return C(t[0]??1,t[1]??1,t[2]??1)}var Eo=[C(1,1,1),C(256,1,1),C(16,16,1),C(8,8,4)],nn=class t{#e;#r;#t;#n;#a;constructor(e,r,n,a){this.#e=e,this.#r=r,this.#t=n,this.#n=a,this.#a=C()}with(e){return new t(this.#e,this.#r.with(e),this.#t,this.#n)}dispatchThreads(...e){let r=Co(e),n=qn(N(r).div(N(this.#n)));Yn(r,this.#a)||(this.#a=r,this.#t.write(r)),this.#r.dispatchWorkgroups(n.x,n.y,n.z),this.#e.flush()}},an=class t{constructor(e,r){this._getRoot=e;this._slotBindings=r}with(e,r){return new t(this._getRoot,[...this._slotBindings,[fe(e)?e.slot:e,r]])}withCompute(e){return new on(this._getRoot(),this._slotBindings,e)}createGuardedComputePipeline(e){let r=this._getRoot();if(e.length>=4)throw new Error("Guarded compute callback only supports up to three dimensions.");let n=Eo[e.length],a=U([R,R,R])(e),o=r.createUniform(C),s=Et({workgroupSize:n,in:{id:jn.globalInvocationId}})`{
186
+ ${a}`),{code:a,usedBindGroupLayouts:s,catchall:y,logResources:r.logResources}}function vo(e,t,r){let n=t.map(a=>`${a.value}: ${e.resolve(a.dataType).value}`).join(", ");return r.type!=="void"?`(${n}) -> ${At(r)}${e.resolve(r).value} `:`(${n}) `}function Or(e){let t=e;return t?.resourceType==="compute-pipeline"&&!!t[p]}function zr(e){let t=e;return t?.resourceType==="render-pipeline"&&!!t[p]}function $a(e){return zr(e)||Or(e)}function Nr(e){let{externals:t,shaderGenerator:r,template:n,names:a="random",config:o,enableExtensions:s}=e,i={};Pt(i,t??{});let u={[p]:!0,[h](m){return g(Bt(m,i,n??""),A)},toString:()=>"<root>"},l=Object.values(t).filter($a);if(l.length>1)throw new Error(`Found ${l.length} pipelines but can only resolve one at a time.`);return me(u,{namespace:typeof a=="string"?Q({names:a}):a,enableExtensions:s,shaderGenerator:r,config:o,root:l[0]?.[p].branch})}function La(e){return Nr(e).code}function Ra(e){let t=N()??new st({namespace:Q(),shaderGenerator:Rt}),r=[1,1,1],n=[1,1,1],a=[r[0]*n[0],r[1]*n[1],r[2]*n[2]],o=new Map,s=Array.from({length:r[0]},()=>Array.from({length:r[1]},()=>Array.from({length:r[2]},()=>new Map))),i=Array.from({length:a[0]},()=>Array.from({length:a[1]},()=>Array.from({length:a[2]},()=>new Map))),u=Array.from({length:a[0]},(l,m)=>Array.from({length:a[1]},(y,f)=>Array.from({length:a[2]},(T,w)=>{let x=Math.floor(m/n[0]),P=Math.floor(f/n[1]),F=Math.floor(w/n[2]);return new Sn(o,{private:i[m][f][w],workgroup:s[x][P][F]})})));t.pushMode(u[0][0][0]);try{return{value:xt(t,e),buffers:o,privateVars:i,workgroupVars:s}}finally{t.popMode("simulate")}}function Ga(e,t,r,n){return new qr(e,t,r,n)}function it(e){let t=e;return t?.resourceType==="query-set"&&!!t[p]}var qr=class{constructor(t,r,n,a){this.type=r;this.count=n;this.rawQuerySet=a;this.#e=t.device,this._ownQuerySet=!a,this._querySet=a||null}resourceType="query-set";#e;_querySet=null;_ownQuerySet;_destroyed=!1;_available=!0;_readBuffer=null;_resolveBuffer=null;get querySet(){if(this._destroyed)throw new Error("This QuerySet has been destroyed.");return this.rawQuerySet?this.rawQuerySet:this._querySet?this._querySet:(this._querySet=this.#e.createQuerySet({type:this.type,count:this.count}),this._querySet)}get destroyed(){return this._destroyed}get available(){return this._available}get[p](){let t=this;return{get readBuffer(){return t._readBuffer||(t._readBuffer=t.#e.createBuffer({size:t.count*BigUint64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),t._readBuffer},get resolveBuffer(){return t._resolveBuffer||(t._resolveBuffer=t.#e.createBuffer({size:t.count*BigUint64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC})),t._resolveBuffer}}}$name(t){return v(this,t),this._querySet&&(this._querySet.label=t),this}resolve(){if(this._destroyed)throw new Error("This QuerySet has been destroyed.");if(!this._available)throw new Error("This QuerySet is busy resolving or reading.");let t=this.#e.createCommandEncoder();t.resolveQuerySet(this.querySet,0,this.count,this[p].resolveBuffer,0),this.#e.queue.submit([t.finish()])}async read(){if(!this._resolveBuffer)throw new Error("QuerySet must be resolved before reading.");this._available=!1;try{let t=this.#e.createCommandEncoder();t.copyBufferToBuffer(this[p].resolveBuffer,0,this[p].readBuffer,0,this.count*BigUint64Array.BYTES_PER_ELEMENT),this.#e.queue.submit([t.finish()]);let r=this[p].readBuffer;await r.mapAsync(GPUMapMode.READ);let n=new BigUint64Array(r.getMappedRange().slice());return r.unmap(),Array.from(n)}finally{this._available=!0}}destroy(){this._destroyed||(this._destroyed=!0,this._querySet&&this._ownQuerySet&&this._querySet.destroy(),this._readBuffer?.destroy(),this._resolveBuffer?.destroy(),this._readBuffer=this._resolveBuffer=null)}};var ut=class{constructor(t){this._make=t}_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 Io(e){return e instanceof be}var be=class{constructor(t,r){this.resourceType=t;this.buffer=r;this[D]=r,this.#e=this.buffer.as(this.resourceType)}[p]=!0;[D];#e;$name(t){return v(this[D],t),this}write(t){this.buffer.write(t)}writePartial(t){this.buffer.writePartial(t)}read(){return this.buffer.read()}get[S](){return this.#e.$}get $(){return this.#e.$}get value(){return this.$}[h](t){return t.resolve(this.#e)}};var b=e=>Nn(e??0),H=e=>qn(e??0),We=e=>jn(e??0),Uo={f32:e=>b(e[0]),f16:e=>We(e[0]).x,i32:e=>H(e[0]),u32:e=>e[0]??0,bool:e=>!!e[0],vec2f:e=>M(b(e[0]),b(e[1])),vec3f:e=>q(b(e[0]),b(e[1]),b(e[2])),vec4f:e=>V(b(e[0]),b(e[1]),b(e[2]),b(e[3])),vec2h(e){let t=We(e[0]);return Fe(t.x,t.y)},vec3h(e){let t=We(e[0]),r=We(e[1]);return Pe(t.x,t.y,r.x)},vec4h(e){let t=We(e[0]),r=We(e[1]);return De(t.x,t.y,r.x,r.y)},vec2i:e=>Y(H(e[0]),H(e[1])),vec3i:e=>ce(H(e[0]),H(e[1]),H(e[2])),vec4i:e=>X(H(e[0]),H(e[1]),H(e[2]),H(e[3])),vec2u:e=>J(e[0]??0,e[1]??0),vec3u:e=>C(e[0]??0,e[1]??0,e[2]??0),vec4u:e=>Z(e[0]??0,e[1]??0,e[2]??0,e[3]??0),"vec2<bool>":e=>vt(!!e[0],!!e[1]),"vec3<bool>":e=>It(!!e[0],!!e[1],!!e[2]),"vec4<bool>":e=>Ut(!!e[0],!!e[1],!!e[2],!!e[3]),mat2x2f:e=>Be(b(e[0]),b(e[1]),b(e[2]),b(e[3])),mat3x3f:e=>Ae(b(e[0]),b(e[1]),b(e[2]),b(e[4]),b(e[5]),b(e[6]),b(e[8]),b(e[9]),b(e[10])),mat4x4f:e=>$e(b(e[0]),b(e[1]),b(e[2]),b(e[3]),b(e[4]),b(e[5]),b(e[6]),b(e[7]),b(e[8]),b(e[9]),b(e[10]),b(e[11]),b(e[12]),b(e[13]),b(e[14]),b(e[15]))};function Fo(e,t){let r=Uo[t.type];if(r)return r(e);if(_(t)){let n=Object.keys(t.propTypes),a=Object.values(t.propTypes),o=jr(e,a);return Object.fromEntries(n.map((s,i)=>[s,o[i]]))}if(z(t)){let n=t.elementType,a=t.elementCount;return jr(e,Array.from({length:a},()=>n))}throw new Error(`Cannot deserialize data of type ${t.type}`)}function jr(e,t){let r=0;return t.map(n=>{if(!Se(n))return n;let a=Math.ceil(I(n)/4),o=Fo(e.subarray(r,r+a),n);return r+=a,o})}function Po(e,t){return jr(e,t).map(Ln)}function pt(e){let{indexBuffer:t,dataBuffer:r,logIdToMeta:n,options:a}=e;r.read().then(o=>{o.filter(s=>s.id).forEach(({id:s,serializedData:i})=>{let{argTypes:u,op:l}=n.get(s),m=Po(new Uint32Array(i),u);m.length===0&&m.push(""),console[l](`%c${a.messagePrefix}%c ${m[0]}`,"background: #936ff5; color: white;","color: inherit; background: none",...m.slice(1))})}),t.read().then(o=>{o>a.logCountLimit&&console.warn(`Log count limit per dispatch (${a.logCountLimit}) exceeded by ${o-a.logCountLimit} calls. Consider increasing the limit by passing appropriate options to tgpu.init().`)}),r.buffer.clear(),t.buffer.clear()}function ar(e,t,r){if(!r.enabledFeatures.has("timestamp-query"))throw new Error('Performance callback requires the "timestamp-query" feature to be enabled on GPU device.');return e.timestampWrites?{...e,performanceCallback:t}:{...e,performanceCallback:t,hasAutoQuerySet:!0,timestampWrites:{querySet:r.createQuerySet("timestamp",2),beginningOfPassWriteIndex:0,endOfPassWriteIndex:1}}}function or(e,t,r){if(!r.enabledFeatures.has("timestamp-query"))throw new Error('Timestamp writes require the "timestamp-query" feature to be enabled on GPU device.');e.hasAutoQuerySet&&e.timestampWrites&&e.timestampWrites.querySet.destroy();let n={querySet:t.querySet};return t.beginningOfPassWriteIndex!==void 0&&(n.beginningOfPassWriteIndex=t.beginningOfPassWriteIndex),t.endOfPassWriteIndex!==void 0&&(n.endOfPassWriteIndex=t.endOfPassWriteIndex),{...e,hasAutoQuerySet:!1,timestampWrites:n}}function sr(e,t){if(!e.timestampWrites)return{};let{querySet:r,beginningOfPassWriteIndex:n,endOfPassWriteIndex:a}=e.timestampWrites,o={querySet:it(r)?t.unwrap(r):r};return n!==void 0&&(o.beginningOfPassWriteIndex=n),a!==void 0&&(o.endOfPassWriteIndex=a),{timestampWrites:o}}function lt({root:e,priors:t}){let r=t.timestampWrites?.querySet,n=t.performanceCallback;if(!r)throw new Error("Cannot dispatch workgroups with performance callback without a query set.");if(!it(r))throw new Error("Performance callback with raw GPUQuerySet is not supported. Use TgpuQuerySet instead.");let a=e.device.createCommandEncoder();a.resolveQuerySet(e.unwrap(r),0,r.count,r[p].resolveBuffer,0),e.device.queue.submit([a.finish()]),e.device.queue.onSubmittedWorkDone().then(async()=>{if(!r.available)return;let o=await r.read(),s=o[t.timestampWrites?.beginningOfPassWriteIndex??0],i=o[t.timestampWrites?.endOfPassWriteIndex??1];if(s===void 0||i===void 0)throw new Error("QuerySet did not return valid timestamps.");await n(s,i)})}function Ca(e,t,r){return new Qr(new Hr(e,t,r),{})}var Qr=class e{constructor(t,r){this._core=t;this._priors=r;this[p]={get rawPipeline(){return t.unwrap().pipeline},get priors(){return r},get branch(){return t.branch}},this[D]=t}[p];resourceType="compute-pipeline";[D];[h](t){return t.resolve(this._core)}toString(){return`computePipeline:${c(this)??"<unnamed>"}`}get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){return xe(t)?new e(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[t.layout,t]])}):new e(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[t,r]])})}withPerformanceCallback(t){let r=ar(this._priors,t,this._core.branch);return new e(this._core,r)}withTimestampWrites(t){let r=or(this._priors,t,this._core.branch);return new e(this._core,r)}dispatchWorkgroups(t,r,n){let a=this._core.unwrap(),{branch:o}=this._core,s={label:c(this._core)??"<unnamed>",...sr(this._priors,o)},i=o.device.createCommandEncoder(),u=i.beginComputePass(s);u.setPipeline(a.pipeline);let l=new Set(a.usedBindGroupLayouts);if(a.usedBindGroupLayouts.forEach((m,y)=>{if(a.catchall&&y===a.catchall[0])u.setBindGroup(y,o.unwrap(a.catchall[1])),l.delete(m);else{let f=this._priors.bindGroupLayoutMap?.get(m);f!==void 0&&(l.delete(m),u.setBindGroup(y,o.unwrap(f)))}}),l.size>0)throw new fe(l);u.dispatchWorkgroups(t,r,n),u.end(),o.device.queue.submit([i.finish()]),a.logResources&&pt(a.logResources),this._priors.performanceCallback&&lt({root:o,priors:this._priors})}$name(t){return v(this._core,t),this}},Hr=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n}[p]=!0;_memo;[h](t){return t.withSlots(this._slotBindings,()=>(t.resolve(this._entryFn),g("",A)))}toString(){return"computePipelineCore"}unwrap(){if(this._memo===void 0){let t=this.branch.device,r=Gt.filter(y=>this.branch.enabledFeatures.has(Ct[y])),n,a,o=Q({names:this.branch.nameRegistrySetting});if(te?.enabled){let y=performance.mark("typegpu:resolution:start");n=me(this,{namespace:o,enableExtensions:r,shaderGenerator:this.branch.shaderGenerator,root:this.branch}),a=performance.measure("typegpu:resolution",{start:y.name})}else n=me(this,{namespace:o,enableExtensions:r,shaderGenerator:this.branch.shaderGenerator,root:this.branch});let{code:s,usedBindGroupLayouts:i,catchall:u,logResources:l}=n;u!==void 0&&i[u[0]]?.$name(`${c(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let m=t.createShaderModule({label:`${c(this)??"<unnamed>"} - Shader`,code:s});this._memo={pipeline:t.createComputePipeline({label:c(this)??"<unnamed>",layout:t.createPipelineLayout({label:`${c(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:i.map(y=>this.branch.unwrap(y))}),compute:{module:m}}),usedBindGroupLayouts:i,catchall:u,logResources:l},te?.enabled&&(async()=>{let y=performance.mark("typegpu:compile-start");await t.queue.onSubmittedWorkDone();let f=performance.measure("typegpu:compiled",{start:y.name});te?.record("resolution",{resolveDuration:a?.duration,compileDuration:f.duration,wgslSize:s.length})})()}return this._memo}};function Jr(e,t="vertex"){return new Yr(e,t)}function ur(e){return e?.resourceType==="vertex-layout"}var Kr=Symbol("defaultAttribEntry");function ir(e,t,r,n,a){if(ct(t)||xn(t)){let o=ne(t);return o!==void 0&&(n[a??Kr]=o),ir(e,t.inner,k(r,j(t)),n)}if(_(t)){let o=r,s=t.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=k(o,$(u));let l=[i,ir(e,u,o,n,i)];return o+=I(u),l}))}if(re(t)){let o=r,s=t.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=k(o,j(u));let l=[i,ir(e,u,o,n,i)];return o+=I(u),l}))}if("type"in t&&typeof t.type=="string"){if(pn.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=ln[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var Yr=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;let n=t(0);this.stride=k(I(n.elementType),$(n)),this.attrib=ir(this,n.elementType,0,this._customLocationMap)}[p]=!0;resourceType="vertex-layout";stride;attrib;_customLocationMap={};get vertexLayout(){if(this._customLocationMap[Kr]!==void 0){if(typeof this.attrib.format!="string"||typeof this.attrib.offset!="number")throw new Error("Single attribute vertex layouts must have a format and offset.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[{format:this.attrib.format,offset:this.attrib.offset,shaderLocation:this._customLocationMap[Kr]}]}}if(!Object.keys(this.attrib).every(r=>this._customLocationMap[r]!==void 0))throw new Error("All attributes must have custom locations in order to unwrap a vertex layout.");return{arrayStride:this.stride,stepMode:this.stepMode,attributes:[...Object.entries(this.attrib).map(([r,n])=>({format:n.format,offset:n.offset,shaderLocation:this._customLocationMap[r]}))]}}$name(t){return v(this,t),this}};function Do(e){return typeof e?.loadOp=="string"}function Ea(e,t){if(ae(e)){if(!Do(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=e[n];if(ue(a))continue;let o=t[n];if(!o)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(o)}return r}function Bo(e){return typeof e?.format=="string"}function Va(e,t){if(ae(e)){if(Tn(e))return[];if(!Bo(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=e[n];if(ue(a))continue;let o=t[n];if(!o)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(o)}return r}function en(e){return new Xr(new Zr(e),{})}var Xr=class e{[p];resourceType="render-pipeline";[D];hasIndexBuffer=!1;constructor(t,r){this[p]={core:t,priors:r,branch:t.options.branch},this[D]=t}[h](t){return t.resolve(this[p].core)}toString(){return`renderPipeline:${c(this)??"<unnamed>"}`}$name(t){return v(this[p].core,t),this}with(t,r){let n=this[p];if(xe(t))return new e(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[t.layout,t]])});if(er(t))return new e(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[t,r]])});if(ur(t))return new e(n.core,{...n.priors,vertexLayoutMap:new Map([...n.priors.vertexLayoutMap??[],[t,r]])});throw new Error("Unsupported value passed into .with()")}withPerformanceCallback(t){let r=this[p],n=ar(r.priors,t,r.core.options.branch);return new e(r.core,n)}withTimestampWrites(t){let r=this[p],n=or(r.priors,t,r.core.options.branch);return new e(r.core,n)}withColorAttachment(t){let r=this[p];return new e(r.core,{...r.priors,colorAttachment:t})}withDepthStencilAttachment(t){let r=this[p];return new e(r.core,{...r.priors,depthStencilAttachment:t})}withIndexBuffer(t,r,n,a){let o=this[p];if(ze(t)){if(typeof r!="string")throw new Error("If a GPUBuffer is passed, indexFormat must be provided.");return new e(o.core,{...o.priors,indexBuffer:{buffer:t,indexFormat:r,offsetBytes:n,sizeBytes:a}})}let s={u32:"uint32",u16:"uint16"},i=t.dataType.elementType;return new e(o.core,{...o.priors,indexBuffer:{buffer:t,indexFormat:s[i.type],offsetBytes:r!==void 0?r*I(i):void 0,sizeBytes:a!==void 0?a*I(i):void 0}})}setupRenderPass(t){let r=this[p],n=r.core.unwrap(),{branch:a,fragmentFn:o}=r.core.options,s=o?Ea(o.shell.out,r.priors.colorAttachment??{}).map(f=>ee(f.view)?{...f,view:a.unwrap(f.view).createView()}:he(f.view)?{...f,view:a.unwrap(f.view)}:f):[null],i={label:c(r.core)??"<unnamed>",colorAttachments:s,...sr(r.priors,a)};if(r.priors.depthStencilAttachment!==void 0){let f=r.priors.depthStencilAttachment;ee(f.view)?i.depthStencilAttachment={...f,view:a.unwrap(f.view).createView()}:i.depthStencilAttachment=f}let u=t.beginRenderPass(i);u.setPipeline(n.pipeline);let l=new Set(n.usedBindGroupLayouts);n.usedBindGroupLayouts.forEach((f,T)=>{if(n.catchall&&T===n.catchall[0])u.setBindGroup(T,a.unwrap(n.catchall[1])),l.delete(f);else{let w=r.priors.bindGroupLayoutMap?.get(f);w!==void 0&&(l.delete(f),u.setBindGroup(T,a.unwrap(w)))}});let m=new Set(r.core.usedVertexLayouts);if(r.core.usedVertexLayouts.forEach((f,T)=>{let w=r.priors.vertexLayoutMap?.get(f);w&&(m.delete(f),u.setVertexBuffer(T,a.unwrap(w)))}),l.size>0)throw new fe(l);if(m.size>0)throw new Oe(m);return u}draw(t,r,n,a){let o=this[p],{branch:s}=o.core.options,{logResources:i}=o.core.unwrap(),u=s.device.createCommandEncoder(),l=this.setupRenderPass(u);l.draw(t,r,n,a),l.end(),s.device.queue.submit([u.finish()]),i&&pt(i),o.priors.performanceCallback&&lt({root:s,priors:o.priors})}drawIndexed(t,r,n,a,o){let s=this[p];if(!s.priors.indexBuffer)throw new Error("No index buffer set for this render pipeline.");let{logResources:i}=s.core.unwrap(),{branch:u}=s.core.options,{buffer:l,indexFormat:m,offsetBytes:y,sizeBytes:f}=s.priors.indexBuffer,T=u.device.createCommandEncoder(),w=this.setupRenderPass(T);ze(l)?w.setIndexBuffer(l,m,y,f):w.setIndexBuffer(u.unwrap(l),m,y,f),w.drawIndexed(t,r,n,a,o),w.end(),u.device.queue.submit([T.finish()]),i&&pt(i),s.priors.performanceCallback&&lt({root:u,priors:s.priors})}},Zr=class{constructor(t){this.options=t;let r=ea(t.vertexFn.shell.in??{},t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=t.fragmentFn&&t.targets?Va(t.fragmentFn.shell.out,t.targets):[null]}[p]=!0;usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;[h](t){let{vertexFn:r,fragmentFn:n,slotBindings:a}=this.options,o=Ao(r.shell.out,n?.shell.in,c(r)??"<unnamed>",c(n)??"<unnamed>");return t.withVaryingLocations(o,()=>t.withSlots(a,()=>(t.resolve(r),n&&t.resolve(n),g("",A))))}toString(){return"renderPipelineCore"}unwrap(){if(this._memo===void 0){let{branch:t,primitiveState:r,depthStencilState:n,multisampleState:a}=this.options,o=t.device,s=Gt.filter(F=>t.enabledFeatures.has(Ct[F])),i,u,l=Q({names:t.nameRegistrySetting});if(te?.enabled){let F=performance.mark("typegpu:resolution:start");i=me(this,{namespace:l,enableExtensions:s,shaderGenerator:t.shaderGenerator,root:t}),u=performance.measure("typegpu:resolution",{start:F.name})}else i=me(this,{namespace:l,enableExtensions:s,shaderGenerator:t.shaderGenerator,root:t});let{code:m,usedBindGroupLayouts:y,catchall:f,logResources:T}=i;f!==void 0&&y[f[0]]?.$name(`${c(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let w=o.createShaderModule({label:`${c(this)??"<unnamed>"} - Shader`,code:m}),x={layout:o.createPipelineLayout({label:`${c(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:y.map(F=>t.unwrap(F))}),vertex:{module:w,buffers:this._vertexBufferLayouts}},P=c(this);P!==void 0&&(x.label=P),this.options.fragmentFn&&(x.fragment={module:w,targets:this._targets}),r&&(Se(r.stripIndexFormat)?x.primitive={...r,stripIndexFormat:{u32:"uint32",u16:"uint16"}[r.stripIndexFormat.type]}:x.primitive=r),n&&(x.depthStencil=n),a&&(x.multisample=a),this._memo={pipeline:o.createRenderPipeline(x),usedBindGroupLayouts:y,catchall:f,logResources:T},te?.enabled&&(async()=>{let F=performance.mark("typegpu:compile-start");await o.queue.onSubmittedWorkDone();let R=performance.measure("typegpu:compiled",{start:F.name});te?.record("resolution",{resolveDuration:u?.duration,compileDuration:R.duration,wgslSize:m.length})})()}return this._memo}};function Ao(e,t,r,n){let a={},o=new Set;function s(u,l){a[u]=l,o.add(l)}for(let[u,l]of Object.entries(e)){let m=ne(l);m!==void 0&&s(u,m)}for(let[u,l]of Object.entries(t??{})){let m=ne(l);m!==void 0&&(a[u]===void 0?s(u,m):a[u]!==m&&console.warn(`Mismatched location between vertexFn (${r}) output (${a[u]}) and fragmentFn (${n}) input (${m}) for the key "${u}", using the location set on vertex output.`))}let i=0;for(let u of Object.keys(e??{}))if(!(ue(e[u])||a[u]!==void 0)){for(;o.has(i);)i++;s(u,i)}return a}function $o(e){if(e.includes(0))throw new Error("Size and workgroupSize cannot contain zeroes.");return C(e[0]??1,e[1]??1,e[2]??1)}var Lo=[C(1,1,1),C(256,1,1),C(16,16,1),C(8,8,4)],tn=class e{#e;#r;#t;#n;#a;constructor(t,r,n,a){this.#e=t,this.#r=r,this.#t=n,this.#n=a,this.#a=C()}with(t){return new e(this.#e,this.#r.with(t),this.#t,this.#n)}dispatchThreads(...t){let r=$o(t),n=On(q(r).div(q(this.#n)));Qn(r,this.#a)||(this.#a=r,this.#t.write(r)),this.#r.dispatchWorkgroups(n.x,n.y,n.z)}get pipeline(){return this.#r}get sizeUniform(){return this.#t}},rn=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 nn(this._getRoot(),this._slotBindings,t)}createGuardedComputePipeline(t){let r=this._getRoot();if(t.length>=4)throw new Error("Guarded compute callback only supports up to three dimensions.");let n=Lo[t.length],a=U([G,G,G])(t),o=r.createUniform(C),s=Et({workgroupSize:n,in:{id:zn.globalInvocationId}})`{
187
187
  if (any(in.id >= sizeUniform)) {
188
188
  return;
189
189
  }
190
190
  wrappedCallback(in.id.x, in.id.y, in.id.z);
191
- }`.$uses({sizeUniform:o,wrappedCallback:a}),i=this.withCompute(s).createPipeline();return new nn(r,i,o,n)}withVertex(e,r){return new sn({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:e,vertexAttribs:r,multisampleState:void 0})}pipe(e){let r=e(new Le([]));return new t(this._getRoot,[...this._slotBindings,...r.bindings])}},on=class{constructor(e,r,n){this._root=e;this._slotBindings=r;this._entryFn=n}createPipeline(){return Wa(this._root,this._slotBindings,this._entryFn)}},sn=class t{constructor(e){this._options=e}withFragment(e,r,n){return K(typeof e!="string","Just type mismatch validation"),K(typeof r!="string","Just type mismatch validation"),new un({...this._options,fragmentFn:e,targets:r})}withPrimitive(e){return new t({...this._options,primitiveState:e})}withDepthStencil(e){return new t({...this._options,depthStencilState:e})}withMultisample(e){return new t({...this._options,multisampleState:e})}createPipeline(){return rn({...this._options,fragmentFn:null,targets:null})}},un=class t{constructor(e){this._options=e}withPrimitive(e){return new t({...this._options,primitiveState:e})}withDepthStencil(e){return new t({...this._options,depthStencilState:e})}withMultisample(e){return new t({...this._options,multisampleState:e})}createPipeline(){return rn(this._options)}},pr=class extends an{constructor(r,n,a,o,s){super(()=>this,[]);this.device=r;this.nameRegistrySetting=n;this._ownDevice=a;this.shaderGenerator=s;this["~unstable"]=this,this[l]={logOptions:o}}"~unstable";_unwrappedBindGroupLayouts=new ut(r=>r.unwrap(this));_unwrappedBindGroups=new ut(r=>r.unwrap(this));_commandEncoder=null;[l];get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}get enabledFeatures(){return new Set(this.device.features)}createBuffer(r,n){return Ze(this,r,n)}createUniform(r,n){let a=Ze(this,r,n).$usage("uniform");return new xe("uniform",a)}createMutable(r,n){let a=Ze(this,r,n).$usage("storage");return new xe("mutable",a)}createReadonly(r,n){let a=Ze(this,r,n).$usage("storage");return new xe("readonly",a)}createQuerySet(r,n,a){return _a(this,r,n,a)}createBindGroup(r,n){return new Ce(r,n)}destroy(){xa(this.device),this._ownDevice&&this.device.destroy()}createTexture(r){return Sa(r,this)}createSampler(r){return ya(r,this)}createComparisonSampler(r){return Ta(r,this)}unwrap(r){if(Nr(r))return r[l].rawPipeline;if(qr(r))return r[l].core.unwrap().pipeline;if(er(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(Te(r))return this._unwrappedBindGroups.getOrMake(r);if(pe(r))return r.buffer;if(ee(r))return r[l].unwrap();if(nt(r)){if(!r[l].unwrap)throw new Error("Cannot unwrap laid-out texture view as it has no underlying resource.");return r[l].unwrap()}if(ur(r))return r.vertexLayout;if(et(r)||tt(r)){if(r[l].unwrap)return r[l].unwrap();throw new Error("Cannot unwrap laid-out sampler.")}if(it(r))return r.querySet;throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,s=new Map,i,u=()=>{if(!i)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:p,priors:m}=i[l],c=p.unwrap();a.setPipeline(c.pipeline);let y=new Set(c.usedBindGroupLayouts);c.usedBindGroupLayouts.forEach((v,x)=>{if(c.catchall&&x===c.catchall[0])a.setBindGroup(x,this.unwrap(c.catchall[1])),y.delete(v);else{let P=m.bindGroupLayoutMap?.get(v)??o.get(v);P!==void 0&&(y.delete(v),Te(P)?a.setBindGroup(x,this.unwrap(P)):a.setBindGroup(x,P))}});let h=new Set;if(p.usedVertexLayouts.forEach((v,x)=>{let P=m.vertexLayoutMap?.get(v),F=P?{buffer:P,offset:void 0,size:void 0}:s.get(v);!F||!F.buffer?h.add(v):pe(F.buffer)?a.setVertexBuffer(x,this.unwrap(F.buffer),F.offset,F.size):a.setVertexBuffer(x,F.buffer,F.offset,F.size)}),y.size>0)throw new me(y);if(h.size>0)throw new Me(h)};n({setViewport(...p){a.setViewport(...p)},setScissorRect(...p){a.setScissorRect(...p)},setBlendConstant(...p){a.setBlendConstant(...p)},setStencilReference(...p){a.setStencilReference(...p)},beginOcclusionQuery(...p){a.beginOcclusionQuery(...p)},endOcclusionQuery(...p){a.endOcclusionQuery(...p)},executeBundles(...p){a.executeBundles(...p)},setPipeline(p){i=p},setIndexBuffer:(p,m,c,y)=>{pe(p)?a.setIndexBuffer(this.unwrap(p),m,c,y):a.setIndexBuffer(p,m,c,y)},setVertexBuffer(p,m,c,y){s.set(p,{buffer:m,offset:c,size:y})},setBindGroup(p,m){o.set(p,m)},draw(p,m,c,y){u(),a.draw(p,m,c,y)},drawIndexed(...p){u(),a.drawIndexed(...p)},drawIndirect(...p){u(),a.drawIndirect(...p)},drawIndexedIndirect(...p){u(),a.drawIndexedIndirect(...p)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function Oa(t){let{adapter:e,device:r,unstable_names:n="random",unstable_logOptions:a}=t??{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(e);if(!o)throw new Error("Could not find a compatible GPU");let s=[];for(let u of r?.requiredFeatures??[]){if(!o.features.has(u))throw new Error(`Requested feature "${u}" is not supported by the adapter.`);s.push(u)}for(let u of r?.optionalFeatures??[])o.features.has(u)?s.push(u):console.warn(`Optional feature "${u}" is not supported by the adapter.`);let i=await o.requestDevice({...r,requiredFeatures:s});return new pr(i,n,!0,a??{},t?.shaderGenerator)}function za(t){let{device:e,unstable_names:r="random",unstable_logOptions:n}=t??{};return new pr(e,r,!1,n??{},t?.shaderGenerator)}function Na(t,e){return new pn(t,e)}var pn=class{constructor(e,r=void 0){this.schema=e;this.defaultValue=r;this.slot=he(r),this[D]=this.slot}[l]=!0;[D];resourceType="accessor";slot;get[w](){return new Proxy({[l]:!0,[B]:this.#e(),[T]:e=>e.resolve(this),toString:()=>`accessor:${f(this)??"<unnamed>"}.$`},G)}#e(){let e=z(),r=ge(e.unwrap(this.slot));return He(r)?r[l].gpuImpl():g(r,this.schema)}$name(e){return this.slot.$name(e),this}toString(){return`accessor:${f(this)??"<unnamed>"}`}get value(){if(E())return this[w];throw new Error("`tgpu.accessor` relies on GPU resources and cannot be accessed outside of a compute dispatch or draw call")}get $(){return this.value}[T](e){let r=this.#e();return g(e.resolve(r.value,r.dataType).value,r.dataType)}};function qa(t){return _o(t)}function Vo([t,e]){return`${f(t)??"<unnamed>"}=${e}`}function _o(t){if(z())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{[l]:!0,resourceType:"derived","~compute":t,get[w](){let r=z();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ge(r.unwrap(this))},get value(){return this[w]},get $(){return this.value},with(r,n){return ja(this,[[r,n]])},toString(){return"derived"}}}function ja(t,e){return{[l]:!0,resourceType:"derived","~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},[H]:{inner:t,pairs:e},get[w](){let n=z();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ge(n.unwrap(this))},get value(){return this[w]},get $(){return this.value},with(n,a){return ja(t,[...e,[n,a]])},toString(){return`derived[${e.map(Vo).join(", ")}]`}}}var Wo={fn:U,bindGroupLayout:Zt,vertexLayout:Zr,slot:he,init:Oa,initFromDevice:za,resolve:Ea,resolveWithContext:jr,privateVar:Ee,workgroupVar:kr,const:Ir,"~unstable":{fn:U,fragmentFn:ea,vertexFn:_n,computeFn:Et,vertexLayout:Zr,namespace:j,derived:qa,slot:he,accessor:Na,privateVar:Ee,workgroupVar:kr,const:Ir,declare:Xn,simulate:Va}},Wf=Wo;export{me as MissingBindGroupsError,Ha as MissingLinksError,cr as MissingSlotValueError,Me as MissingVertexBuffersError,gr as NotUniformError,be as ResolutionError,Wf as default,pe as isBuffer,Do as isBufferShorthand,tt as isComparisonSampler,ht as isDerived,et as isSampler,Tt as isSlot,ee as isTexture,He as isTgpuFn,So as isUsableAsRender,Er as isUsableAsSampled,ye as isUsableAsStorage,jt as isUsableAsUniform,yo as isUsableAsVertex,Io as isVariable,Wo as tgpu};
191
+ }`.$uses({sizeUniform:o,wrappedCallback:a}),i=this.withCompute(s).createPipeline();return new tn(r,i,o,n)}withVertex(t,r){return new an({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r,multisampleState:void 0})}pipe(t){let r=t(new Ge([]));return new e(this._getRoot,[...this._slotBindings,...r.bindings])}},nn=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return Ca(this._root,this._slotBindings,this._entryFn)}},an=class e{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 on({...this._options,fragmentFn:t,targets:r})}withPrimitive(t){return new e({...this._options,primitiveState:t})}withDepthStencil(t){return new e({...this._options,depthStencilState:t})}withMultisample(t){return new e({...this._options,multisampleState:t})}createPipeline(){return en({...this._options,fragmentFn:null,targets:null})}},on=class e{constructor(t){this._options=t}withPrimitive(t){return new e({...this._options,primitiveState:t})}withDepthStencil(t){return new e({...this._options,depthStencilState:t})}withMultisample(t){return new e({...this._options,multisampleState:t})}createPipeline(){return en(this._options)}},pr=class extends rn{constructor(r,n,a,o,s){super(()=>this,[]);this.device=r;this.nameRegistrySetting=n;this._ownDevice=a;this.shaderGenerator=s;this["~unstable"]=this,this[p]={logOptions:o}}"~unstable";_unwrappedBindGroupLayouts=new ut(r=>r.unwrap(this));_unwrappedBindGroups=new ut(r=>r.unwrap(this));[p];get enabledFeatures(){return new Set(this.device.features)}createBuffer(r,n){return et(this,r,n)}createUniform(r,n){let a=et(this,r,n).$usage("uniform");return new be("uniform",a)}createMutable(r,n){let a=et(this,r,n).$usage("storage");return new be("mutable",a)}createReadonly(r,n){let a=et(this,r,n).$usage("storage");return new be("readonly",a)}createQuerySet(r,n,a){return Ga(this,r,n,a)}createBindGroup(r,n){return new Ve(r,n)}destroy(){ga(this.device),this._ownDevice&&this.device.destroy()}createTexture(r){return ha(r,this)}createSampler(r){return fa(r,this)}createComparisonSampler(r){return da(r,this)}unwrap(r){if(Or(r))return r[p].rawPipeline;if(zr(r))return r[p].core.unwrap().pipeline;if(er(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(xe(r))return this._unwrappedBindGroups.getOrMake(r);if(le(r))return r.buffer;if(ee(r))return r[p].unwrap();if(he(r)){if(!r[p].unwrap)throw new Error("Cannot unwrap laid-out texture view as it has no underlying resource.");return r[p].unwrap()}if(ur(r))return r.vertexLayout;if(tt(r)||rt(r)){if(r[p].unwrap)return r[p].unwrap();throw new Error("Cannot unwrap laid-out sampler.")}if(it(r))return r.querySet;throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.device.createCommandEncoder(),o=a.beginRenderPass(r),s=new Map,i=new Map,u,l=()=>{if(!u)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:m,priors:y}=u[p],f=m.unwrap();o.setPipeline(f.pipeline);let T=new Set(f.usedBindGroupLayouts);f.usedBindGroupLayouts.forEach((x,P)=>{if(f.catchall&&P===f.catchall[0])o.setBindGroup(P,this.unwrap(f.catchall[1])),T.delete(x);else{let F=y.bindGroupLayoutMap?.get(x)??s.get(x);F!==void 0&&(T.delete(x),xe(F)?o.setBindGroup(P,this.unwrap(F)):o.setBindGroup(P,F))}});let w=new Set;if(m.usedVertexLayouts.forEach((x,P)=>{let F=y.vertexLayoutMap?.get(x),R=F?{buffer:F,offset:void 0,size:void 0}:i.get(x);!R||!R.buffer?w.add(x):le(R.buffer)?o.setVertexBuffer(P,this.unwrap(R.buffer),R.offset,R.size):o.setVertexBuffer(P,R.buffer,R.offset,R.size)}),T.size>0)throw new fe(T);if(w.size>0)throw new Oe(w)};n({setViewport(...m){o.setViewport(...m)},setScissorRect(...m){o.setScissorRect(...m)},setBlendConstant(...m){o.setBlendConstant(...m)},setStencilReference(...m){o.setStencilReference(...m)},beginOcclusionQuery(...m){o.beginOcclusionQuery(...m)},endOcclusionQuery(...m){o.endOcclusionQuery(...m)},executeBundles(...m){o.executeBundles(...m)},setPipeline(m){u=m},setIndexBuffer:(m,y,f,T)=>{le(m)?o.setIndexBuffer(this.unwrap(m),y,f,T):o.setIndexBuffer(m,y,f,T)},setVertexBuffer(m,y,f,T){i.set(m,{buffer:y,offset:f,size:T})},setBindGroup(m,y){s.set(m,y)},draw(m,y,f,T){l(),o.draw(m,y,f,T)},drawIndexed(...m){l(),o.drawIndexed(...m)},drawIndirect(...m){l(),o.drawIndirect(...m)},drawIndexedIndirect(...m){l(),o.drawIndexedIndirect(...m)}}),o.end(),this.device.queue.submit([a.finish()])}flush(){console.warn("flush() has been deprecated, and has no effect.")}};async function _a(e){let{adapter:t,device:r,unstable_names:n="random",unstable_logOptions:a}=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");let s=[];for(let u of r?.requiredFeatures??[]){if(!o.features.has(u))throw new Error(`Requested feature "${u}" is not supported by the adapter.`);s.push(u)}for(let u of r?.optionalFeatures??[])o.features.has(u)?s.push(u):console.warn(`Optional feature "${u}" is not supported by the adapter.`);let i=await o.requestDevice({...r,requiredFeatures:s});return new pr(i,n,!0,a??{},e?.shaderGenerator)}function Wa(e){let{device:t,unstable_names:r="random",unstable_logOptions:n}=e??{};return new pr(t,r,!1,n??{},e?.shaderGenerator)}function Ma(e,t){return new sn(e,t)}var sn=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;this.slot=we(r),this[D]=this.slot}[p]=!0;[D];resourceType="accessor";slot;get[S](){return new Proxy({[p]:!0,[L]:this.#e(),[h]:t=>t.resolve(this),toString:()=>`accessor:${c(this)??"<unnamed>"}.$`},E)}#e(){let t=N(),r=ge(t.unwrap(this.slot));return Ke(r)?r[p].gpuImpl():g(r,this.schema)}$name(t){return this.slot.$name(t),this}toString(){return`accessor:${c(this)??"<unnamed>"}`}get value(){if(W())return this[S];throw new Error("`tgpu.accessor` relies on GPU resources and cannot be accessed outside of a compute dispatch or draw call")}get $(){return this.value}[h](t){let r=this.#e();return g(t.resolve(r.value,r.dataType).value,r.dataType)}};function ka(e){return Go(e)}function Ro([e,t]){return`${c(e)??"<unnamed>"}=${t}`}function Go(e){if(N())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{[p]:!0,resourceType:"derived","~compute":e,get[S](){let r=N();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ge(r.unwrap(this))},get value(){return this[S]},get $(){return this.value},with(r,n){return Oa(this,[[r,n]])},toString(){return"derived"}}}function Oa(e,t){return{[p]:!0,resourceType:"derived","~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},[K]:{inner:e,pairs:t},get[S](){let n=N();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ge(n.unwrap(this))},get value(){return this[S]},get $(){return this.value},with(n,a){return Oa(e,[...t,[n,a]])},toString(){return`derived[${t.map(Ro).join(", ")}]`}}}var Co={fn:U,bindGroupLayout:Zt,vertexLayout:Jr,slot:we,init:_a,initFromDevice:Wa,resolve:La,resolveWithContext:Nr,privateVar:_e,workgroupVar:_r,const:wr,"~unstable":{fn:U,fragmentFn:Yn,vertexFn:Cn,computeFn:Et,vertexLayout:Jr,namespace:Q,derived:ka,slot:we,accessor:Ma,privateVar:_e,workgroupVar:_r,const:wr,declare:Hn,simulate:Ra}},bf=Co;export{fe as MissingBindGroupsError,Na as MissingLinksError,cr as MissingSlotValueError,Oe as MissingVertexBuffersError,gr as NotUniformError,ve as ResolutionError,bf as default,le as isBuffer,Io as isBufferShorthand,rt as isComparisonSampler,ht as isDerived,tt as isSampler,Tt as isSlot,ee as isTexture,Ke as isTgpuFn,ho as isUsableAsRender,Gr as isUsableAsSampled,Te as isUsableAsStorage,jt as isUsableAsUniform,mo as isUsableAsVertex,wo as isVariable,Co as tgpu};
192
192
  //# sourceMappingURL=index.js.map