typegpu 0.6.0 → 0.7.0

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 (42) hide show
  1. package/chunk-3K53YJSU.cjs +10 -0
  2. package/chunk-3K53YJSU.cjs.map +1 -0
  3. package/chunk-BF35NEOX.cjs +43 -0
  4. package/chunk-BF35NEOX.cjs.map +1 -0
  5. package/chunk-IH2QU6TV.js +43 -0
  6. package/chunk-IH2QU6TV.js.map +1 -0
  7. package/chunk-S27MYQ6U.js +10 -0
  8. package/chunk-S27MYQ6U.js.map +1 -0
  9. package/data/index.cjs +1 -1
  10. package/data/index.cjs.map +1 -1
  11. package/data/index.d.cts +3 -3
  12. package/data/index.d.ts +3 -3
  13. package/data/index.js +1 -1
  14. package/index.cjs +18 -29
  15. package/index.cjs.map +1 -1
  16. package/index.d.cts +38 -3
  17. package/index.d.ts +38 -3
  18. package/index.js +18 -29
  19. package/index.js.map +1 -1
  20. package/{matrix-S8W4dk8I.d.ts → matrix-BXuR-7-A.d.ts} +1 -1
  21. package/{matrix-BN6ObiMv.d.cts → matrix-DzXuhOr3.d.cts} +1 -1
  22. package/package.json +1 -1
  23. package/std/index.cjs +1 -1
  24. package/std/index.cjs.map +1 -1
  25. package/std/index.d.cts +22 -9
  26. package/std/index.d.ts +22 -9
  27. package/std/index.js +1 -1
  28. package/std/index.js.map +1 -1
  29. package/{tgpuComputeFn-DOUjhQua.d.ts → tgpuConstant-BAmV6caN.d.cts} +3171 -2970
  30. package/{tgpuComputeFn-DOUjhQua.d.cts → tgpuConstant-BAmV6caN.d.ts} +3171 -2970
  31. package/chunk-APTRHY5Y.js +0 -41
  32. package/chunk-APTRHY5Y.js.map +0 -1
  33. package/chunk-RC26P3MP.cjs +0 -2
  34. package/chunk-RC26P3MP.cjs.map +0 -1
  35. package/chunk-RK6TMFVW.js +0 -2
  36. package/chunk-RK6TMFVW.js.map +0 -1
  37. package/chunk-S62QJDM6.js +0 -2
  38. package/chunk-S62QJDM6.js.map +0 -1
  39. package/chunk-TG4A6AM3.cjs +0 -2
  40. package/chunk-TG4A6AM3.cjs.map +0 -1
  41. package/chunk-UMHCZDPA.cjs +0 -41
  42. package/chunk-UMHCZDPA.cjs.map +0 -1
package/index.js CHANGED
@@ -1,31 +1,20 @@
1
- import{S as $,T as K,V as v,W as ur,X as ct,_ as xt,a as O,aa as Ce,b as qe,ba as Re,ca as Dn,da as In}from"./chunk-S62QJDM6.js";import{c as vn}from"./chunk-RK6TMFVW.js";import{$ as hn,A as mn,Aa as ir,B as dn,Ba as F,C as ye,Ca as je,D as mt,Da as _,E as fn,Ea as k,F as cn,Fa as sr,G as X,Ga as Sn,H as gn,I as yn,J as Tn,K as Te,M as ne,N as q,O as B,P as rr,Pa as gt,Q as xn,Qa as yt,Ra as Tt,W as dt,X as ft,Y as Ue,Z as Fe,_ as Q,a as l,b as w,c as U,ca as W,d as S,da as M,e as L,ea as V,f as Ht,fa as T,g as Yt,ga as bn,h as ee,ha as wn,i as d,ia as nr,j as h,ja as Pe,k as te,ka as ar,l as un,la as E,m as ce,ma as C,n as Y,o as Jt,oa as R,p as Xt,pa as c,q as Zt,qa as Me,r as ge,ra as N,s as Oe,sa as Ne,t as We,ta as ae,u as pn,ua as oe,v as re,va as or,w as er,wa as xe,x as tr,xa as ze,y as J,ya as Be,z as ln,za as Ae}from"./chunk-APTRHY5Y.js";function Un(e){if(typeof e?.[U]=="function")return e[U].bind(e)}function ht(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var Fa={f:{1:c,2:N,3:xe,4:F},h:{1:Me,2:Ne,3:ze,4:je},i:{1:R,2:ae,3:Be,4:_},u:{1:C,2:oe,3:Ae,4:k},b:{1:E,2:or,3:ir,4:sr}},Pa={vec2f:N,vec2h:Ne,vec2i:ae,vec2u:oe,"vec2<bool>":or,vec3f:xe,vec3h:ze,vec3i:Be,vec3u:Ae,"vec3<bool>":ir,vec4f:F,vec4h:je,vec4i:_,vec4u:k,"vec4<bool>":sr,mat2x2f:gt,mat3x3f:yt,mat4x4f:Tt},Fn={vec2f:c,vec2h:Me,vec2i:R,vec2u:C,"vec2<bool>":E,vec3f:c,vec3h:Me,vec3i:R,vec3u:C,"vec3<bool>":E,vec4f:c,vec4h:Me,vec4i:R,vec4u:C,"vec4<bool>":E,mat2x2f:N,mat3x3f:xe,mat4x4f:F};function Qe(e,t){if(B(e)||Q(e))return e.propTypes[t]??V;if(e===E||vn(e))return V;let r=t.length;if(X(e)&&r>=1&&r<=4){let n=e.type.includes("bool")?"b":e.type[4],a=Fa[n][r];if(a)return a}return V}function pr(e){return q(e)||Fe(e)?e.elementType:e.type in Fn?Fn[e.type]:V}function lr(e){if(/^0x[0-9a-f]+$/i.test(e))return T(e,Pe);if(/^0b[01]+$/i.test(e))return T(`${Number.parseInt(e.slice(2),2)}`,Pe);if(/^-?(?:\d+\.\d*|\d*\.\d+)$/i.test(e))return T(e,ar);if(/^-?\d+(?:\.\d+)?e-?\d+$/i.test(e))return T(e,ar);if(/^-?\d+$/i.test(e))return T(e,Pe)}var mr={rank:Number.POSITIVE_INFINITY,action:"none"};function $e(e){return e.type==="decorated"?e.inner:e}function Pn(e){return X(e)?Sn[e.type]:void 0}function bt(e,t){let r=$e(e),n=$e(t);if(r.type===n.type)return{rank:0,action:"none"};if(r.type==="abstractFloat"){if(n.type==="f32")return{rank:1,action:"none"};if(n.type==="f16")return{rank:2,action:"none"}}if(r.type==="abstractInt"){if(n.type==="i32")return{rank:3,action:"none"};if(n.type==="u32")return{rank:4,action:"none"};if(n.type==="abstractFloat")return{rank:5,action:"none"};if(n.type==="f32")return{rank:6,action:"none"};if(n.type==="f16")return{rank:7,action:"none"}}if(X(r)&&X(n)){let a=Pn(r),o=Pn(n);if(a&&o)return bt(a,o)}return Te(r)&&Te(n)?{rank:0,action:"none"}:mr}function Ba(e,t){let r=$e(e),n=$e(t);if(r.type==="ptr"&&bt(r.inner,n).rank<Number.POSITIVE_INFINITY)return{rank:0,action:"deref"};if(n.type==="ptr"&&bt(r,n.inner).rank<Number.POSITIVE_INFINITY)return{rank:1,action:"ref"};let a={f32:0,f16:1,i32:2,u32:3,bool:4};if(r.type in a&&n.type in a){let o=r.type,i=n.type;if(o!==i){let s=a[o];return{rank:a[i]<s?10:20,action:"cast",targetType:n}}}return mr}function Aa(e,t,r){let n=bt(e,t);return n.rank<Number.POSITIVE_INFINITY?n:r?Ba(e,t):mr}function Bn(e,t,r){let n,a=Number.POSITIVE_INFINITY,o=new Map;for(let u of t){let f=0,m=[],g=!0;for(let y of e){let x=Aa(y,u,r);if(x.rank===Number.POSITIVE_INFINITY){g=!1;break}f+=x.rank,m.push(x)}g&&f<a&&(a=f,n=u,o.set(n,m))}if(!n)return;let s=o.get(n).map((u,f)=>({sourceIndex:f,action:u.action,...u.action==="cast"&&{targetType:u.targetType}})),p=s.some(u=>u.action==="cast");return{targetType:n,actions:s,hasImplicitConversions:p}}function dr(e){return e.type==="abstractFloat"?c:e.type==="abstractInt"?R:e}function An(e,t){if(e.length===0)return;let r=[...new Set(e.map($e))],n=t?[...new Set(t.map($e))]:r,a=Bn(e,n,!1);if(a)return a;let o=Bn(e,n,!0);if(o)return o.hasImplicitConversions=o.actions.some(i=>i.action==="cast"),o}function Ca(e,t,r,n){if(r.action==="none")return T(t.value,n);let a=e.resolve(t.value);switch(r.action){case"ref":return T(`&${a}`,n);case"deref":return T(`*${a}`,n);case"cast":return T(`${e.resolve(n)}(${a})`,n);default:ht(r.action,"applyActionToSnippet")}}function z(e,t,r){let n=t.map(o=>o.dataType);if(n.some(o=>o===V))return;let a=An(n,r);if(a)return a.hasImplicitConversions&&console.warn(`Implicit conversions from [
2
- ${t.map(o=>` ${o.value}: ${o.dataType.type}`).join(`,
3
- `)}
4
- ] to ${a.targetType.type} are supported, but not recommended.
5
- Consider using explicit conversions instead.`),t.map((o,i)=>{let s=a.actions[i];return ce(s,"Action should not be undefined"),Ca(e,o,s,a.targetType)})}function fr(e,t,r){return Object.keys(t.propTypes).map(a=>{let o=r[a];if(!o)throw new Error(`Missing property ${a}`);let i=t.propTypes[a];return z(e,[o],[i])?.[0]??o})}function he(e){if(bn(e))return e;if(dn(e))return T(e,e[w]);if(mt(e)||gn(e))return T(e,Pa[e.kind]);if(Array.isArray(e)){let t=e.map(he).filter(Boolean),r=re();if(!r)throw new Error("Tried to coerce array without a context");let n=z(r,t),a=An(t.map(o=>o.dataType))?.targetType;return!n||!a?T(e,V):T(n.map(o=>o.value).join(", "),ct(dr(a),e.length))}return typeof e=="string"||typeof e=="function"||typeof e=="object"||typeof e=="symbol"||typeof e>"u"||e===null?T(e,V):typeof e=="number"||typeof e=="bigint"?T(e,lr(String(e))?.dataType??V):typeof e=="boolean"?T(e,E):T(e,V)}var H={get(e,t){if(t in e)return Reflect.get(e,t);if(t!==L)return t==="toString"||t===Symbol.toStringTag||t===Symbol.toPrimitive?()=>e.toString():new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>`.value(...).${String(t)}:${d(e)??"<unnamed>"}`,[w]:Qe(e[w],String(t))},H)}};function Ke(e,t){let r=t,n;for(;n=Un(r);)r=n(e);return r}function Cn(e,t){return new cr(e,t)}var cr=class{constructor(t,r){this.dataType=t;this._value=r;this[l]={dataType:t}}[l];$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.resolveValue(this._value,this.dataType),a=t.resolve(this.dataType);return t.addDeclaration(`const ${r}: ${a} = ${n};`),r}toString(){return`const:${d(this)??"<unnamed>"}`}[U](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${d(this)??"<unnamed>"}`,[w]:this.dataType},H)}get value(){return J()?this[U]():this._value}get $(){return this.value}};function Ge(e){return e?.resourceType==="slot"}function Ve(e){return e?.resourceType==="derived"}function He(e){return e?.[L]!==void 0}function Ee(e){return e?.resourceType==="accessor"}function gr(e){return typeof e?.["~resolve"]=="function"}function wt(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||gr(e)||ne(e)||Ge(e)||Ve(e)||He(e)}function Ye(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function Rn(e){return e?.resourceType==="buffer-usage"}function yr(e){return!!e?.[l]}function be(e,t){for(let[r,n]of Object.entries(t))e[r]=n,te(n)&&d(n)===void 0&&n.$name(r)}function $n(e,t,r){let n=[...e.matchAll(/:\s*(?<arg>.*?)\s*[,)]/g)].map(a=>a?a[1]:void 0);r(Object.fromEntries(t.flatMap((a,o)=>{let i=n?n[o]:void 0;return B(a)&&i!==void 0?[[i,a]]:[]})))}function St(e,t,r){let n=e.match(/->\s(?<output>[\w\d_]+)\s{/),a=n?n[1]?.trim():void 0;B(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function Ra(e){return new RegExp(`(?<![\\w\\$_.])${e.replaceAll(".","\\.").replaceAll("$","\\$")}(?![\\w\\$_])`,"g")}function we(e,t,r){return Object.entries(t).reduce((n,[a,o])=>wt(o)||Ue(o)?n.replaceAll(Ra(a),e.resolve(o)):o!==null&&typeof o=="object"?([...r.matchAll(new RegExp(`${a.replaceAll(".","\\.").replaceAll("$","\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`,"g"))].map(s=>s[1])??[]).reduce((s,p)=>p&&p in o?we(e,{[`${a}.${p}`]:o[p]},s):s,n):n,r)}function Gn(e){return new Tr(e)}var Tr=class{constructor(t){this.declaration=t}externalsToApply=[];$uses(t){return this.externalsToApply.push(t),this}"~resolve"(t){let r={};for(let a of this.externalsToApply)be(r,a);let n=we(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};import{FuncParameterType as Ln}from"tinyest";function _n(e){let{strippedCode:t,argRange:r}=$a(e),n=new vt(t);n.consume("(");let a=[];for(;!n.isAt(")");){let i=[];for(;n.isAt("@");)n.parseUntil(Vn,En),n.consume(")"),i.push(n.lastParsed);n.parseUntil(Va);let s=n.lastParsed,p;n.isAt(":")&&(n.consume(":"),n.parseUntil(Ea,ka),p=n.lastParsed),a.push({identifier:s,attributes:i,type:p}),n.isAt(",")&&n.consume(",")}n.consume(")");let o;if(n.isAt("->")){n.consume("->");let i=[];for(;n.isAt("@");)n.parseUntil(Vn,En),n.consume(")"),i.push(n.lastParsed);o={type:n.str.slice(n.pos),attributes:i}}return{args:a,ret:o,range:{begin:r[0],end:r[1]}}}function $a(e){let t=new vt(e),r="",n;for(;!t.isFinished();){if(t.isAt(Ga)){t.advanceBy(1);continue}if(t.isAt("//")){t.consume("//"),t.parseUntil(kn),t.advanceBy(1);continue}if(t.isAt("/*")){t.parseUntil(_a,La),t.consume("*/");continue}if(t.isAt("{"))return{strippedCode:r,argRange:[n,t.pos]};t.isAt("(")&&n===void 0&&(n=t.pos),n!==void 0&&(r+=t.str[t.pos]),t.advanceBy(1)}throw new Error("Invalid wgsl code!")}var vt=class{constructor(t){this.str=t;this.#e=0}#t;#e;get pos(){return this.#e}get lastParsed(){if(this.#t===void 0)throw new Error("Parse was not called yet!");return this.str.slice(this.#t,this.pos)}isFinished(){return this.#e>=this.str.length}isAt(t){if(typeof t=="string"){for(let r=0;r<t.length;r++)if(this.str[this.#e+r]!==t[r])return!1;return!0}for(let r of t)if(this.isAt(r))return!0;return!1}parseUntil(t,r){this.#t=this.#e;let n=0;for(;this.#e<this.str.length;){if(r&&this.isAt(r[0])&&(n+=1),r&&this.isAt(r[1])&&(n-=1),n===0&&this.isAt(t))return this.#e;this.#e+=1}throw new Error("Reached the end of the string without finding a match!")}advanceBy(t){this.#e+=t}consume(t){if(!this.isAt(t))throw new Error(`Expected '${t}' at position ${this.#e}, but found '${this.str.slice(this.#e,this.#e+t.length)}'`);this.advanceBy(t.length)}},kn=new Set([`
6
- `,"\v","\f","\r","\x85","\u2028","\u2029"]),Ga=new Set([...kn," "," ","\u200E","\u200F"]),Vn=new Set([")"]),Va=new Set([":",",",")"]),Ea=new Set([",",")"]),_a=new Set(["*/"]),En=["(",")"],ka=["<",">"],La=["/*","*/"];function ie(e,t=""){let r=[],n={applyExternals(o){r.push(o)},resolve(o,i,s){let p={};for(let f of r)be(p,f);let u=o.names.makeUnique(d(this));if(typeof e=="string"){let f=we(o,p,e),m="",g="";if(t!==""){let y=B(i[0])?`(in: ${o.resolve(i[0])})`:"()",x=ne(s)?Re(s):"",b=s!==ye?B(s)?`-> ${o.resolve(s)}`:`-> ${x!==""?x:"@location(0)"} ${o.resolve(s)}`:"";m=`${y} ${b} `,g=f}else{let y=_n(f);if(y.args.length!==i.length)throw new Error(`WGSL implementation has ${y.args.length} arguments, while the shell has ${i.length} arguments.`);let x=y.args.map((I,P)=>`${I.identifier}: ${On(o,`parameter ${I.identifier}`,I.type,i[P])}`).join(", "),b=s===ye?"":`-> ${On(o,"return type",y.ret?.type,s)}`;m=`(${x}) ${b}`,g=f.slice(y.range.end)}o.addDeclaration(`${t}fn ${u}${m}${g}`)}else{let f=un(e);if(f?.externals){let b=Object.fromEntries(Object.entries(f.externals).filter(([I])=>!(I in p)));be(p,b)}let m=f?.ast;if(!m)throw new Error("Missing metadata for tgpu.fn function body (either missing 'kernel' directive, or misconfigured `unplugin-typegpu`)");let g=m.externalNames.filter(b=>!(b in p));if(g.length>0)throw new Zt(d(this),g);let{head:y,body:x}=o.fnToWgsl({args:i.map((b,I)=>T(m.params[I]?.type===Ln.identifier?m.params[I].name:`_arg_${I}`,b)),argAliases:Object.fromEntries(m.params.flatMap((b,I)=>b.type===Ln.destructuredObject?b.props.map(({name:P,alias:Ua})=>[Ua,T(`_arg_${I}.${P}`,i[I].propTypes[P])]):[])),returnType:s,body:m.body,externalMap:p});o.addDeclaration(`${t}fn ${u}${o.resolve(y)}${o.resolve(x)}`)}return u}},a=d(e);return a!==void 0&&h(n,a),n}function On(e,t,r,n){let a=e.resolve(n).replace(/\s/g,"");if(!r)return a;let o=r.replace(/\s/g,"");if(o!==a)throw new Error(`Type mismatch between TGPU shell and WGSL code string: ${t}, JS type "${a}", WGSL type "${o}".`);return r}function Oa(e,t={}){let r=0,n=new Set;return Object.fromEntries(Object.entries(e??{}).map(([a,o])=>{let i=W(o);if(i!==void 0){if(n.has(i))throw new Error("Duplicate custom location attributes found");n.add(i)}return[a,o]}).map(([a,o])=>{if(Ce(o))return[a,o];if(W(o)!==void 0)return[a,o];if(t[a])return[a,xt(t[a],o)];for(;n.has(r);)r++;return[a,xt(r++,o)]}))}function se(e,t={}){return M(e)?ft(e)||W(e)!==void 0?e:xt(0,e):In(Oa(e,t))}function ue(e,...t){return Wa(e)?Ma(e,...t):e}function Wa(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)&&e.raw.every(t=>typeof t=="string")}function Ma(e,...t){return e.slice(1).reduce((r,n,a)=>`${r}${t[a]}${n}`,e[0])}function Wn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[se(e.in)]:[],returnType:ye,workgroupSize:[e.workgroupSize[0]??1,e.workgroupSize[1]??1,e.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>Na(t,e.workgroupSize,ue(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Na(e,t,r){let n=ie(r,`@compute @workgroup_size(${t.join(", ")}) `),a=e.argTypes[0];return{shell:e,$uses(i){return n.applyExternals(i),this},[l]:!0,[S]:n,$name(i){return h(n,i),te(a)&&a.$name(`${i}_Input`),this},"~resolve"(i){return n.resolve(i,e.argTypes,e.returnType)},toString(){return`computeFn:${d(n)??"<unnamed>"}`}}}function xr(e,t){let r={[l]:!0,argTypes:e,returnType:t??ye,isEntry:!1};return Object.assign((a,...o)=>ja(r,ue(a,...o)),r)}function hr(e){return!!e?.[l]&&e?.resourceType==="function"}function za([e,t]){return`${d(e)??"<unnamed>"}=${t}`}function ja(e,t){let r=ie(t,""),n={[l]:{implementation:t,argTypes:e.argTypes},shell:e,resourceType:"function",$uses(i){return r.applyExternals(i),this},[S]:r,$name(i){return h(r,i),this},with(i,s){return Mn(o,[[Ee(i)?i.slot:i,s]])},"~resolve"(i){if(typeof t=="string")return $n(t,e.argTypes,r.applyExternals),St(t,e.returnType,r.applyExternals),r.resolve(i,e.argTypes,e.returnType);let s=i;if(s.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return s.callStack.push(e.returnType),r.resolve(i,e.argTypes,e.returnType)}finally{s.callStack.pop()}}},a=nr((...i)=>{if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");let s=i.map((p,u)=>Dn(e.argTypes[u],p));return t(...s)},(...i)=>T(new Dt(o,i.map(s=>s.value)),e.returnType??V),"tgpuFnCall",e.argTypes);a[l].implementation=t;let o=Object.assign(a,n);return Object.defineProperty(o,"toString",{value(){return`fn:${d(r)??"<unnamed>"}`}}),o}function Mn(e,t){let r={[l]:{implementation:e[l].implementation,argTypes:e[l].argTypes},resourceType:"function",shell:e.shell,[L]:{inner:e,pairs:t},$uses(o){return e.$uses(o),this},[S]:e,$name(o){return e.$name(o),this},with(o,i){return Mn(a,[...t,[Ee(o)?o.slot:o,i]])}},n=nr((...o)=>e(...o),(...o)=>T(new Dt(a,o.map(i=>i.value)),e.shell.returnType??V),"tgpuFnCall",e.shell.argTypes),a=Object.assign(n,r);return Object.defineProperty(a,"toString",{value(){return`fn:${d(e)??"<unnamed>"}[${t.map(za).join(", ")}]`}}),a[l].implementation=e[l].implementation,a}var Dt=class{constructor(t,r){this._fn=t;this._params=r;this[S]=t}[S];"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){return`call:${d(this)??"<unnamed>"}`}};function Nn(e){let t={in:e.in,out:e.out,returnType:se(e.out),isEntry:!0},r=(n,...a)=>qa(t,ue(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function qa(e,t){let r=ie(t,"@fragment "),n=e.returnType;return typeof t=="string"&&St(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,$uses(o){return r.applyExternals(o),this},[l]:!0,[S]:r,$name(o){return h(r,o),te(n)&&n.$name(`${o}_Output`),this},"~resolve"(o){let i=e.in?se(e.in,o.varyingLocations).$name(`${d(this)??""}_Input`):void 0;if(i&&r.applyExternals({In:i}),r.applyExternals({Out:n}),typeof t=="string")return r.resolve(o,i?[i]:[],e.returnType);let s=o;if(s.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return s.callStack.push(n),r.resolve(o,i?[i]:[],e.returnType)}finally{s.callStack.pop()}},toString(){return`fragmentFn:${d(r)??"<unnamed>"}`}}}function zn(e){if(Object.keys(e.out).length===0)throw new Error("A vertexFn output cannot be empty since it must include the 'position' builtin.");let t={in:e.in,out:e.out,argTypes:e.in&&Object.keys(e.in).length!==0?[se(e.in)]:[],isEntry:!0},r=(n,...a)=>Qa(t,ue(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Qa(e,t){let r=ie(t,"@vertex "),n=e.argTypes[0];return{shell:e,$uses(o){return r.applyExternals(o),this},[l]:!0,[S]:r,$name(o){return h(r,o),te(n)&&n.$name(`${o}_Input`),this},"~resolve"(o){let i=se(e.out,o.varyingLocations).$name(`${d(this)??""}_Output`);if(typeof t=="string")return n&&r.applyExternals({In:n}),r.applyExternals({Out:i}),r.resolve(o,e.argTypes,i);let s=o;if(s.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return s.callStack.push(i),r.resolve(o,e.argTypes,i)}finally{s.callStack.pop()}},toString(){return`vertexFn:${d(r)??"<unnamed>"}`}}}var pe=class{lastUniqueId=0;makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},le=class{_usedNames=new Set;makeUnique(t){if(t===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=t;for(;this._usedNames.has(n);)r++,n=`${t}_${r}`;return this._usedNames.add(n),n}};function Je(e){return typeof e?.format=="string"}function jn(e,t){let r=[];if(M(e)){if(!Je(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:W(e)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[i,s]of Object.entries(e)){if(Ce(s))continue;let p=t[i];if(!p)throw new Error(`An attribute by the name of '${i}' was not provided to the shader.`);let u=p._layout,f=a.get(u);f||(r.push(u),f=[],n.push({arrayStride:u.stride,stepMode:u.stepMode,attributes:f}),a.set(u,f)),o=W(s)??o,f.push({format:p.format,offset:p.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"];function Ha(e){return Ka.includes(e.type)}function br(e,[t,r]){return` ${Re(r)}${t}: ${e.resolve(r)},
7
- `}function Ya(e,t){let r=e.names.makeUnique(d(t));return e.addDeclaration(`
8
- struct ${r} {
9
- ${Object.entries(t.propTypes).map(n=>br(e,n)).join("")}}
10
- `),r}function Ja(e,t){let r=e.names.makeUnique(d(t));return e.addDeclaration(`
11
- struct ${r} {
12
- ${Object.entries(t.propTypes).map(n=>Je(n[1])?br(e,[n[0],qe[n[1].format]]):br(e,n)).join("")}
13
- }
14
- `),r}function Xa(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Za(e,t){let r=e.resolve(Je(t.elementType)?qe[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function wr(e,t){if(Ue(t))return t.type==="unstruct"?Ja(e,t):t.type==="disarray"?Za(e,t):t.type==="loose-decorated"?e.resolve(Je(t.inner)?qe[t.inner.format]:t.inner):e.resolve(qe[t.type]);if(Ha(t))return t.type;if(t.type==="struct")return Ya(e,t);if(t.type==="array")return Xa(e,t);if(t.type==="atomic")return`atomic<${wr(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner)}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner)}>`;if(t.type==="abstractInt"||t.type==="abstractFloat"||t.type==="void"||t.type==="u16")throw new Error(`${t.type} has no representation in WGSL`);ht(t,"resolveData")}import{BufferReader as Pr,BufferWriter as Br,getSystemEndianness as ao}from"typed-binary";import{Measurer as to}from"typed-binary";function eo(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 A=eo;var qn=new WeakMap;function It(e){let t=qn.get(e);if(t)return t;let r=new to,n={},a;for(let o in e.propTypes){let i=e.propTypes[o];if(i===void 0)throw new Error(`Property ${o} is undefined in struct`);let s=r.size;A(r,Q(e)?K(i):$(i)),a&&(a.padding=r.size-s);let p=v(i);n[o]={offset:r.size,size:p},a=n[o],r.add(p)}return a&&(a.padding=O(v(e),$(e))-r.size),qn.set(e,n),n}var Ft=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),Sr=new WeakMap,vr={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",vec2h:"f32",vec3h:"f32",vec4h:"f32",mat2x2f:"f32",mat3x3f:"f32",mat4x4f:"f32"},Dr={u32:"setUint32",i32:"setInt32",f32:"setFloat32",u16:"setUint16"};function Ut(e,t,r){if(xn(e)||dt(e))return Ut(e.inner,t,r);if(B(e)||Q(e)){let a=It(e),o=Object.entries(a).sort((s,p)=>s[1].offset-p[1].offset),i="";for(let[s,p]of o){let u=e.propTypes[s];u&&(i+=Ut(u,`(${t} + ${p.offset})`,`${r}.${s}`))}return i}if(q(e)||Fe(e)){let a=e,o=O(v(a.elementType),$(a.elementType)),i="";return i+=`for (let i = 0; i < ${a.elementCount}; i++) {
15
- `,i+=Ut(a.elementType,`(${t} + i * ${o})`,`${r}[i]`),i+=`}
16
- `,i}if(X(e)){let a=vr[e.type],o="",i=Dr[a],s=["x","y","z","w"],p=fn(e)?2:cn(e)?3:4;for(let u=0;u<p;u++)o+=`output.${i}((${t} + ${u*4}), ${r}.${s[u]}, littleEndian);
17
- `;return o}if(Te(e)){let a=vr[e.type],o=Dr[a],i=yn(e)?2:Tn(e)?3:4,s=i*i,p=O(i*4,8),u="";for(let f=0;f<s;f++){let m=Math.floor(f/i),g=f%i,y=m*p+g*4;u+=`output.${o}((${t} + ${y}), ${r}.columns[${m}].${["x","y","z","w"][g]}, littleEndian);
18
- `}return u}let n=vr[e.type];return`output.${Dr[n]}(${t}, ${r}, littleEndian);
19
- `}function Pt(e){if(Sr.has(e))return Sr.get(e);let t=Ut(e,"offset","value"),r=new Function("output","offset","value","littleEndian=true",t);return Sr.set(e,r),r}var _e={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);A(e,n);for(let[a,o]of Object.entries(t.propTypes))A(e,$(o)),me(e,o,r[a]);A(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=$(t);A(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)A(e,n),me(e,t.elementType,r[o]);e.seekTo(a+v(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){_e[t.inner.type]?.(e,t,r)},decorated(e,t,r){let n=K(t);A(e,n);let a=e.currentByteOffset;_e[t.inner?.type]?.(e,t.inner,r),e.seekTo(a+v(t))},uint8(e,t,r){e.writeUint8(r)},uint8x2(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y)},uint8x4(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y),e.writeUint8(r.z),e.writeUint8(r.w)},sint8(e,t,r){e.writeInt8(r)},sint8x2(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y)},sint8x4(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y),e.writeInt8(r.z),e.writeInt8(r.w)},unorm8(e,t,r){e.writeUint8(r*255)},unorm8x2(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255)},unorm8x4(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255),e.writeUint8(r.z*255),e.writeUint8(r.w*255)},snorm8(e,t,r){e.writeUint8(r*127+128)},snorm8x2(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128)},snorm8x4(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128),e.writeUint8(r.z*127+128),e.writeUint8(r.w*127+128)},uint16(e,t,r){e.writeUint16(r)},uint16x2(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y)},uint16x4(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y),e.writeUint16(r.z),e.writeUint16(r.w)},sint16(e,t,r){e.writeInt16(r)},sint16x2(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y)},sint16x4(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y),e.writeInt16(r.z),e.writeInt16(r.w)},unorm16(e,t,r){e.writeUint16(r*65535)},unorm16x2(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535)},unorm16x4(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535),e.writeUint16(r.z*65535),e.writeUint16(r.w*65535)},snorm16(e,t,r){e.writeUint16(r*32767+32768)},snorm16x2(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768)},snorm16x4(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768),e.writeUint16(r.z*32767+32768),e.writeUint16(r.w*32767+32768)},float16(e,t,r){e.writeFloat16(r)},float16x2(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},float16x4(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},float32(e,t,r){e.writeFloat32(r)},float32x2(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},float32x3(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},float32x4(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},uint32(e,t,r){e.writeUint32(r)},uint32x2(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},uint32x3(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},uint32x4(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},sint32(e,t,r){e.writeInt32(r)},sint32x2(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},sint32x3(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},sint32x4(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},"unorm10-10-10-2"(e,t,r){let n=0;n|=(r.x*1023&1023)<<22,n|=(r.x*1023&1023)<<12,n|=(r.y*1023&1023)<<2,n|=r.z*3&3,e.writeUint32(n)},"unorm8x4-bgra"(e,t,r){e.writeUint8(r.z*255),e.writeUint8(r.y*255),e.writeUint8(r.x*255),e.writeUint8(r.w*255)},disarray(e,t,r){let n=$(t);A(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)A(e,n),_e[t.elementType?.type]?.(e,t.elementType,r[o]);e.seekTo(a+v(t))},unstruct(e,t,r){for(let[n,a]of Object.entries(t.propTypes))_e[a.type]?.(e,a,r[n])},"loose-decorated"(e,t,r){let n=K(t);A(e,n);let a=e.currentByteOffset,o=_e[t.inner?.type];return o?.(e,t.inner,r),e.seekTo(a+v(t)),r}};function me(e,t,r){let n=_e[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var Se={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 N(e.readFloat32(),e.readFloat32())},vec3f(e){return xe(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Ne(e.readFloat16(),e.readFloat16())},vec3h(e){return ze(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return je(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return ae(e.readInt32(),e.readInt32())},vec3i(e){return Be(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return _(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return oe(e.readUint32(),e.readUint32())},vec3u(e){return Ae(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return k(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 gt(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return yt(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return Tt(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);A(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))A(e,$(o)),n[a]=j(e,o);return A(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++){A(e,r);let o=t.elementType,i=j(e,o);n.push(i)}return A(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return j(e,t.inner)},decorated(e,t){let r=K(t);A(e,r);let n=e.currentByteOffset,a=j(e,t.inner);return e.seekTo(n+v(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>oe(e.readUint8(),e.readUint8()),uint8x4:e=>k(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>ae(e.readInt8(),e.readInt8()),sint8x4:e=>_(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>N(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>F(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>(e.readUint8()-128)/127,snorm8x2:e=>N((e.readUint8()-128)/127,(e.readUint8()-128)/127),snorm8x4:e=>F((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>oe(e.readUint16(),e.readUint16()),uint16x4:e=>k(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>ae(e.readInt16(),e.readInt16()),sint16x4:e=>_(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>N(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>F(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>N(Se.snorm16(e),Se.snorm16(e)),snorm16x4:e=>F(Se.snorm16(e),Se.snorm16(e),Se.snorm16(e),Se.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>N(e.readFloat16(),e.readFloat16()),float16x4:e=>F(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>N(e.readFloat32(),e.readFloat32()),float32x3:e=>xe(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>oe(e.readUint32(),e.readUint32()),uint32x3:e=>Ae(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>k(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>ae(e.readInt32(),e.readInt32()),sint32x3:e=>Be(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>_(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32()),"unorm10-10-10-2"(e){let t=e.readUint32(),r=(t>>22)/1023,n=(t>>12&1023)/1023,a=(t>>2&1023)/1023,o=(t&3)/3;return F(r,n,a,o)},"unorm8x4-bgra"(e){let t=e.readByte()/255,r=e.readByte()/255,n=e.readByte()/255,a=e.readByte()/255;return F(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=j(e,a);return r},disarray(e,t){let r=$(t),n=[];for(let a=0;a<t.elementCount;a++)A(e,r),n.push(j(e,t.elementType));return A(e,r),n},"loose-decorated"(e,t){A(e,K(t));let r=e.currentByteOffset,n=j(e,t.inner);return e.seekTo(r+v(t)),n}};function j(e,t){let r=Se[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as no}from"typed-binary";function Qn(e,t){let r=v(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new no(n),o=[];function i(u,f,m,g){if(f!=null){if(B(u)||Q(u)){let y=It(u);for(let[x,b]of Object.entries(y)){let I=u.propTypes[x];if(!I)continue;let P=f[x];P!==void 0&&i(I,P,m+b.offset,b.padding??g)}return}if(q(u)||Fe(u)){let y=u,x=O(v(y.elementType),$(y.elementType));if(!Array.isArray(f))throw new Error("Partial value for array must be an array");let b=f??[];b.sort((I,P)=>I.idx-P.idx);for(let{idx:I,value:P}of b)i(y.elementType,P,m+I*x,x-v(y.elementType))}else{let y=v(u);a.seekTo(m),me(a,u,f),o.push({start:m,end:m+y,padding:g})}}}if(i(e,t,0),o.length===0)return[];let s=[],p=o[0];for(let u=1;u<o.length;u++){let f=o[u];if(!f||!p)throw new Error("Internal error: missing segment");f.start===p.end+(p.padding??0)?(p.end=f.end,p.padding=f.padding):(s.push({data:new Uint8Array(n,p.start,p.end-p.start)}),p=f)}if(!p)throw new Error("Internal error: missing segment");return s.push({data:new Uint8Array(n,p.start,p.end-p.start)}),s}function ve(e){return!!e?.usableAsStorage}var Xe=class e extends Error{constructor(t){super(`Resource '${d(t)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Bt(e){return!!e.usableAsUniform}var Jn={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Ze=class{constructor(t,r){this.usage=t;this.buffer=r;this[l]={dataType:r.dataType},this[S]=r}resourceType="buffer-usage";[l];[S];$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Jn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}toString(){return`${this.usage}:${d(this)??"<unnamed>"}`}[U](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${d(this)??"<unnamed>"}`,[w]:this.buffer.dataType},H)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[U]()}get $(){return this.value}},et=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;this[l]={dataType:r},h(this,n.key)}resourceType="buffer-usage";[l];"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout),a=Jn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){return`${this.usage}:${d(this)??"<unnamed>"}`}[U](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${d(this)??"<unnamed>"}`,[w]:this.dataType},H)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[U]()}get $(){return this.value}},Kn=new WeakMap;function Ir(e){if(!ve(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=Kn.get(e);return t||(t=new Ze("mutable",e),Kn.set(e,t)),t}var Hn=new WeakMap;function Ur(e){if(!ve(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=Hn.get(e);return t||(t=new Ze("readonly",e),Hn.set(e,t)),t}var Yn=new WeakMap;function Fr(e){if(!Bt(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=Yn.get(e);return t||(t=new Ze("uniform",e),Yn.set(e,t)),t}var oo={uniform:Fr,mutable:Ir,readonly:Ur};function tt(e,t,r){return ne(t)?new At(e,t,r):new At(e,t,r,["storage","uniform"])}function de(e){return e.resourceType==="buffer"}function io(e){return!!e.usableAsVertex}var Xn=ao(),At=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;Ye(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 t=this._group.device;if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=t.createBuffer({size:v(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:d(this)??"<unnamed>"}),this.initial)){let r=new Br(this._buffer.getMappedRange());me(r,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(t){return h(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(){if(Ft)Pt(this.dataType);else throw new Error("This environment does not allow eval")}write(t){let r=this.buffer,n=this._group.device;if(r.mapState==="mapped"){let o=r.getMappedRange();if(Ft){Pt(this.dataType)(new DataView(o),0,t,Xn==="little");return}me(new Br(o),this.dataType,t);return}let a=v(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(a)),this._group.flush(),Ft?Pt(this.dataType)(new DataView(this._hostBuffer),0,t,Xn==="little"):me(new Br(this._hostBuffer),this.dataType,t),n.queue.writeBuffer(r,0,this._hostBuffer,0,a)}writePartial(t){let r=this.buffer,n=this._group.device,a=Qn(this.dataType,t);if(r.mapState==="mapped"){let o=r.getMappedRange(),i=new Uint8Array(o);for(let s of a)i.set(s.data,s.data.byteOffset)}else for(let o of a)n.queue.writeBuffer(r,o.data.byteOffset,o.data,0,o.data.byteLength)}copyFrom(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=v(this.dataType);this._group.commandEncoder.copyBufferToBuffer(t.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let t=this.buffer,r=this._group.device;if(t.mapState==="mapped"){let i=t.getMappedRange();return j(new Pr(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),s=j(new Pr(i),this.dataType);return t.unmap(),s}let n=r.createBuffer({size:v(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,v(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,v(this.dataType));let o=j(new Pr(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){return oo[t]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${d(this)??"<unnamed>"}`}};function Zn(e){return new Ar(e)}function ea(e){return new Cr(e)}function rt(e){let t=e;return t?.resourceType==="sampler"&&!!t[l]}function nt(e){let t=e;return t?.resourceType==="sampler-comparison"&&!!t[l]}var Ct=class{constructor(t){this._membership=t;this[w]=this,this[l]={},h(this,t.key)}[w];[l];resourceType="sampler";"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Rt=class{constructor(t){this._membership=t;this[w]=this,this[l]={},h(this,t.key)}[w];[l];resourceType="sampler-comparison";"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Ar=class{constructor(t){this._props=t;this[w]=this,this[l]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:d(this)??"<unnamed>"})),this._sampler)},this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}[w];[l];resourceType="sampler";_filtering;_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),{group:n,binding:a}=t.allocateFixedEntry({sampler:this._filtering?"filtering":"non-filtering"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Cr=class{constructor(t){this._props=t;this[w]=this,this[l]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:d(this)??"<unnamed>"})),this._sampler)}}[w];[l];resourceType="sampler-comparison";_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),{group:n,binding:a}=t.allocateFixedEntry({sampler:"comparison"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}};var $t=class{constructor(t){this._membership=t;h(this,t.key)}resourceType="external-texture";"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}};var ta={r8unorm:c,r8snorm:c,r8uint:C,r8sint:R,r16uint:C,r16sint:R,r16float:c,rg8unorm:c,rg8snorm:c,rg8uint:C,rg8sint:R,r32uint:C,r32sint:R,r32float:c,rg16uint:C,rg16sint:R,rg16float:c,rgba8unorm:c,"rgba8unorm-srgb":c,rgba8snorm:c,rgba8uint:C,rgba8sint:R,bgra8unorm:c,"bgra8unorm-srgb":c,rgb9e5ufloat:c,rgb10a2uint:C,rgb10a2unorm:c,rg11b10ufloat:c,rg32uint:C,rg32sint:R,rg32float:c,rgba16uint:C,rgba16sint:R,rgba16float:c,rgba32uint:C,rgba32sint:R,rgba32float:c,stencil8:c,depth16unorm:c,depth24plus:c,"depth24plus-stencil8":c,depth32float:c,"depth32float-stencil8":c,"bc1-rgba-unorm":c,"bc1-rgba-unorm-srgb":c,"bc2-rgba-unorm":c,"bc2-rgba-unorm-srgb":c,"bc3-rgba-unorm":c,"bc3-rgba-unorm-srgb":c,"bc4-r-unorm":c,"bc4-r-snorm":c,"bc5-rg-unorm":c,"bc5-rg-snorm":c,"bc6h-rgb-ufloat":c,"bc6h-rgb-float":c,"bc7-rgba-unorm":c,"bc7-rgba-unorm-srgb":c,"etc2-rgb8unorm":c,"etc2-rgb8unorm-srgb":c,"etc2-rgb8a1unorm":c,"etc2-rgb8a1unorm-srgb":c,"etc2-rgba8unorm":c,"etc2-rgba8unorm-srgb":c,"eac-r11unorm":c,"eac-r11snorm":c,"eac-rg11unorm":c,"eac-rg11snorm":c,"astc-4x4-unorm":c,"astc-4x4-unorm-srgb":c,"astc-5x4-unorm":c,"astc-5x4-unorm-srgb":c,"astc-5x5-unorm":c,"astc-5x5-unorm-srgb":c,"astc-6x5-unorm":c,"astc-6x5-unorm-srgb":c,"astc-6x6-unorm":c,"astc-6x6-unorm-srgb":c,"astc-8x5-unorm":c,"astc-8x5-unorm-srgb":c,"astc-8x6-unorm":c,"astc-8x6-unorm-srgb":c,"astc-8x8-unorm":c,"astc-8x8-unorm-srgb":c,"astc-10x5-unorm":c,"astc-10x5-unorm-srgb":c,"astc-10x6-unorm":c,"astc-10x6-unorm-srgb":c,"astc-10x8-unorm":c,"astc-10x8-unorm-srgb":c,"astc-10x10-unorm":c,"astc-10x10-unorm-srgb":c,"astc-12x10-unorm":c,"astc-12x10-unorm-srgb":c,"astc-12x12-unorm":c,"astc-12x12-unorm-srgb":c,r16snorm:c,r16unorm:c,rg16unorm:c,rg16snorm:c,rgba16unorm:c,rgba16snorm:c},at={rgba8unorm:F,rgba8snorm:F,rgba8uint:k,rgba8sint:_,rgba16uint:k,rgba16sint:_,rgba16float:F,r32uint:k,r32sint:_,r32float:F,rg32uint:k,rg32sint:_,rg32float:F,rgba32uint:k,rgba32sint:_,rgba32float:F,bgra8unorm:F},ra={f32:"float",u32:"uint",i32:"sint"},na={float:c,"unfilterable-float":c,uint:C,sint:R,depth:c};function aa(e,t){return new Rr(e,t)}function Z(e){return e?.resourceType==="texture"&&!!e[l]}function ot(e){return e?.resourceType==="texture-storage-view"&&!!e[l]}function it(e){return e?.resourceType==="texture-sampled-view"&&!!e[l]}var oa={mutable:"read_write",readonly:"read",writeonly:"write"},Rr=class{constructor(t,r){this.props=t;this._branch=r;this[l]={unwrap:()=>{if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:d(this)??"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:this.props.dimension??"2d",viewFormats:this.props.viewFormats??[],mipLevelCount:this.props.mipLevelCount??1,sampleCount:this.props.sampleCount??1})),this._texture}}}[l];resourceType="texture";usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;_destroyed=!1;_flags=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;_texture=null;$name(t){return h(this,t),this}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||=r,this.usableAsSampled||=n,this.usableAsRender||=a,this}createView(t,r){if(t==="sampled")return this._asSampled(r);let n=r;switch(t){case"mutable":return this._asMutable(n);case"readonly":return this._asReadonly(n);case"writeonly":return this._asWriteonly(n)}}_asStorage(t,r){if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=t?.format??this.props.format,a=at[n];return ce(!!a,`Unsupported storage texture format: ${n}`),new $r(t??{},r,this)}_asReadonly(t){return this._asStorage(t,"readonly")}_asWriteonly(t){return this._asStorage(t,"writeonly")}_asMutable(t){return this._asStorage(t,"mutable")}_asSampled(t){if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=t?.format??this.props.format;if(!at[r])throw new Error(`Unsupported storage texture format: ${r}`);return new Gr(t,this)}destroy(){this._destroyed||(this._destroyed=!0,this._texture?.destroy())}},Et={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},$r=class{constructor(t,r,n){this.access=r;this._texture=n;this[w]=this,this[l]={unwrap:()=>(this._view||(this._view=this._texture[l].unwrap().createView({label:`${d(this)??"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view)},this[S]=n,this.dimension=t?.dimension??n.props.dimension??"2d",this._format=t?.format??n.props.format,this.texelDataType=at[this._format]}[w];[l];[S];resourceType="texture-storage-view";texelDataType;dimension;_view;_format;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Et[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${oa[this.access]}>;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Gt=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;this[w]=this,this[l]={},this.texelDataType=at[this._format],h(this,a.key)}[w];[l];resourceType="texture-storage-view";texelDataType;"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Et[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${oa[this.access]}>;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Gr=class{constructor(t,r){this._props=t;this._texture=r;this[w]=this,this[l]={unwrap:()=>(this._view||(this._view=this._texture[l].unwrap().createView({label:`${d(this)??"<unnamed>"} - View`,...this._props})),this._view)},this[S]=r,this.dimension=t?.dimension??r.props.dimension??"2d",this._format=t?.format??r.props.format,this.channelDataType=ta[this._format]}[w];[l];[S];resourceType="texture-sampled-view";channelDataType;dimension;_format;_view;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(d(this)),n=(this._texture.props.sampleCount??1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:ra[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${Et[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}},Vt=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;this[w]=this,this[l]={},h(this,a.key),this.channelDataType=na[t]}[w];[l];resourceType="texture-sampled-view";channelDataType;"~resolve"(t){let r=t.names.makeUnique(d(this)),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Et[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${d(this)??"<unnamed>"}`}};function Vr(e){return!!e?.usableAsSampled}function so(e){return!!e?.usableAsRender}var _t=class e extends Error{constructor(t){super(`Resource '${d(t)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function kt(e){return new _r(e)}function Lt(e){return!!e&&e.resourceType==="bind-group-layout"}function kr(e){return!!e&&e.resourceType==="bind-group"}var Er=class e extends Error{constructor(t,r){super(`Bind group '${t??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},ia=["compute"],ke=["compute","vertex","fragment"],_r=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 et("uniform",a.uniform,o)),"storage"in a){let i="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new et(a.access??"readonly",i,o)}"texture"in a&&(this.bound[n]=new Vt(a.texture,a.viewDimension??"2d",a.multisampled??!1,o)),"storageTexture"in a&&(this.bound[n]=new Gt(a.storageTexture,a.viewDimension??"2d",a.access??"writeonly",o)),"externalTexture"in a&&(this.bound[n]=new $t(o)),"sampler"in a&&(a.sampler==="comparison"?this.bound[n]=new Rt(o):this.bound[n]=new Ct(o)),"texture"in a||"storageTexture"in a||"externalTexture"in a||"sampler"in a?this.value[n]=this.bound[n]:Object.defineProperty(this.value,n,{get:()=>this.bound[n].value}),r++}}[l]=!0;_index;resourceType="bind-group-layout";bound={};value={};$=this.value;toString(){return`bindGroupLayout:${d(this)??"<unnamed>"}`}get index(){return this._index}$name(t){return h(this,t),this}$idx(t){return this._index=t,this}unwrap(t){return t.device.createBindGroupLayout({label:d(this)??"<unnamed>",entries:Object.values(this.entries).map((n,a)=>{if(n===null)return null;let o=n.visibility,i={binding:a,visibility:0};if("uniform"in n)o=o??ke,i.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?ia:ke),i.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??ke,i.sampler={type:n.sampler};else if("texture"in n)o=o??ke,i.texture={sampleType:n.texture,viewDimension:n.viewDimension??"2d",multisampled:n.multisampled??!1};else if("storageTexture"in n){let s=n.access??"writeonly";o=o??(s==="readonly"?ke:ia),i.storageTexture={format:n.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[s],viewDimension:n.viewDimension??"2d"}}else"externalTexture"in n&&(o=o??ke,i.externalTexture={});return o?.includes("compute")&&(i.visibility|=GPUShaderStage.COMPUTE),o?.includes("vertex")&&(i.visibility|=GPUShaderStage.VERTEX),o?.includes("fragment")&&(i.visibility|=GPUShaderStage.FRAGMENT),i}).filter(n=>n!==null)})}},Le=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 Er(d(t),n)}resourceType="bind-group";unwrap(t){return t.device.createBindGroup({label:d(this.layout)??"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([n,a],o)=>{if(a===null)return null;let i=this.entries[n];if(i===void 0)throw new Error(`'${n}' is a resource required to populate bind group layout '${d(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let s;if(de(i)){if(!Bt(i))throw new Xt(i);s={buffer:t.unwrap(i)}}else s={buffer:i};return{binding:o,resource:s}}if("storage"in a){let s;if(de(i)){if(!ve(i))throw new Xe(i);s={buffer:t.unwrap(i)}}else s={buffer:i};return{binding:o,resource:s}}if("texture"in a){let s;if(Z(i)){if(!Vr(i))throw new _t(i);s=t.unwrap(i.createView("sampled"))}else it(i)?s=t.unwrap(i):s=i;return{binding:o,resource:s}}if("storageTexture"in a){let s;if(Z(i)){if(!ve(i))throw new Xe(i);a.access==="readonly"?s=t.unwrap(i.createView("readonly")):a.access==="mutable"?s=t.unwrap(i.createView("mutable")):s=t.unwrap(i.createView("writeonly"))}else ot(i)?s=t.unwrap(i):s=i;return{binding:o,resource:s}}if("sampler"in a)return rt(i)||nt(i)?{binding:o,resource:t.unwrap(i)}:{binding:o,resource:i};if("externalTexture"in a)return{binding:o,resource:i};throw new Error(`Malformed bind group entry: ${i} (${JSON.stringify(i)})`)}).filter(n=>n!==null)})}};import*as uo from"tinyest";var{NodeTypeCatalog:D}=uo,po=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"],lo=["&&","||","==","!=","<","<=",">",">="];function sa(e,t,r){return r?lo.includes(t)?E:t==="="?r:e:t==="!"||t==="~"?E:e}function mo(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function ua(e,[t,r]){e.pushBlockScope();try{return`${e.indent()}{
20
- ${r.map(n=>De(e,n)).join(`
21
- `)}
22
- ${e.dedent()}}`}finally{e.popBlockScope()}}function fo(e,t,r){return e.defineVariable(t,r)}function Lr(e,t){let r=e.getById(t);if(!r)throw new Error(`Identifier ${t} not found`);return r}function G(e,t){if(typeof t=="string")return Lr(e,t);if(typeof t=="boolean")return T(t?"true":"false",E);if(t[0]===D.logicalExpr||t[0]===D.binaryExpr||t[0]===D.assignmentExpr){let[r,n,a,o]=t,i=G(e,n),s=G(e,o),p=t[0]===D.assignmentExpr?[i.dataType]:[],u=z(e,[i,s],p),[f,m]=u||[i,s],g=e.resolve(f.value),y=e.resolve(m.value),x=sa(f.dataType,a,m.dataType);return T(po.includes(a)?`(${g} ${a} ${y})`:`${g} ${a} ${y}`,x)}if(t[0]===D.postUpdate){let[r,n,a]=t,o=G(e,a),i=e.resolve(o.value);return T(`${i}${n}`,o.dataType)}if(t[0]===D.unaryExpr){let[r,n,a]=t,o=G(e,a),i=e.resolve(o.value),s=sa(o.dataType,n);return T(`${n}${i}`,s)}if(t[0]===D.memberAccess){let[r,n,a]=t,o=G(e,n);if(o.dataType.type==="unknown"){let i=o.value[a];return he(i)}return rr(o.dataType)?T(`(*${e.resolve(o.value)}).${a}`,Qe(o.dataType.inner,a)):q(o.dataType)&&a==="length"?o.dataType.elementCount===0?T(`arrayLength(&${e.resolve(o.value)})`,C):T(String(o.dataType.elementCount),Pe):Te(o.dataType)&&a==="columns"?T(o.value,o.dataType):X(o.dataType)&&mt(o.value)?he(o.value[a]):T(`${e.resolve(o.value)}.${a}`,Qe(o.dataType,a))}if(t[0]===D.indexAccess){let[r,n,a]=t,o=G(e,n),i=G(e,a),s=e.resolve(o.value),p=e.resolve(i.value);if(o.dataType.type==="unknown"){if(Array.isArray(a)&&a[0]===D.numericLiteral)return he(o.value[a[1]]);throw new Error(`Cannot index value ${s} of unknown type with index ${p}`)}return rr(o.dataType)?T(`(*${s})[${p}]`,pr(o.dataType.inner)):T(`${s}[${p}]`,M(o.dataType)?pr(o.dataType):V)}if(t[0]===D.numericLiteral){let r=lr(t[1]);if(!r)throw new Error(`Invalid numeric literal ${t[1]}`);return r}if(t[0]===D.call){let[r,n,a]=t,o=G(e,n);e.callStack.push(o.value);let s=a.map(m=>G(e,m)).map(m=>T(e.resolve(m.value),m.dataType)),p=s.map(m=>m.value);if(e.callStack.pop(),s.forEach((m,g)=>{if(m.dataType===V)throw new Error(`Tried to pass '${m.value}' of unknown type as argument #${g} to '${typeof o.value=="string"?o.value:d(o.value)??"<unnamed>"}()'`)}),typeof o.value=="string")return T(`${o.value}(${p.join(", ")})`,o.dataType);if(B(o.value)){let m=e.resolve(o.value);return T(`${m}(${p.join(", ")})`,o.value)}if(!yr(o.value))throw new Error(`Function ${String(o.value)} ${d(o.value)} has not been created using TypeGPU APIs. Did you mean to wrap the function with tgpu.fn(args, return)(...) ?`);let u=o.value[l]?.argTypes,f;try{!u||u==="keep"?f=s:u==="coerce"?f=z(e,s)??s:f=(Array.isArray(u)?u:u(...s)).map((y,x)=>[y,s[x]]).map(([y,x])=>{if(x.dataType.type==="unknown")return console.warn(`Internal error: unknown type when generating expression: ${t}`),x;let b=z(e,[x],[y])?.[0];if(!b)throw new Y(`Cannot convert argument of type '${x.dataType.type}' to '${y.type}' for function ${d(o.value)}`,[{function:o.value,callStack:e.callStack,error:`Cannot convert argument of type '${x.dataType.type}' to '${y.type}'`,toString:()=>d(o.value)}]);return b});let m=o.value(...f);return T(e.resolve(m.value),m.dataType)}catch(m){throw new Y(m,[{toString:()=>d(o.value)}])}}if(t[0]===D.objectExpr){let r=t[1],n=e.callStack[e.callStack.length-1];if(B(n)){let a=Object.keys(n.propTypes),o=Object.fromEntries(a.map(s=>{let p=r[s];if(p===void 0)throw new Error(`Missing property ${s} in object literal for struct ${n}`);return[s,G(e,p)]})),i=fr(e,n,o);return T(i.map(s=>e.resolve(s.value)).join(", "),n)}if(yr(n)){let a=n[l]?.argTypes;if(typeof a=="object"&&a!==null){let o=Object.keys(a),i={};for(let s of o){let p=r[s];if(p===void 0)throw new Error(`Missing property ${s} in object literal for function ${n}`);let u=G(e,p),f=a[s],m=z(e,[u],[f]);i[s]=m?.[0]??u}return T(i,V)}}throw new Error("Object expressions are only allowed as return values of functions or as arguments to structs.")}if(t[0]===D.arrayExpr){let[r,n]=t,a=n.map(m=>G(e,m));if(a.length===0)throw new Error("Cannot create empty array literal.");let o=z(e,a);if(!o)throw new Error("The given values cannot be automatically converted to a common type. Consider explicitly casting them.");let i=o[0]?.dataType,s=i.type==="abstractFloat"?c:i.type==="abstractInt"?R:i,u=`array<${e.resolve(s)}, ${a.length}>`,f=o.map(m=>e.resolve(m.value));return T(`${u}( ${f.join(", ")} )`,ct(s,a.length))}if(t[0]===D.stringLiteral)throw new Error("Cannot use string literals in TGSL.");if(t[0]===D.preUpdate)throw new Error("Cannot use pre-updates in TGSL.");mo(t)}function Ot(e){return typeof e!="object"||e[0]!==D.block?[D.block,[e]]:e}function De(e,t){if(typeof t=="string")return`${e.pre}${e.resolve(Lr(e,t).value)};`;if(typeof t=="boolean")return`${e.pre}${t?"true":"false"};`;if(t[0]===D.return){let r=t[1],n=r!==void 0?e.resolve(G(e,r).value):void 0;if(B(e.callStack[e.callStack.length-1])&&typeof r=="object"&&r[0]===D.objectExpr){let a=e.resolve(e.callStack[e.callStack.length-1]);return`${e.pre}return ${a}(${n});`}return n?`${e.pre}return ${n};`:`${e.pre}return;`}if(t[0]===D.if){let[r,n,a,o]=t,i=G(e,n),s=i,p=z(e,[i],[E]);p?.[0]&&([s]=p);let u=e.resolve(s.value);e.indent();let f=De(e,Ot(a));e.dedent(),e.indent();let m=o?De(e,Ot(o)):void 0;return e.dedent(),m?`${e.pre}if (${u})
23
- ${f}
24
- ${e.pre}else
25
- ${m}`:`${e.pre}if (${u})
26
- ${f}`}if(t[0]===D.let||t[0]===D.const){let[r,n,a]=t,o=a!==void 0?G(e,a):void 0;if(!o)throw new Error(`Cannot create variable '${n}' without an initial value.`);if(Ue(o.dataType))throw new Error(`Cannot create variable '${n}' with loose data type.`);fo(e,n,dr(o.dataType));let i=e.resolve(Lr(e,n).value);if(typeof a=="object"&&a[0]===D.objectExpr&&B(e.callStack[e.callStack.length-1])){let s=e.callStack[e.callStack.length-1],p=a[1],u={};for(let[g,y]of Object.entries(p)){if(!y)throw new Error(`Missing property ${g} in object literal`);u[g]=G(e,y)}let f=fr(e,s,u),m=e.resolve(s);return`${e.pre}var ${i} = ${m}(${f.map(g=>e.resolve(g.value)).join(", ")});`}return`${e.pre}var ${i} = ${e.resolve(o.value)};`}if(t[0]===D.block)return ua(e,t);if(t[0]===D.for){let[r,n,a,o,i]=t,s=n?De(e,n):void 0,p=s?s.slice(0,-1):"",u=a?G(e,a):void 0,f=u;if(u){let b=z(e,[u],[E]);b?.[0]&&([f]=b)}let m=f?e.resolve(f.value):"",g=o?De(e,o):void 0,y=g?g.slice(0,-1):"";e.indent();let x=De(e,Ot(i));return e.dedent(),`${e.pre}for (${p}; ${m}; ${y})
27
- ${x}`}if(t[0]===D.while){let[r,n,a]=t,o=G(e,n),i=o;if(o){let u=z(e,[o],[E]);u?.[0]&&([i]=u)}let s=e.resolve(i.value);e.indent();let p=De(e,Ot(a));return e.dedent(),`${e.pre}while (${s})
28
- ${p}`}return t[0]===D.continue?`${e.pre}continue;`:t[0]===D.break?`${e.pre}break;`:`${e.pre}${e.resolve(G(e,t).value)};`}function pa(e,t){return ua(e,t)}var la="#CATCHALL#",Wr=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}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){this._stack.push({type:"functionScope",args:t,argAliases:r,returnType:n,externalMap:a})}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(i=>i.value===t);if(a!==void 0)return a;if(n.argAliases[t])return n.argAliases[t];let o=n.externalMap[t];return o!=null?he(o):void 0}if(n?.type==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return T(t,a)}}}defineBlockVariable(t,r){if(r.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")return a.declarations.set(t,r),T(t,r)}throw new Error("No block scope found to define a variable in.")}},Wt=[""," "," "," "," "," "," "," "," "],Or=Wt.length-1,Mr=class{identLevel=0;get pre(){return Wt[this.identLevel]??Wt[Or].repeat(this.identLevel/Or)+Wt[this.identLevel%Or]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Nr=class{_memoizedResolves=new WeakMap;_memoizedDerived=new WeakMap;_indentController=new Mr;_itemStateStack=new Wr;_declarations=[];_varyingLocations;get varyingLocations(){return this._varyingLocations}[l]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];callStack=[];names;constructor(t){this.names=t.names}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){let r=this._itemStateStack.getSnippetById(t);return r===void 0?null:r}defineVariable(t,r){return this._itemStateStack.defineBlockVariable(t,r)}pushBlockScope(){this._itemStateStack.pushBlockScope()}popBlockScope(){this._itemStateStack.popBlockScope()}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.argAliases,t.returnType,t.externalMap);try{return{head:co(this,t.args,t.returnType),body:pa(this,t.body)}}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:la,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new Jt(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(He(t))return this.withSlots(t[L].pairs,()=>this.unwrap(t[L].inner));let r=t;for(;;)if(Ge(r))r=this.readSlot(r);else if(Ve(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(t){let r=this._memoizedDerived.get(t)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([s,p])=>s.areEqual(this._itemStateStack.readSlot(s),p)))return o.result;er(We.CPU);let n;try{n=t["~compute"]()}finally{tr(We.CPU)}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._memoizedDerived.set(t,r),n}catch(n){throw n instanceof Y?n.appendToTrace(t):new Y(n,[t])}finally{this._itemStateStack.popItem()}}_getOrInstantiate(t){let r=this._memoizedResolves.get(t)??[];this._itemStateStack.pushItem();try{for(let o of r)if([...o.slotToValueMap.entries()].every(([s,p])=>s.areEqual(this._itemStateStack.readSlot(s),p)))return o.result;let n;M(t)?n=wr(this,t):Ve(t)||Ge(t)?n=this.resolve(this.unwrap(t)):gr(t)?n=t["~resolve"](this):n=this.resolveValue(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._memoizedResolves.set(t,r),n}catch(n){throw n instanceof Y?n.appendToTrace(t):new Y(n,[t])}finally{this._itemStateStack.popItem()}}resolve(t){if(He(t))return this.withSlots(t[L].pairs,()=>this.resolve(t[L].inner));if(t&&typeof t=="object"||typeof t=="function"){if(this._itemStateStack.itemDepth===0)try{er(We.GPU);let r=pn(this,()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
1
+ import{$ as Hr,a as A,aa as U,b as Mr,ba as O,c as Wr,d as Ye,da as v,e as Je,ea as Wt,f as Q,fa as Xe,g as Nr,ga as Kr,h as R,i as L,ia as K,j as Et,ja as Zr,k as se,ka as en,na as Ze,qa as xe,ra as he,sa as tn,ta as rn}from"./chunk-S27MYQ6U.js";import{$ as _r,A as Vt,Aa as qr,B as ae,Ba as Fe,Ca as Ue,D as oe,Ea as Ot,F as $t,Fa as jr,G as _t,Ga as kt,H as Pr,Ha as Mt,I as Br,Ja as P,K as Ar,Ka as Qr,L as Rr,La as $,M as Cr,Ma as _,N as fe,O as ge,P as B,R as Gr,X as je,Y as Qe,Ya as Yr,Z as Vr,Za as Jr,_ as $r,_a as Xr,a as p,aa as Er,b,ba as He,c as D,ca as De,d as h,da as Lr,e as G,f as Ft,fa as Or,g as Ut,ga as ce,ha as Ke,i as z,ia as j,j as m,ja as kr,k as T,ka as ye,l as q,la as Te,m as Ur,ma as Lt,n as re,na as zr,o as de,p as Pt,pa as M,q as Bt,r as At,s as Rt,t as ne,ta as C,u as Ie,v as Ct,va as V,w as Gt,wa as d,y as ze,z as qe,za as H}from"./chunk-IH2QU6TV.js";function nn(t){if(typeof t?.[D]=="function")return t[D].bind(t)}var k={get(t,e){if(e in t)return Reflect.get(t,e);if(e!==G)return e==="toString"||e===Symbol.toStringTag||e===Symbol.toPrimitive?()=>t.toString():new Proxy({"~resolve":r=>`${r.resolve(t)}.${String(e)}`,toString:()=>`.value(...).${String(e)}:${m(t)??"<unnamed>"}`,[b]:Zr(t[b],String(e))},k)}};function Pe(t,e){let r=e,n;for(;n=nn(r);)r=n(t);return r}function an(t,e){return new Nt(t,e)}var Nt=class{constructor(e,r){this.dataType=e;this.#e=r}[p]={};#e;$name(e){return T(this,e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.resolveValue(this.#e,this.dataType),a=e.resolve(this.dataType);return e.addDeclaration(`const ${r}: ${a} = ${n};`),r}toString(){return`const:${m(this)??"<unnamed>"}`}[D](){return new Proxy({"~resolve":e=>e.resolve(this),toString:()=>`.value:${m(this)??"<unnamed>"}`,[b]:this.dataType},k)}get value(){return Te()?this[D]():this.#e}get $(){return this.value}};function Y(t,e){for(let[r,n]of Object.entries(e))t[r]=n,q(n)&&m(n)===void 0&&n.$name(r)}function on(t,e,r){let n=[...t.matchAll(/:\s*(?<arg>.*?)\s*[,)]/g)].map(a=>a?a[1]:void 0);r(Object.fromEntries(e.flatMap((a,o)=>{let s=n?n[o]:void 0;return B(a)&&s!==void 0?[[s,a]]:[]})))}function et(t,e,r){let n=t.match(/->\s(?<output>[\w\d_]+)\s{/),a=n?n[1]?.trim():void 0;B(e)&&a&&!/\s/g.test(a)&&r({[a]:e})}function na(t){return new RegExp(`(?<![\\w\\$_.])${t.replaceAll(".","\\.").replaceAll("$","\\$")}(?![\\w\\$_])`,"g")}function ie(t,e,r){return Object.entries(e).reduce((n,[a,o])=>He(o)||Ye(o)?n.replaceAll(na(a),t.resolve(o)):o!==null&&typeof o=="object"?([...r.matchAll(new RegExp(`${a.replaceAll(".","\\.").replaceAll("$","\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`,"g"))].map(i=>i[1])??[]).reduce((i,u)=>u&&u in o?ie(t,{[`${a}.${u}`]:o[u]},i):i,n):n,r)}function sn(t){return new zt(t)}var zt=class{constructor(e){this.declaration=e}externalsToApply=[];$uses(e){return this.externalsToApply.push(e),this}"~resolve"(e){let r={};for(let a of this.externalsToApply)Y(r,a);let n=ie(e,r,this.declaration);return e.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};import{FuncParameterType as dn}from"tinyest";function ln(t){let{strippedCode:e,argRange:r}=aa(t),n=new tt(e);n.consume("(");let a=[];for(;!n.isAt(")");){let s=[];for(;n.isAt("@");)n.parseUntil(un,pn),n.consume(")"),s.push(n.lastParsed);n.parseUntil(sa);let i=n.lastParsed,u;n.isAt(":")&&(n.consume(":"),n.parseUntil(ia,pa),u=n.lastParsed),a.push({identifier:i,attributes:s,type:u}),n.isAt(",")&&n.consume(",")}n.consume(")");let o;if(n.isAt("->")){n.consume("->");let s=[];for(;n.isAt("@");)n.parseUntil(un,pn),n.consume(")"),s.push(n.lastParsed);o={type:n.str.slice(n.pos),attributes:s}}return{args:a,ret:o,range:{begin:r[0],end:r[1]}}}function aa(t){let e=new tt(t),r="",n;for(;!e.isFinished();){if(e.isAt(oa)){e.advanceBy(1);continue}if(e.isAt("//")){e.consume("//"),e.parseUntil(mn),e.advanceBy(1);continue}if(e.isAt("/*")){e.parseUntil(ua,la),e.consume("*/");continue}if(e.isAt("{"))return{strippedCode:r,argRange:[n,e.pos]};e.isAt("(")&&n===void 0&&(n=e.pos),n!==void 0&&(r+=e.str[e.pos]),e.advanceBy(1)}throw new Error("Invalid wgsl code!")}var tt=class{constructor(e){this.str=e;this.#t=0}#e;#t;get pos(){return this.#t}get lastParsed(){if(this.#e===void 0)throw new Error("Parse was not called yet!");return this.str.slice(this.#e,this.pos)}isFinished(){return this.#t>=this.str.length}isAt(e){if(typeof e=="string"){for(let r=0;r<e.length;r++)if(this.str[this.#t+r]!==e[r])return!1;return!0}for(let r of e)if(this.isAt(r))return!0;return!1}parseUntil(e,r){this.#e=this.#t;let n=0;for(;this.#t<this.str.length;){if(r&&this.isAt(r[0])&&(n+=1),r&&this.isAt(r[1])&&(n-=1),n===0&&this.isAt(e))return this.#t;this.#t+=1}throw new Error("Reached the end of the string without finding a match!")}advanceBy(e){this.#t+=e}consume(e){if(!this.isAt(e))throw new Error(`Expected '${e}' at position ${this.#t}, but found '${this.str.slice(this.#t,this.#t+e.length)}'`);this.advanceBy(e.length)}},mn=new Set([`
2
+ `,"\v","\f","\r","\x85","\u2028","\u2029"]),oa=new Set([...mn," "," ","\u200E","\u200F"]),un=new Set([")"]),sa=new Set([":",",",")"]),ia=new Set([",",")"]),ua=new Set(["*/"]),pn=["(",")"],pa=["<",">"],la=["/*","*/"];function J(t,e=""){let r=[],n={applyExternals(o){r.push(o)},resolve(o,s,i){let u={};for(let f of r)Y(u,f);let l=o.names.makeUnique(m(this));if(typeof t=="string"){let f=ie(o,u,t),g="",c="";if(e!==""){let y=B(s[0])?`(in: ${o.resolve(s[0])})`:"()",x=fe(i)?he(i):"",I=i!==oe?B(i)?`-> ${o.resolve(i)}`:`-> ${x!==""?x:"@location(0)"} ${o.resolve(i)}`:"";g=`${y} ${I} `,c=f}else{let y=ln(f);if(y.args.length!==s.length)throw new Error(`WGSL implementation has ${y.args.length} arguments, while the shell has ${s.length} arguments.`);let x=y.args.map((w,S)=>`${w.identifier}: ${fn(o,`parameter ${w.identifier}`,w.type,s[S])}`).join(", "),I=i===oe?"":`-> ${fn(o,"return type",y.ret?.type,i)}`;g=`(${x}) ${I}`,c=f.slice(y.range.end)}o.addDeclaration(`${e}fn ${l}${g}${c}`)}else{let f=Ur(t);if(f?.externals){let w=Object.fromEntries(Object.entries(f.externals).filter(([S])=>!(S in u)));Y(u,w)}let g=f?.ast;if(!g)throw new Error("Missing metadata for tgpu.fn function body (either missing 'kernel' directive, or misconfigured `unplugin-typegpu`)");let c=g.externalNames.filter(w=>!(w in u));if(c.length>0)throw new Rt(m(this),c);let y=g.params[1];y&&y.type==="i"&&e!==""&&Y(u,{[y.name]:zr(i)});let{head:x,body:I}=o.fnToWgsl({args:s.map((w,S)=>M(g.params[S]?.type===dn.identifier?g.params[S].name:`_arg_${S}`,w)),argAliases:Object.fromEntries(g.params.flatMap((w,S)=>w.type===dn.destructuredObject?w.props.map(({name:Fr,alias:ra})=>[ra,M(`_arg_${S}.${Fr}`,s[S].propTypes[Fr])]):[])),returnType:i,body:g.body,externalMap:u});o.addDeclaration(`${e}fn ${l}${o.resolve(x)}${o.resolve(I)}`)}return l}},a=m(t);return a!==void 0&&T(n,a),n}function fn(t,e,r,n){let a=t.resolve(n).replace(/\s/g,"");if(!r)return a;let o=r.replace(/\s/g,"");if(o!==a)throw new Error(`Type mismatch between TGPU shell and WGSL code string: ${e}, JS type "${a}", WGSL type "${o}".`);return r}function ma(t,e={}){let r=0,n=new Set;return Object.fromEntries(Object.entries(t??{}).map(([a,o])=>{let s=R(o);if(s!==void 0){if(n.has(s))throw new Error("Duplicate custom location attributes found");n.add(s)}return[a,o]}).map(([a,o])=>{if(xe(o))return[a,o];if(R(o)!==void 0)return[a,o];if(e[a])return[a,Ze(e[a],o)];for(;n.has(r);)r++;return[a,Ze(r++,o)]}))}function X(t,e={}){return L(t)?Qe(t)||R(t)!==void 0?t:Ze(0,t):tn(ma(t,e))}function Z(t,...e){return da(t)?fa(t,...e):t}function da(t){return Array.isArray(t)&&"raw"in t&&Array.isArray(t.raw)&&t.raw.every(e=>typeof e=="string")}function fa(t,...e){return t.slice(1).reduce((r,n,a)=>`${r}${e[a]}${n}`,t[0])}function gn(t){let e={argTypes:t.in&&Object.keys(t.in).length!==0?[X(t.in)]:[],returnType:oe,workgroupSize:[t.workgroupSize[0]??1,t.workgroupSize[1]??1,t.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>ga(e,t.workgroupSize,Z(n,...a));return Object.assign(Object.assign(r,e),{does:r})}function ga(t,e,r){let n=J(r,`@compute @workgroup_size(${e.join(", ")}) `),a=t.argTypes[0];return{shell:t,$uses(s){return n.applyExternals(s),this},[p]:!0,[h]:n,$name(s){return T(n,s),q(a)&&a.$name(`${s}_Input`),this},"~resolve"(s){return n.resolve(s,t.argTypes,t.returnType)},toString(){return`computeFn:${m(n)??"<unnamed>"}`}}}function qt(t,e){let r={[p]:!0,argTypes:t,returnType:e??oe,isEntry:!1};return Object.assign((a,...o)=>ya(r,Z(a,...o)),r)}function jt(t){return!!t?.[p]&&t?.resourceType==="function"}function ca([t,e]){return`${m(t)??"<unnamed>"}=${e}`}function ya(t,e){let r=J(e,""),n={[p]:{implementation:e,argConversionHint:t.argTypes},shell:t,resourceType:"function",$uses(s){return r.applyExternals(s),this},[h]:r,$name(s){return T(r,s),this},with(s,i){return cn(o,[[ae(s)?s.slot:s,i]])},"~resolve"(s){return typeof e=="string"&&(on(e,t.argTypes,r.applyExternals),et(e,t.returnType,r.applyExternals)),r.resolve(s,t.argTypes,t.returnType)}},a=Lt((...s)=>Or(()=>{try{if(typeof e=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");let i=s.map((u,l)=>Xe(t.argTypes[l],u));return e(...i)}catch(i){throw i instanceof Pt?i.appendToTrace(o):new Pt(i,[o])}}),(...s)=>M(new rt(o,s.map(i=>i.value)),t.returnType??Et),"tgpuFnCall",t.argTypes);a[p].jsImpl=e;let o=Object.assign(a,n);return Object.defineProperty(o,"toString",{value(){return`fn:${m(r)??"<unnamed>"}`}}),o}function cn(t,e){let r={[p]:{implementation:t[p].implementation,argConversionHint:t[p].argConversionHint},resourceType:"function",shell:t.shell,[G]:{inner:t,pairs:e},$uses(o){return t.$uses(o),this},[h]:t,$name(o){return t.$name(o),this},with(o,s){return cn(a,[...e,[ae(o)?o.slot:o,s]])}},n=Lt((...o)=>t(...o),(...o)=>M(new rt(a,o.map(s=>s.value)),t.shell.returnType??Et),"tgpuFnCall",t.shell.argTypes),a=Object.assign(n,r);return Object.defineProperty(a,"toString",{value(){return`fn:${m(t)??"<unnamed>"}[${e.map(ca).join(", ")}]`}}),a[p].implementation=t[p].implementation,a}var rt=class{constructor(e,r){this._fn=e;this._params=r;this[h]=e}[h];"~resolve"(e){return e.resolve(`${e.resolve(this._fn)}(${this._params.map(r=>e.resolve(r)).join(", ")})`)}toString(){return`call:${m(this)??"<unnamed>"}`}};function yn(t){let e={in:t.in,out:t.out,returnType:X(t.out),isEntry:!0},r=(n,...a)=>Ta(e,Z(n,...a));return Object.assign(Object.assign(r,e),{does:r})}function Ta(t,e){let r=J(e,"@fragment "),n=t.returnType;return typeof e=="string"&&et(e,n,o=>r.applyExternals(o)),{shell:t,outputType:n,$uses(o){return r.applyExternals(o),this},[p]:!0,[h]:r,$name(o){return T(r,o),q(n)&&n.$name(`${o}_Output`),this},"~resolve"(o){let s=t.in?X(t.in,o.varyingLocations).$name(`${m(this)??""}_Input`):void 0;return s&&r.applyExternals({In:s}),r.applyExternals({Out:n}),r.resolve(o,s?[s]:[],t.returnType)},toString(){return`fragmentFn:${m(r)??"<unnamed>"}`}}}function Tn(t){if(Object.keys(t.out).length===0)throw new Error("A vertexFn output cannot be empty since it must include the 'position' builtin.");let e={in:t.in,out:t.out,argTypes:t.in&&Object.keys(t.in).length!==0?[X(t.in)]:[],isEntry:!0},r=(n,...a)=>xa(e,Z(n,...a));return Object.assign(Object.assign(r,e),{does:r})}function xa(t,e){let r=J(e,"@vertex "),n=t.argTypes[0];return{shell:t,$uses(o){return r.applyExternals(o),this},[p]:!0,[h]:r,$name(o){return T(r,o),q(n)&&n.$name(`${o}_Input`),this},"~resolve"(o){let s=X(t.out,o.varyingLocations).$name(`${m(this)??""}_Output`);return typeof e=="string"&&(n&&r.applyExternals({In:n}),r.applyExternals({Out:s})),r.resolve(o,t.argTypes,s)},toString(){return`vertexFn:${m(r)??"<unnamed>"}`}}}var ue=class{lastUniqueId=0;makeUnique(e){let r;return e?(r=e.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},W=class{_usedNames=new Set;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 Be(t){return typeof t?.format=="string"}function xn(t,e){let r=[];if(L(t)){if(!Be(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:R(t)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[s,i]of Object.entries(t)){if(xe(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 l=u._layout,f=a.get(l);f||(r.push(l),f=[],n.push({arrayStride:l.stride,stepMode:l.stepMode,attributes:f}),a.set(l,f)),o=R(i)??o,f.push({format:u.format,offset:u.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var ha=["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"];function ba(t){return ha.includes(t.type)}function Qt(t,[e,r]){return` ${he(r)}${e}: ${t.resolve(r)},
3
+ `}function wa(t,e){let r=t.names.makeUnique(m(e));return t.addDeclaration(`struct ${r} {
4
+ ${Object.entries(e.propTypes).map(n=>Qt(t,n)).join("")}}`),r}function Sa(t,e){let r=t.names.makeUnique(m(e));return t.addDeclaration(`struct ${r} {
5
+ ${Object.entries(e.propTypes).map(n=>Be(n[1])?Qt(t,[n[0],se[n[1].format]]):Qt(t,n)).join("")}
6
+ }`),r}function va(t,e){let r=t.resolve(e.elementType);return e.elementCount===0?`array<${r}>`:`array<${r}, ${e.elementCount}>`}function Ia(t,e){let r=t.resolve(Be(e.elementType)?se[e.elementType.format]:e.elementType);return e.elementCount===0?`array<${r}>`:`array<${r}, ${e.elementCount}>`}function Ht(t,e){if(Ye(e))return e.type==="unstruct"?Sa(t,e):e.type==="disarray"?Ia(t,e):e.type==="loose-decorated"?t.resolve(Be(e.inner)?se[e.inner.format]:e.inner):t.resolve(se[e.type]);if(ba(e))return e.type;if(e.type==="struct")return wa(t,e);if(e.type==="array")return va(t,e);if(e.type==="atomic")return`atomic<${Ht(t,e.inner)}>`;if(e.type==="decorated")return t.resolve(e.inner);if(e.type==="ptr")return e.addressSpace==="storage"?`ptr<storage, ${t.resolve(e.inner)}, ${e.access==="read-write"?"read_write":e.access}>`:`ptr<${e.addressSpace}, ${t.resolve(e.inner)}>`;if(e.type==="abstractInt"||e.type==="abstractFloat"||e.type==="void"||e.type==="u16")throw new Error(`${e.type} has no representation in WGSL`);K(e,"resolveData")}var be=class t{constructor(e){this.bindings=e}with(e,r){return new t([...this.bindings,[ae(e)?e.slot:e,r]])}pipe(e){let r=e(this);return new t([...this.bindings,...r.bindings])}};function*hn(t){let e=0;for(;;)t.has(e)||(yield e),e++}import{BufferReader as Jt,BufferWriter as An,getSystemEndianness as Ca}from"typed-binary";import{Measurer as Fa}from"typed-binary";function Da(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 F=Da;var bn=new WeakMap;function nt(t){let e=bn.get(t);if(e)return e;let r=new Fa,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;F(r,Q(t)?O(s):U(s)),a&&(a.padding=r.size-i);let u=v(s);n[o]={offset:r.size,size:u},a=n[o],r.add(u)}return a&&(a.padding=A(v(t),U(t))-r.size),bn.set(t,n),n}var Ua=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),Kt=new WeakMap,at={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"},Pa={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"},ot={u32:"setUint32",i32:"setInt32",f32:"setFloat32",u16:"setUint16",i16:"setInt16",f16:"setFloat16",u8:"setUint8",i8:"setInt8"},Ba={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)`},wn={"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);
7
+ `},"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);
8
+ `;return n}}};function st(t,e,r){if(Gr(t)||je(t))return st(t.inner,e,r);if(B(t)||Q(t)){let a=nt(t),o="";for(let[s,i]of Object.entries(a)){let u=t.propTypes[s];u&&(o+=st(u,`(${e} + ${i.offset})`,`${r}.${s}`))}return o}if(ge(t)||Je(t)){let a=A(v(t.elementType),U(t)),o="";return o+=`for (let i = 0; i < ${t.elementCount}; i++) {
9
+ `,o+=st(t.elementType,`(${e} + i * ${a})`,`${r}[i]`),o+=`}
10
+ `,o}if(Br(t)){let a=at[t.type],o="",s=ot[a],i=["x","y","z","w"],u=$t(t)?2:_t(t)?3:4;for(let l=0;l<u;l++)o+=`output.${s}((${e} + ${l*4}), ${r}.${i[l]}, littleEndian);
11
+ `;return o}if(Cr(t)){let a=at[t.type],o=ot[a],s=Ar(t)?2:Rr(t)?3:4,i=s*s,u=A(s*4,8),l="";for(let f=0;f<i;f++){let g=Math.floor(f/s),c=f%s,y=g*u+c*4;l+=`output.${o}((${e} + ${y}), ${r}.columns[${g}].${["x","y","z","w"][c]}, littleEndian);
12
+ `}return l}if(Hr(t)){let a=t.type;if(a in wn)return wn[a].generator(e,r);let o=Pa[a],s=ot[o],i=se[a],u=Pr(i)?4:_t(i)?3:$t(i)?2:1,l=o==="u8"||o==="i8"?1:o==="u16"||o==="i16"||o==="f16"?2:4,f=["x","y","z","w"],g=Ba[a],c="";for(let y=0;y<u;y++){let x=u===1?r:`${r}.${f[y]}`,I=g?g(x):x;c+=`output.${s}((${e} + ${y*l}), ${I}, littleEndian);
13
+ `}return c}if(!Object.hasOwn(at,t.type))throw new Error(`Primitive ${t.type} is unsupported by compiled writer`);let n=at[t.type];return`output.${ot[n]}(${e}, ${r}, littleEndian);
14
+ `}function Yt(t){if(!Ua){console.warn("This environment does not allow eval - using default writer as fallback");return}if(Kt.has(t))return Kt.get(t);try{let e=st(t,"offset","value"),r=new Function("output","offset","value","littleEndian=true",e);return Kt.set(t,r),r}catch(e){console.warn(`Failed to compile writer for schema: ${t}
15
+ Reason: ${e instanceof Error?e.message:String(e)}
16
+ Falling back to default writer`)}}var we={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=U(e);F(t,n);for(let[a,o]of Object.entries(e.propTypes))F(t,U(o)),pe(t,o,r[a]);F(t,n)},array(t,e,r){if(e.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=U(e);F(t,n);let a=t.currentByteOffset;for(let o=0;o<Math.min(e.elementCount,r.length);o++)F(t,n),pe(t,e.elementType,r[o]);t.seekTo(a+v(e))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(t,e,r){we[e.inner.type]?.(t,e,r)},decorated(t,e,r){let n=O(e);F(t,n);let a=t.currentByteOffset;we[e.inner?.type]?.(t,e.inner,r),t.seekTo(a+v(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=U(e);F(t,n);let a=t.currentByteOffset;for(let o=0;o<Math.min(e.elementCount,r.length);o++)F(t,n),we[e.elementType?.type]?.(t,e.elementType,r[o]);t.seekTo(a+v(e))},unstruct(t,e,r){let n=e.propTypes;for(let[a,o]of Object.entries(n))we[o.type]?.(t,o,r[a])},"loose-decorated"(t,e,r){let n=O(e);F(t,n);let a=t.currentByteOffset,o=we[e.inner?.type];return o?.(t,e.inner,r),t.seekTo(a+v(e)),r}};function pe(t,e,r){let n=we[e.type];if(!n)throw new Error(`Cannot write data of type '${e.type}'.`);n(t,e,r)}var Aa={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 H(t.readFloat32(),t.readFloat32())},vec3f(t){return Ot(t.readFloat32(),t.readFloat32(),t.readFloat32())},vec4f(t){return P(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32())},vec2h(t){return qr(t.readFloat16(),t.readFloat16())},vec3h(t){return jr(t.readFloat16(),t.readFloat16(),t.readFloat16())},vec4h(t){return Qr(t.readFloat16(),t.readFloat16(),t.readFloat16(),t.readFloat16())},vec2i(t){return Fe(t.readInt32(),t.readInt32())},vec3i(t){return kt(t.readInt32(),t.readInt32(),t.readInt32())},vec4i(t){return $(t.readInt32(),t.readInt32(),t.readInt32(),t.readInt32())},vec2u(t){return Ue(t.readUint32(),t.readUint32())},vec3u(t){return Mt(t.readUint32(),t.readUint32(),t.readUint32())},vec4u(t){return _(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 Yr(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32())},mat3x3f(t){let e=()=>{let r=t.readFloat32();return t.readFloat32(),r};return Jr(t.readFloat32(),t.readFloat32(),e(),t.readFloat32(),t.readFloat32(),e(),t.readFloat32(),t.readFloat32(),e())},mat4x4f(t){return Xr(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=U(e);F(t,r);let n={},a=e.propTypes;for(let[o,s]of Object.entries(a))F(t,U(s)),n[o]=E(t,s);return F(t,r),n},array(t,e){if(e.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=U(e),n=[];for(let a=0;a<e.elementCount;a++){F(t,r);let o=e.elementType,s=E(t,o);n.push(s)}return F(t,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(t,e){return E(t,e.inner)},decorated(t,e){let r=O(e);F(t,r);let n=t.currentByteOffset,a=E(t,e.inner);return t.seekTo(n+v(e)),a},uint8:t=>t.readUint8(),uint8x2:t=>Ue(t.readUint8(),t.readUint8()),uint8x4:t=>_(t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8()),sint8:t=>t.readInt8(),sint8x2:t=>Fe(t.readInt8(),t.readInt8()),sint8x4:t=>$(t.readInt8(),t.readInt8(),t.readInt8(),t.readInt8()),unorm8:t=>t.readUint8()/255,unorm8x2:t=>H(t.readUint8()/255,t.readUint8()/255),unorm8x4:t=>P(t.readUint8()/255,t.readUint8()/255,t.readUint8()/255,t.readUint8()/255),snorm8:t=>t.readInt8()/127,snorm8x2:t=>H(t.readInt8()/127,t.readInt8()/127),snorm8x4:t=>P(t.readInt8()/127,t.readInt8()/127,t.readInt8()/127,t.readInt8()/127),uint16:t=>t.readUint16(),uint16x2:t=>Ue(t.readUint16(),t.readUint16()),uint16x4:t=>_(t.readUint16(),t.readUint16(),t.readUint16(),t.readUint16()),sint16:t=>t.readInt16(),sint16x2:t=>Fe(t.readInt16(),t.readInt16()),sint16x4:t=>$(t.readInt16(),t.readInt16(),t.readInt16(),t.readInt16()),unorm16:t=>t.readUint16()/65535,unorm16x2:t=>H(t.readUint16()/65535,t.readUint16()/65535),unorm16x4:t=>P(t.readUint16()/65535,t.readUint16()/65535,t.readUint16()/65535,t.readUint16()/65535),snorm16:t=>t.readInt16()/32767,snorm16x2:t=>H(t.readInt16()/32767,t.readInt16()/32767),snorm16x4:t=>P(t.readInt16()/32767,t.readInt16()/32767,t.readInt16()/32767,t.readInt16()/32767),float16(t){return t.readFloat16()},float16x2:t=>H(t.readFloat16(),t.readFloat16()),float16x4:t=>P(t.readFloat16(),t.readFloat16(),t.readFloat16(),t.readFloat16()),float32:t=>t.readFloat32(),float32x2:t=>H(t.readFloat32(),t.readFloat32()),float32x3:t=>Ot(t.readFloat32(),t.readFloat32(),t.readFloat32()),float32x4:t=>P(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32()),uint32:t=>t.readUint32(),uint32x2:t=>Ue(t.readUint32(),t.readUint32()),uint32x3:t=>Mt(t.readUint32(),t.readUint32(),t.readUint32()),uint32x4:t=>_(t.readUint32(),t.readUint32(),t.readUint32(),t.readUint32()),sint32:t=>t.readInt32(),sint32x2:t=>Fe(t.readInt32(),t.readInt32()),sint32x3:t=>kt(t.readInt32(),t.readInt32(),t.readInt32()),sint32x4:t=>$(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 P(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 P(n,r,e,a)},unstruct(t,e){let r={},n=e.propTypes;for(let[a,o]of Object.entries(n))r[a]=E(t,o);return r},disarray(t,e){let r=U(e),n=[];for(let a=0;a<e.elementCount;a++)F(t,r),n.push(E(t,e.elementType));return F(t,r),n},"loose-decorated"(t,e){F(t,O(e));let r=t.currentByteOffset,n=E(t,e.inner);return t.seekTo(r+v(e)),n}};function E(t,e){let r=Aa[e.type];if(!r)throw new Error(`Cannot read data of type '${e.type}'.`);return r(t,e)}import{BufferWriter as Ra}from"typed-binary";function Sn(t,e){let r=v(t);if(r===0||e===void 0||e===null)return[];let n=new ArrayBuffer(r),a=new Ra(n),o=[];function s(l,f,g,c){if(f!=null){if(B(l)||Q(l)){let y=nt(l);for(let[x,I]of Object.entries(y)){let w=l.propTypes[x];if(!w)continue;let S=f[x];S!==void 0&&s(w,S,g+I.offset,I.padding??c)}return}if(ge(l)||Je(l)){let y=l,x=A(v(y.elementType),U(y.elementType));if(!Array.isArray(f))throw new Error("Partial value for array must be an array");let I=f??[];I.sort((w,S)=>w.idx-S.idx);for(let{idx:w,value:S}of I)s(y.elementType,S,g+w*x,x-v(y.elementType))}else{let y=v(l);a.seekTo(g),pe(a,l,f),o.push({start:g,end:g+y,padding:c})}}}if(s(t,e,0),o.length===0)return[];let i=[],u=o[0];for(let l=1;l<o.length;l++){let f=o[l];if(!f||!u)throw new Error("Internal error: missing segment");f.start===u.end+(u.padding??0)?(u.end=f.end,u.padding=f.padding):(i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),u=f)}if(!u)throw new Error("Internal error: missing segment");return i.push({data:new Uint8Array(n,u.start,u.end-u.start)}),i}function le(t){return!!t?.usableAsStorage}var Ae=class t extends Error{constructor(e){super(`Resource '${m(e)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,t.prototype)}};function it(t){return!!t.usableAsUniform}var Fn={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Re=class{constructor(e,r){this.usage=e;this.buffer=r;this[p]={dataType:r.dataType},this[h]=r}resourceType="buffer-usage";[p];[h];$name(e){return this.buffer.$name(e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),{group:n,binding:a}=e.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Fn[this.usage];return e.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${e.resolve(this.buffer.dataType)};`),r}toString(){return`${this.usage}:${m(this)??"<unnamed>"}`}[D](){return new Proxy({"~resolve":e=>e.resolve(this),toString:()=>`.value:${m(this)??"<unnamed>"}`,[b]:this.buffer.dataType},k)}get $(){let e=ye(),r=ce();if(e.type==="normal")throw new Gt(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[D]():e.type==="simulate"?(e.buffers.has(this.buffer)||e.buffers.set(this.buffer,Xe(this.buffer.dataType,this.buffer.initial)??Kr(this.buffer.dataType)),e.buffers.get(this.buffer)):K(e,"bufferUsage.ts#TgpuFixedBufferImpl/$")}get value(){return this.$}set $(e){let r=ye(),n=ce();if(r.type==="normal")throw new Gt(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}K(r,"bufferUsage.ts#TgpuFixedBufferImpl/$")}set value(e){this.$=e}},Ce=class{constructor(e,r,n){this.usage=e;this.dataType=r;this._membership=n;this[p]={dataType:r},T(this,n.key)}resourceType="buffer-usage";[p];"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout),a=Fn[this.usage];return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${e.resolve(this.dataType)};`),r}toString(){return`${this.usage}:${m(this)??"<unnamed>"}`}[D](){return new Proxy({"~resolve":e=>e.resolve(this),toString:()=>`.value:${m(this)??"<unnamed>"}`,[b]:this.dataType},k)}get $(){if(Te())return this[D]();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.$}},vn=new WeakMap;function Un(t){if(!le(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=vn.get(t);return e||(e=new Re("mutable",t),vn.set(t,e)),e}var In=new WeakMap;function Pn(t){if(!le(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=In.get(t);return e||(e=new Re("readonly",t),In.set(t,e)),e}var Dn=new WeakMap;function Bn(t){if(!it(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=Dn.get(t);return e||(e=new Re("uniform",t),Dn.set(t,e)),e}var Ga={uniform:Bn,mutable:Un,readonly:Pn};function Ge(t,e,r){return fe(e)?new ut(t,e,r):new ut(t,e,r,["storage","uniform"])}function ee(t){return t.resourceType==="buffer"}function Va(t){return!!t.usableAsVertex}var $a=Ca(),ut=class{constructor(e,r,n,a){this._group=e;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;De(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}[p]=!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");if(!this._buffer&&(this._buffer=e.createBuffer({size:v(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:m(this)??"<unnamed>"}),this.initial)){let r=new An(this._buffer.getMappedRange());pe(r,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(e){return T(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(){Yt(this.dataType)}_writeToTarget(e,r){let n=Yt(this.dataType);if(n)try{n(new DataView(e),0,r,$a==="little");return}catch(a){console.error(`Error when using compiled writer for buffer ${m(this)??"<unnamed>"} - this is likely a bug, please submit an issue at https://github.com/software-mansion/TypeGPU/issues
17
+ Using fallback writer instead.`,a)}pe(new An(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=v(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=Sn(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)}copyFrom(e){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=v(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 E(new Jt(s),this.dataType)}if(e.usage&GPUBufferUsage.MAP_READ){await e.mapAsync(GPUMapMode.READ);let s=e.getMappedRange(),i=E(new Jt(s),this.dataType);return e.unmap(),i}let n=r.createBuffer({size:v(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(e,0,n,0,v(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,v(this.dataType));let o=E(new Jt(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(e){return Ga[e]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${m(this)??"<unnamed>"}`}};function Rn(t){return new Xt(t)}function Cn(t){return new Zt(t)}function Ve(t){let e=t;return e?.resourceType==="sampler"&&!!e[p]}function $e(t){let e=t;return e?.resourceType==="sampler-comparison"&&!!e[p]}var pt=class{constructor(e){this._membership=e;this[b]=this,this[p]={},T(this,e.key)}[b];[p];resourceType="sampler";"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout);return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},lt=class{constructor(e){this._membership=e;this[b]=this,this[p]={},T(this,e.key)}[b];[p];resourceType="sampler-comparison";"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout);return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},Xt=class{constructor(e){this._props=e;this[b]=this,this[p]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:m(this)??"<unnamed>"})),this._sampler)},this._filtering=e.minFilter==="linear"||e.magFilter==="linear"||e.mipmapFilter==="linear"}[b];[p];resourceType="sampler";_filtering;_sampler=null;$name(e){return T(this,e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),{group:n,binding:a}=e.allocateFixedEntry({sampler:this._filtering?"filtering":"non-filtering"},this);return e.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},Zt=class{constructor(e){this._props=e;this[b]=this,this[p]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:m(this)??"<unnamed>"})),this._sampler)}}[b];[p];resourceType="sampler-comparison";_sampler=null;$name(e){return T(this,e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),{group:n,binding:a}=e.allocateFixedEntry({sampler:"comparison"},this);return e.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}};var mt=class{constructor(e){this._membership=e;T(this,e.key)}resourceType="external-texture";"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout);return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}};var Gn={r8unorm:d,r8snorm:d,r8uint:C,r8sint:V,r16uint:C,r16sint:V,r16float:d,rg8unorm:d,rg8snorm:d,rg8uint:C,rg8sint:V,r32uint:C,r32sint:V,r32float:d,rg16uint:C,rg16sint:V,rg16float:d,rgba8unorm:d,"rgba8unorm-srgb":d,rgba8snorm:d,rgba8uint:C,rgba8sint:V,bgra8unorm:d,"bgra8unorm-srgb":d,rgb9e5ufloat:d,rgb10a2uint:C,rgb10a2unorm:d,rg11b10ufloat:d,rg32uint:C,rg32sint:V,rg32float:d,rgba16uint:C,rgba16sint:V,rgba16float:d,rgba32uint:C,rgba32sint:V,rgba32float:d,stencil8:d,depth16unorm:d,depth24plus:d,"depth24plus-stencil8":d,depth32float:d,"depth32float-stencil8":d,"bc1-rgba-unorm":d,"bc1-rgba-unorm-srgb":d,"bc2-rgba-unorm":d,"bc2-rgba-unorm-srgb":d,"bc3-rgba-unorm":d,"bc3-rgba-unorm-srgb":d,"bc4-r-unorm":d,"bc4-r-snorm":d,"bc5-rg-unorm":d,"bc5-rg-snorm":d,"bc6h-rgb-ufloat":d,"bc6h-rgb-float":d,"bc7-rgba-unorm":d,"bc7-rgba-unorm-srgb":d,"etc2-rgb8unorm":d,"etc2-rgb8unorm-srgb":d,"etc2-rgb8a1unorm":d,"etc2-rgb8a1unorm-srgb":d,"etc2-rgba8unorm":d,"etc2-rgba8unorm-srgb":d,"eac-r11unorm":d,"eac-r11snorm":d,"eac-rg11unorm":d,"eac-rg11snorm":d,"astc-4x4-unorm":d,"astc-4x4-unorm-srgb":d,"astc-5x4-unorm":d,"astc-5x4-unorm-srgb":d,"astc-5x5-unorm":d,"astc-5x5-unorm-srgb":d,"astc-6x5-unorm":d,"astc-6x5-unorm-srgb":d,"astc-6x6-unorm":d,"astc-6x6-unorm-srgb":d,"astc-8x5-unorm":d,"astc-8x5-unorm-srgb":d,"astc-8x6-unorm":d,"astc-8x6-unorm-srgb":d,"astc-8x8-unorm":d,"astc-8x8-unorm-srgb":d,"astc-10x5-unorm":d,"astc-10x5-unorm-srgb":d,"astc-10x6-unorm":d,"astc-10x6-unorm-srgb":d,"astc-10x8-unorm":d,"astc-10x8-unorm-srgb":d,"astc-10x10-unorm":d,"astc-10x10-unorm-srgb":d,"astc-12x10-unorm":d,"astc-12x10-unorm-srgb":d,"astc-12x12-unorm":d,"astc-12x12-unorm-srgb":d,r16snorm:d,r16unorm:d,rg16unorm:d,rg16snorm:d,rgba16unorm:d,rgba16snorm:d},_e={rgba8unorm:P,rgba8snorm:P,rgba8uint:_,rgba8sint:$,rgba16uint:_,rgba16sint:$,rgba16float:P,r32uint:_,r32sint:$,r32float:P,rg32uint:_,rg32sint:$,rg32float:P,rgba32uint:_,rgba32sint:$,rgba32float:P,bgra8unorm:P},Vn={f32:"float",u32:"uint",i32:"sint"},$n={float:d,"unfilterable-float":d,uint:C,sint:V,depth:d};function _n(t,e){return new er(t,e)}function N(t){return t?.resourceType==="texture"&&!!t[p]}function Ee(t){return t?.resourceType==="texture-storage-view"&&!!t[p]}function Le(t){return t?.resourceType==="texture-sampled-view"&&!!t[p]}var En={mutable:"read_write",readonly:"read",writeonly:"write"},er=class{constructor(e,r){this.props=e;this._branch=r;this[p]={unwrap:()=>{if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:m(this)??"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:this.props.dimension??"2d",viewFormats:this.props.viewFormats??[],mipLevelCount:this.props.mipLevelCount??1,sampleCount:this.props.sampleCount??1})),this._texture}}}[p];resourceType="texture";usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;_destroyed=!1;_flags=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;_texture=null;$name(e){return T(this,e),this}$usage(...e){let r=e.includes("storage"),n=e.includes("sampled"),a=e.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||=r,this.usableAsSampled||=n,this.usableAsRender||=a,this}createView(e,r){if(e==="sampled")return this._asSampled(r);let n=r;switch(e){case"mutable":return this._asMutable(n);case"readonly":return this._asReadonly(n);case"writeonly":return this._asWriteonly(n)}}_asStorage(e,r){if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=e?.format??this.props.format,a=_e[n];return re(!!a,`Unsupported storage texture format: ${n}`),new tr(e??{},r,this)}_asReadonly(e){return this._asStorage(e,"readonly")}_asWriteonly(e){return this._asStorage(e,"writeonly")}_asMutable(e){return this._asStorage(e,"mutable")}_asSampled(e){if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=e?.format??this.props.format;if(!_e[r])throw new Error(`Unsupported storage texture format: ${r}`);return new rr(e,this)}destroy(){this._destroyed||(this._destroyed=!0,this._texture?.destroy())}},gt={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},tr=class{constructor(e,r,n){this.access=r;this._texture=n;this[b]=this,this[p]={unwrap:()=>(this._view||(this._view=this._texture[p].unwrap().createView({label:`${m(this)??"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view)},this[h]=n,this.dimension=e?.dimension??n.props.dimension??"2d",this._format=e?.format??n.props.format,this.texelDataType=_e[this._format]}[b];[p];[h];resourceType="texture-storage-view";texelDataType;dimension;_view;_format;$name(e){return this._texture.$name(e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),{group:n,binding:a}=e.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${gt[this.dimension]}`;return e.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${En[this.access]}>;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},dt=class{constructor(e,r,n,a){this._format=e;this.dimension=r;this.access=n;this._membership=a;this[b]=this,this[p]={},this.texelDataType=_e[this._format],T(this,a.key)}[b];[p];resourceType="texture-storage-view";texelDataType;"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${gt[this.dimension]}`;return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${En[this.access]}>;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},rr=class{constructor(e,r){this._props=e;this._texture=r;this[b]=this,this[p]={unwrap:()=>(this._view||(this._view=this._texture[p].unwrap().createView({label:`${m(this)??"<unnamed>"} - View`,...this._props})),this._view)},this[h]=r,this.dimension=e?.dimension??r.props.dimension??"2d",this._format=e?.format??r.props.format,this.channelDataType=Gn[this._format]}[b];[p];[h];resourceType="texture-sampled-view";channelDataType;dimension;_format;_view;$name(e){return this._texture.$name(e),this}"~resolve"(e){let r=e.names.makeUnique(m(this)),n=(this._texture.props.sampleCount??1)>1,{group:a,binding:o}=e.allocateFixedEntry({texture:Vn[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),s=n?"texture_multisampled_2d":`texture_${gt[this.dimension]}`;return e.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${s}<${e.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}},ft=class{constructor(e,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;this[b]=this,this[p]={},T(this,a.key),this.channelDataType=$n[e]}[b];[p];resourceType="texture-sampled-view";channelDataType;"~resolve"(e){let r=e.names.makeUnique(m(this)),n=e.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${gt[this.dimension]}`;return e.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${e.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${m(this)??"<unnamed>"}`}};function nr(t){return!!t?.usableAsSampled}function _a(t){return!!t?.usableAsRender}var ct=class t extends Error{constructor(e){super(`Resource '${m(e)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,t.prototype)}};function yt(t){return new or(t)}function Tt(t){return!!t&&t.resourceType==="bind-group-layout"}function sr(t){return!!t&&t.resourceType==="bind-group"}var ar=class t extends Error{constructor(e,r){super(`Bind group '${e??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,t.prototype)}},Ln=["compute"],Se=["compute","vertex","fragment"],or=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 Ce("uniform",a.uniform,o)),"storage"in a){let s="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Ce(a.access??"readonly",s,o)}"texture"in a&&(this.bound[n]=new ft(a.texture,a.viewDimension??"2d",a.multisampled??!1,o)),"storageTexture"in a&&(this.bound[n]=new dt(a.storageTexture,a.viewDimension??"2d",a.access??"writeonly",o)),"externalTexture"in a&&(this.bound[n]=new mt(o)),"sampler"in a&&(a.sampler==="comparison"?this.bound[n]=new lt(o):this.bound[n]=new pt(o)),"texture"in a||"storageTexture"in a||"externalTexture"in a||"sampler"in a?this.value[n]=this.bound[n]:Object.defineProperty(this.value,n,{get:()=>this.bound[n].value}),r++}}[p]=!0;_index;resourceType="bind-group-layout";bound={};value={};$=this.value;toString(){return`bindGroupLayout:${m(this)??"<unnamed>"}`}get index(){return this._index}$name(e){return T(this,e),this}$idx(e){return this._index=e,this}unwrap(e){return e.device.createBindGroupLayout({label:m(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??Se,s.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?Ln:Se),s.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??Se,s.sampler={type:n.sampler};else if("texture"in n)o=o??Se,s.texture={sampleType:n.texture,viewDimension:n.viewDimension??"2d",multisampled:n.multisampled??!1};else if("storageTexture"in n){let i=n.access??"writeonly";o=o??(i==="readonly"?Se:Ln),s.storageTexture={format:n.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[i],viewDimension:n.viewDimension??"2d"}}else"externalTexture"in n&&(o=o??Se,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(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 ar(m(e),n)}resourceType="bind-group";unwrap(e){return e.device.createBindGroup({label:m(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 '${m(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let i;if(ee(s)){if(!it(s))throw new At(s);i={buffer:e.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("storage"in a){let i;if(ee(s)){if(!le(s))throw new Ae(s);i={buffer:e.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("texture"in a){let i;if(N(s)){if(!nr(s))throw new ct(s);i=e.unwrap(s.createView("sampled"))}else Le(s)?i=e.unwrap(s):i=s;return{binding:o,resource:i}}if("storageTexture"in a){let i;if(N(s)){if(!le(s))throw new Ae(s);a.access==="readonly"?i=e.unwrap(s.createView("readonly")):a.access==="mutable"?i=e.unwrap(s.createView("mutable")):i=e.unwrap(s.createView("writeonly"))}else Ee(s)?i=e.unwrap(s):i=s;return{binding:o,resource:i}}if("sampler"in a)return Ve(s)||$e(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: ${s} (${JSON.stringify(s)})`)}).filter(n=>n!==null)})}};var On="#CATCHALL#",ur=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 topFunctionReturnType(){let e=this._stack.findLast(r=>r.type==="functionScope");if(!e)throw new Error("Internal error, expected function scope to be present.");return e.returnType}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){this._stack.push({type:"functionScope",args:e,argAliases:r,returnType:n,externalMap:a})}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?en(o):void 0}if(n?.type==="blockScope"){let a=n.declarations.get(e);if(a!==void 0)return M(e,a)}}}defineBlockVariable(e,r){if(r.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")return a.declarations.set(e,r),M(e,r)}throw new Error("No block scope found to define a variable in.")}},xt=[""," "," "," "," "," "," "," "," "],ir=xt.length-1,pr=class{identLevel=0;get pre(){return xt[this.identLevel]??xt[ir].repeat(this.identLevel/ir)+xt[this.identLevel%ir]}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}}},Oe=class{_memoizedResolves=new WeakMap;_memoizedDerived=new WeakMap;_indentController=new pr;_itemStateStack=new ur;#e=[];_declarations=[];_varyingLocations;get varyingLocations(){return this._varyingLocations}[p]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];names;expectedType;constructor(e){this.names=e.names}get pre(){return this._indentController.pre}get topFunctionReturnType(){return this._itemStateStack.topFunctionReturnType}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){return this._itemStateStack.defineBlockVariable(e,r)}pushBlockScope(){this._itemStateStack.pushBlockScope()}popBlockScope(){this._itemStateStack.popBlockScope()}fnToWgsl(e){this._itemStateStack.pushFunctionScope(e.args,e.argAliases,e.returnType,e.externalMap);try{return{head:Ea(this,e.args,e.returnType),body:rn(this,e.body)}}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:On,binding:n}}readSlot(e){let r=this._itemStateStack.readSlot(e);if(r===void 0)throw new Bt(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(Vt(e))return this.withSlots(e[G].pairs,()=>this.unwrap(e[G].inner));let r=e;for(;;)if(ze(r))r=this.readSlot(r);else if(qe(r))r=this._getOrCompute(r);else break;return r}_getOrCompute(e){let r=this._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 Vr);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._memoizedDerived.set(e,r),n}catch(n){throw n instanceof de?n.appendToTrace(e):new de(n,[e])}finally{this._itemStateStack.popItem()}}_getOrInstantiate(e){let r=this._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;L(e)?n=Ht(this,e):qe(e)||ze(e)?n=this.resolve(this.unwrap(e)):Er(e)?n=e["~resolve"](this):n=this.resolveValue(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._memoizedResolves.set(e,r),n}catch(n){throw n instanceof de?n.appendToTrace(e):new de(n,[e])}finally{this._itemStateStack.popItem()}}resolve(e){if(Vt(e))return this.withSlots(e[G].pairs,()=>this.resolve(e[G].inner));if(e&&typeof e=="object"||typeof e=="function"){if(this._itemStateStack.itemDepth===0)try{this.pushMode(new $r);let r=Ke(this,()=>this._getOrInstantiate(e));return`${[...this._declarations].join(`
29
18
 
30
- `)}${r}`}finally{tr(We.GPU)}return this._getOrInstantiate(t)}return String(t)}resolveValue(t,r){if(wt(t))return this.resolve(t);if(r&&q(r))return`array(${t.map(n=>this.resolveValue(n,r.elementType))})`;if(Array.isArray(t))return`array(${t.map(n=>this.resolveValue(n))})`;if(r&&B(r))return`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>this.resolveValue(t[n],a))})`;throw new Error(`Value ${t} (as json: ${JSON.stringify(t)}) of schema ${r} is not resolvable to WGSL`)}};function fe(e,t){let r=new Nr(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],i=new Set([...a.keys()].map(m=>m.index).filter(m=>m!==void 0)),s=wn(i),p=r.fixedBindings.map((m,g)=>[String(g),m.layoutEntry]),u=()=>{let m=s.next().value,g=kt(Object.fromEntries(p));return o[m]=g,n=n.replaceAll(la,String(m)),[m,new Le(g,Object.fromEntries(r.fixedBindings.map((y,x)=>[String(x),y.resource])))]},f=p.length>0?u():void 0;for(let[m,g]of a.entries()){let y=m.index??s.next().value;o[y]=m,n=n.replaceAll(g,String(y))}return{code:n,usedBindGroupLayouts:o,catchall:f}}function co(e,t,r){let n=t.map(a=>`${a.value}: ${e.resolve(a.dataType)}`).join(", ");return r.type!=="void"?`(${n}) -> ${Re(r)} ${e.resolve(r)}`:`(${n})`}function zr(e){let{externals:t,template:r,names:n}=e,a={};return be(a,t??{}),fe({"~resolve"(i){return we(i,a,r??"")},toString:()=>"<root>"},{names:n==="strict"?new le:new pe})}function ma(e){return zr(e).code}function da(e,t,r,n){return new jr(e,t,r,n)}function st(e){let t=e;return t?.resourceType==="query-set"&&!!t[l]}var jr=class{constructor(t,r,n,a){this._group=t;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 t=this;return{get readBuffer(){return t._readBuffer||(t._readBuffer=t._group.device.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._group.device.createBuffer({size:t.count*BigUint64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC})),t._resolveBuffer}}}$name(t){return h(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._group.device.createCommandEncoder();t.resolveQuerySet(this.querySet,0,this.count,this[l].resolveBuffer,0),this._group.device.queue.submit([t.finish()])}async read(){if(this._group.flush(),!this._resolveBuffer)throw new Error("QuerySet must be resolved before reading.");this._available=!1;try{let t=this._group.device.createCommandEncoder();t.copyBufferToBuffer(this[l].resolveBuffer,0,this[l].readBuffer,0,this.count*BigUint64Array.BYTES_PER_ELEMENT),this._group.device.queue.submit([t.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(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 Mt(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 Nt(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 zt(e,t){if(!e.timestampWrites)return{};let{querySet:r,beginningOfPassWriteIndex:n,endOfPassWriteIndex:a}=e.timestampWrites,o={querySet:st(r)?t.unwrap(r):r};return n!==void 0&&(o.beginningOfPassWriteIndex=n),a!==void 0&&(o.endOfPassWriteIndex=a),{timestampWrites:o}}function pt({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(!st(r))throw new Error("Performance callback with raw GPUQuerySet is not supported. Use TgpuQuerySet instead.");e.commandEncoder.resolveQuerySet(e.unwrap(r),0,r.count,r[l].resolveBuffer,0),e.flush(),e.device.queue.onSubmittedWorkDone().then(async()=>{if(!r.available)return;let a=await r.read(),o=a[t.timestampWrites?.beginningOfPassWriteIndex??0],i=a[t.timestampWrites?.endOfPassWriteIndex??1];if(o===void 0||i===void 0)throw new Error("QuerySet did not return valid timestamps.");await n(o,i)})}function fa(e,t,r){return new qr(new Qr(e,t,r),{})}function ca(e){let t=e;return t?.resourceType==="compute-pipeline"&&!!t[l]}var qr=class e{constructor(t,r){this._core=t;this._priors=r;this[l]={get rawPipeline(){return t.unwrap().pipeline},get priors(){return r}},this[S]=t}[l];resourceType="compute-pipeline";[S];"~resolve"(t){return t.resolve(this._core)}toString(){return`computePipeline:${d(this)??"<unnamed>"}`}get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){return new e(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[t,r]])})}withPerformanceCallback(t){let r=Mt(this._priors,t,this._core.branch);return new e(this._core,r)}withTimestampWrites(t){let r=Nt(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,i={label:d(this._core)??"<unnamed>",...zt(this._priors,o)},s=o.commandEncoder.beginComputePass(i);s.setPipeline(a.pipeline);let p=new Set(a.usedBindGroupLayouts);if(a.usedBindGroupLayouts.forEach((u,f)=>{if(a.catchall&&f===a.catchall[0])s.setBindGroup(f,o.unwrap(a.catchall[1])),p.delete(u);else{let m=this._priors.bindGroupLayoutMap?.get(u);m!==void 0&&(p.delete(u),s.setBindGroup(f,o.unwrap(m)))}}),p.size>0)throw new ge(p);s.dispatchWorkgroups(t,r,n),s.end(),this._priors.performanceCallback&&pt({root:o,priors:this._priors})}$name(t){return h(this._core,t),this}},Qr=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n}_memo;"~resolve"(t){return t.withSlots(this._slotBindings,()=>(t.resolve(this._entryFn),""))}toString(){return"computePipelineCore"}unwrap(){if(this._memo===void 0){let t=this.branch.device,r,n;if(ee?.enabled){let p=performance.mark("typegpu:resolution:start");r=fe(this,{names:this.branch.nameRegistry}),n=performance.measure("typegpu:resolution",{start:p.name})}else r=fe(this,{names:this.branch.nameRegistry});let{code:a,usedBindGroupLayouts:o,catchall:i}=r;i!==void 0&&o[i[0]]?.$name(`${d(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let s=t.createShaderModule({label:`${d(this)??"<unnamed>"} - Shader`,code:a});this._memo={pipeline:t.createComputePipeline({label:d(this)??"<unnamed>",layout:t.createPipelineLayout({label:`${d(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:o.map(p=>this.branch.unwrap(p))}),compute:{module:s}}),usedBindGroupLayouts:o,catchall:i},ee?.enabled&&(async()=>{let p=performance.mark("typegpu:compile-start");await t.queue.onSubmittedWorkDone();let u=performance.measure("typegpu:compiled",{start:p.name});ee?.record("resolution",{resolveDuration:n?.duration,compileDuration:u.duration,wgslSize:a.length})})()}return this._memo}};function Yr(e,t="vertex"){return new Hr(e,t)}function qt(e){return e?.resourceType==="vertex-layout"}var Kr=Symbol("defaultAttribEntry");function jt(e,t,r,n,a){if(dt(t)||hn(t)){let o=W(t);return o!==void 0&&(n[a??Kr]=o),jt(e,t.inner,O(r,K(t)),n)}if(B(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,s])=>{o=O(o,$(s));let p=[i,jt(e,s,o,n,i)];return o+=v(s),p}))}if(Q(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,s])=>{o=O(o,K(s));let p=[i,jt(e,s,o,n,i)];return o+=v(s),p}))}if("type"in t&&typeof t.type=="string"){if(ln.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=mn[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var Hr=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;let n=t(0);this.stride=O(v(n.elementType),$(n)),this.attrib=jt(this,n.elementType,0,this._customLocationMap)}[l]=!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 h(this,t),this}};function go(e){return typeof e?.loadOp=="string"}function ga(e,t){if(M(e)){if(!go(t))throw new Error("Expected a single color attachment, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function yo(e){return typeof e?.format=="string"}function ya(e,t){if(M(e)){if(ft(e))return[];if(!yo(t))throw new Error("Expected a single color target configuration, not a record.");return[t]}let r=[];for(let n of Object.keys(e)){let a=t[n];if(!a)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Ta(e){return new Jr(new Xr(e),{})}function xa(e){let t=e;return t?.resourceType==="render-pipeline"&&!!t[l]}var Jr=class e{[l];resourceType="render-pipeline";[S];hasIndexBuffer=!1;constructor(t,r){this[l]={core:t,priors:r},this[S]=t}"~resolve"(t){return t.resolve(this[l].core)}toString(){return`renderPipeline:${d(this)??"<unnamed>"}`}$name(t){return h(this[l].core,t),this}with(t,r){let n=this[l];if(Lt(t))return new e(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[t,r]])});if(qt(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[l],n=Mt(r.priors,t,r.core.options.branch);return new e(r.core,n)}withTimestampWrites(t){let r=this[l],n=Nt(r.priors,t,r.core.options.branch);return new e(r.core,n)}withColorAttachment(t){let r=this[l];return new e(r.core,{...r.priors,colorAttachment:t})}withDepthStencilAttachment(t){let r=this[l];return new e(r.core,{...r.priors,depthStencilAttachment:t})}withIndexBuffer(t,r,n,a){let o=this[l];if(Ye(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 i={u32:"uint32",u16:"uint16"},s=t.dataType.elementType;return new e(o.core,{...o.priors,indexBuffer:{buffer:t,indexFormat:i[s.type],offsetBytes:r!==void 0?r*ur(s):void 0,sizeBytes:a!==void 0?a*ur(s):void 0}})}setupRenderPass(){let t=this[l],r=t.core.unwrap(),{branch:n,fragmentFn:a}=t.core.options,o=ga(a.shell.out,t.priors.colorAttachment??{}).map(m=>Z(m.view)?{...m,view:n.unwrap(m.view).createView()}:m),i={label:d(t.core)??"<unnamed>",colorAttachments:o,...zt(t.priors,n)};if(t.priors.depthStencilAttachment!==void 0){let m=t.priors.depthStencilAttachment;Z(m.view)?i.depthStencilAttachment={...m,view:n.unwrap(m.view).createView()}:i.depthStencilAttachment=m}let s=n.commandEncoder.beginRenderPass(i);s.setPipeline(r.pipeline);let p=new Set(r.usedBindGroupLayouts);r.usedBindGroupLayouts.forEach((m,g)=>{if(r.catchall&&g===r.catchall[0])s.setBindGroup(g,n.unwrap(r.catchall[1])),p.delete(m);else{let y=t.priors.bindGroupLayoutMap?.get(m);y!==void 0&&(p.delete(m),s.setBindGroup(g,n.unwrap(y)))}});let u=new Set(t.core.usedVertexLayouts);if(t.core.usedVertexLayouts.forEach((m,g)=>{let y=t.priors.vertexLayoutMap?.get(m);y&&(u.delete(m),s.setVertexBuffer(g,n.unwrap(y)))}),p.size>0)throw new ge(p);if(u.size>0)throw new Oe(u);return s}draw(t,r,n,a){let o=this[l],i=this.setupRenderPass(),{branch:s}=o.core.options;i.draw(t,r,n,a),i.end(),o.priors.performanceCallback?pt({root:s,priors:o.priors}):s.flush()}drawIndexed(t,r,n,a,o){let i=this[l];if(!i.priors.indexBuffer)throw new Error("No index buffer set for this render pipeline.");let{buffer:s,indexFormat:p,offsetBytes:u,sizeBytes:f}=i.priors.indexBuffer,m=this.setupRenderPass(),{branch:g}=i.core.options;Ye(s)?m.setIndexBuffer(s,p,u,f):m.setIndexBuffer(g.unwrap(s),p,u,f),m.drawIndexed(t,r,n,a,o),m.end(),i.priors.performanceCallback?pt({root:g,priors:i.priors}):g.flush()}},Xr=class{constructor(t){this.options=t;let r=jn(t.vertexFn.shell.in??{},t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=ya(t.fragmentFn.shell.out,t.targets)}usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;"~resolve"(t){let{vertexFn:r,fragmentFn:n,slotBindings:a}=this.options,o=To(r.shell.out,n.shell.in,d(r)??"<unnamed>",d(n)??"<unnamed>");return t.withVaryingLocations(o,()=>t.withSlots(a,()=>(t.resolve(r),t.resolve(n),"")))}toString(){return"renderPipelineCore"}unwrap(){if(this._memo===void 0){let{branch:t,primitiveState:r,depthStencilState:n,multisampleState:a}=this.options,o=t.device,i,s;if(ee?.enabled){let x=performance.mark("typegpu:resolution:start");i=fe(this,{names:t.nameRegistry}),s=performance.measure("typegpu:resolution",{start:x.name})}else i=fe(this,{names:t.nameRegistry});let{code:p,usedBindGroupLayouts:u,catchall:f}=i;f!==void 0&&u[f[0]]?.$name(`${d(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let m=o.createShaderModule({label:`${d(this)??"<unnamed>"} - Shader`,code:p}),g={layout:o.createPipelineLayout({label:`${d(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:u.map(x=>t.unwrap(x))}),vertex:{module:m,buffers:this._vertexBufferLayouts},fragment:{module:m,targets:this._targets}},y=d(this);y!==void 0&&(g.label=y),r&&(ne(r.stripIndexFormat)?g.primitive={...r,stripIndexFormat:{u32:"uint32",u16:"uint16"}[r.stripIndexFormat.type]}:g.primitive=r),n&&(g.depthStencil=n),a&&(g.multisample=a),this._memo={pipeline:o.createRenderPipeline(g),usedBindGroupLayouts:u,catchall:f},ee?.enabled&&(async()=>{let x=performance.mark("typegpu:compile-start");await o.queue.onSubmittedWorkDone();let b=performance.measure("typegpu:compiled",{start:x.name});ee?.record("resolution",{resolveDuration:s?.duration,compileDuration:b.duration,wgslSize:p.length})})()}return this._memo}};function To(e,t,r,n){let a={},o=new Set;function i(p,u){a[p]=u,o.add(u)}for(let[p,u]of Object.entries(e)){let f=W(u);f!==void 0&&i(p,f)}for(let[p,u]of Object.entries(t??{})){let f=W(u);f!==void 0&&(a[p]===void 0?i(p,f):a[p]!==f&&console.warn(`Mismatched location between vertexFn (${r}) output (${a[p]}) and fragmentFn (${n}) input (${f}) for the key "${p}", using the location set on vertex output.`))}let s=0;for(let p of Object.keys(e??{}))if(!(Ce(e[p])||a[p]!==void 0)){for(;o.has(s);)s++;i(p,s)}return a}function Zr(e){return e instanceof Ie}var Ie=class{constructor(t,r){this.resourceType=t;this.buffer=r;this[S]=r,this.#t=this.buffer.as(this.resourceType)}[l]=!0;[S];#t;$name(t){return h(this[S],t),this}write(t){this.buffer.write(t)}writePartial(t){this.buffer.writePartial(t)}read(){return this.buffer.read()}get value(){return this.#t.value}"~resolve"(t){return t.resolve(this.#t)}get $(){return this.value}};var en=class e{constructor(t){this.bindings=t}with(t,r){return new e([...this.bindings,[Ee(t)?t.slot:t,r]])}pipe(t){let r=t(this);return new e([...this.bindings,...r.bindings])}},tn=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[Ee(t)?t.slot:t,r]])}withCompute(t){return new rn(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new nn({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 en([]));return new e(this._getRoot,[...this._slotBindings,...r.bindings])}},rn=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return fa(this._root,this._slotBindings,this._entryFn)}},nn=class{constructor(t){this._options=t}withFragment(t,r,n){return ce(typeof t!="string","Just type mismatch validation"),ce(typeof r!="string","Just type mismatch validation"),new an({...this._options,fragmentFn:t,targets:r})}},an=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 Ta(this._options)}},Qt=class extends tn{constructor(r,n,a){super(()=>this,[]);this.device=r;this.nameRegistry=n;this._ownDevice=a;this["~unstable"]=this}"~unstable";_disposables=[];_unwrappedBindGroupLayouts=new ut(r=>r.unwrap(this));_unwrappedBindGroups=new ut(r=>r.unwrap(this));_commandEncoder=null;get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}get enabledFeatures(){return new Set(this.device.features)}createBuffer(r,n){let a=tt(this,r,n);return this._disposables.push(a),a}createUniform(r,n){let a=tt(this,r,n).$usage("uniform");return this._disposables.push(a),new Ie("uniform",a)}createMutable(r,n){let a=tt(this,r,n).$usage("storage");return this._disposables.push(a),new Ie("mutable",a)}createReadonly(r,n){let a=tt(this,r,n).$usage("storage");return this._disposables.push(a),new Ie("readonly",a)}createQuerySet(r,n,a){return da(this,r,n,a)}createBindGroup(r,n){return new Le(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=aa(r,this);return this._disposables.push(n),n}unwrap(r){if(ca(r))return r[l].rawPipeline;if(xa(r))return r[l].core.unwrap().pipeline;if(Lt(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(kr(r))return this._unwrappedBindGroups.getOrMake(r);if(de(r))return r.buffer;if(Z(r))return r[l].unwrap();if(ot(r)){if(r[l].unwrap)return r[l].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(it(r)){if(r[l].unwrap)return r[l].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(qt(r))return r.vertexLayout;if(rt(r)){if(r[l].unwrap)return r[l].unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if(nt(r)){if(r[l].unwrap)return r[l].unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}if(st(r))return r.querySet;throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,i=new Map,s,p=()=>{if(!s)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:u,priors:f}=s[l],m=u.unwrap();a.setPipeline(m.pipeline);let g=new Set(m.usedBindGroupLayouts);m.usedBindGroupLayouts.forEach((x,b)=>{if(m.catchall&&b===m.catchall[0])a.setBindGroup(b,this.unwrap(m.catchall[1])),g.delete(x);else{let I=f.bindGroupLayoutMap?.get(x)??o.get(x);I!==void 0&&(g.delete(x),kr(I)?a.setBindGroup(b,this.unwrap(I)):a.setBindGroup(b,I))}});let y=new Set;if(u.usedVertexLayouts.forEach((x,b)=>{let I=f.vertexLayoutMap?.get(x),P=I?{buffer:I,offset:void 0,size:void 0}:i.get(x);!P||!P.buffer?y.add(x):de(P.buffer)?a.setVertexBuffer(b,this.unwrap(P.buffer),P.offset,P.size):a.setVertexBuffer(b,P.buffer,P.offset,P.size)}),g.size>0)throw new ge(g);if(y.size>0)throw new Oe(y)};n({setViewport(...u){a.setViewport(...u)},setScissorRect(...u){a.setScissorRect(...u)},setBlendConstant(...u){a.setBlendConstant(...u)},setStencilReference(...u){a.setStencilReference(...u)},beginOcclusionQuery(...u){a.beginOcclusionQuery(...u)},endOcclusionQuery(...u){a.endOcclusionQuery(...u)},executeBundles(...u){a.executeBundles(...u)},setPipeline(u){s=u},setIndexBuffer:(u,f,m,g)=>{de(u)?a.setIndexBuffer(this.unwrap(u),f,m,g):a.setIndexBuffer(u,f,m,g)},setVertexBuffer(u,f,m,g){i.set(u,{buffer:f,offset:m,size:g})},setBindGroup(u,f){o.set(u,f)},draw(u,f,m,g){p(),a.draw(u,f,m,g)},drawIndexed(...u){p(),a.drawIndexed(...u)},drawIndirect(...u){p(),a.drawIndirect(...u)},drawIndexedIndirect(...u){p(),a.drawIndexedIndirect(...u)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function ha(e){let{adapter:t,device:r,unstable_names:n="random"}=e??{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let a=await navigator.gpu.requestAdapter(t);if(!a)throw new Error("Could not find a compatible GPU");let o=[];for(let i of r?.requiredFeatures??[]){if(!a.features.has(i))throw new Error(`Requested feature "${i}" is not supported by the adapter.`);o.push(i)}for(let i of r?.optionalFeatures??[])a.features.has(i)?o.push(i):console.warn(`Optional feature "${i}" is not supported by the adapter.`);return new Qt(await a.requestDevice({...r,requiredFeatures:o}),n==="random"?new pe:new le,!0)}function ba(e){let{device:t,unstable_names:r="random"}=e??{};return new Qt(t,r==="random"?new pe:new le,!1)}function lt(e){return new on(e)}var on=class{constructor(t=void 0){this.defaultValue=t}[l]=!0;resourceType="slot";$name(t){return h(this,t),this}areEqual(t,r){return Object.is(t,r)}toString(){return`slot:${d(this)??"<unnamed>"}`}[U](t){return Ke(t,t.unwrap(this))}get value(){let t=re();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return this[U](t)}get $(){return this.value}};function wa(e,t){return new sn(e,t)}var sn=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;this.slot=lt(r),this[S]=this.slot}[l]=!0;resourceType="accessor";slot;$name(t){return this.slot.$name(t),this}toString(){return`accessor:${d(this)??"<unnamed>"}`}[U](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${d(this)??"<unnamed>"}`,[w]:this.schema},H)}get value(){if(!J())throw new Error("`tgpu.accessor` values are only accessible on the GPU");return this[U]()}get $(){return this.value}"~resolve"(t){let r=t.unwrap(this.slot);return Rn(r)||Zr(r)?t.resolve(r):hr(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function Sa(e){return ho(e)}function xo([e,t]){return`${d(e)??"<unnamed>"}=${t}`}function ho(e){if(re())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{resourceType:"derived","~compute":e,[Ht]:void 0,[Yt]:void 0,[U](r){return Ke(r,r.unwrap(this))},get value(){let r=re();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[U](r)},get $(){return this.value},with(r,n){return va(this,[[r,n]])},toString(){return"derived"}}}function va(e,t){return{resourceType:"derived",[Ht]:void 0,[Yt]:void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},[L]:{inner:e,pairs:t},[U](n){return Ke(n,n.unwrap(this))},get value(){let n=re();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[U](n)},get $(){return this.value},with(n,a){return va(e,[...t,[n,a]])},toString(){return`derived[${t.map(xo).join(", ")}]`}}}function Da(e,t){return new Kt("private",e,t)}function Ia(e){return new Kt("workgroup",e)}var Kt=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n;this[l]={scope:t}}"~resolve"(t){let r=t.names.makeUnique(d(this));return this._initialValue?t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)} = ${t.resolveValue(this._initialValue,this._dataType)};`):t.addDeclaration(`var<${this.scope}> ${r}: ${t.resolve(this._dataType)};`),r}$name(t){return h(this,t),this}toString(){return`var:${d(this)??"<unnamed>"}`}[U](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${d(this)??"<unnamed>"}`,[w]:this._dataType},H)}get value(){if(!J())throw new Error("`tgpu.var` values are only accessible on the GPU");return this[U]()}};var bo={fn:xr,bindGroupLayout:kt,vertexLayout:Yr,slot:lt,init:ha,initFromDevice:ba,resolve:ma,resolveWithContext:zr,"~unstable":{fn:xr,fragmentFn:Nn,vertexFn:zn,computeFn:Wn,vertexLayout:Yr,derived:Sa,slot:lt,accessor:wa,privateVar:Da,workgroupVar:Ia,const:Cn,declare:Gn,sampler:Zn,comparisonSampler:ea}},um=bo;export{ge as MissingBindGroupsError,Zt as MissingLinksError,Jt as MissingSlotValueError,Oe as MissingVertexBuffersError,Xt as NotUniformError,pe as RandomNameRegistry,Y as ResolutionError,le as StrictNameRegistry,um as default,de as isBuffer,Zr as isBufferShorthand,nt as isComparisonSampler,Ve as isDerived,it as isSampledTextureView,rt as isSampler,Ge as isSlot,ot as isStorageTextureView,Z as isTexture,hr as isTgpuFn,so as isUsableAsRender,Vr as isUsableAsSampled,ve as isUsableAsStorage,Bt as isUsableAsUniform,io as isUsableAsVertex,bo as tgpu,Ir as unstable_asMutable,Ur as unstable_asReadonly,Fr as unstable_asUniform};
19
+ `)}${r}`}finally{this.popMode("codegen")}return this._getOrInstantiate(e)}return String(e)}resolveValue(e,r){if(He(e))return this.resolve(e);if(r&&ge(r))return`array(${e.map(n=>this.resolveValue(n,r.elementType))})`;if(Array.isArray(e))return`array(${e.map(n=>this.resolveValue(n))})`;if(r&&B(r))return`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>this.resolveValue(e[n],a))})`;throw new Error(`Value ${e} (as json: ${JSON.stringify(e)}) of schema ${r} is not resolvable to WGSL`)}pushMode(e){this.#e.push(e)}popMode(e){let r=this.#e.pop();e!==void 0&&re(r?.type===e,"Unexpected mode")}get mode(){return this.#e[this.#e.length-1]??kr}};function te(t,e,r){let n=new Oe(e),a=r?n.withSlots(r(new be([])).bindings,()=>n.resolve(t)):n.resolve(t),o=n.bindGroupLayoutsToPlaceholderMap,s=[],i=new Set([...o.keys()].map(c=>c.index).filter(c=>c!==void 0)),u=hn(i),l=n.fixedBindings.map((c,y)=>[String(y),c.layoutEntry]),f=()=>{let c=u.next().value,y=yt(Object.fromEntries(l));return s[c]=y,a=a.replaceAll(On,String(c)),[c,new ve(y,Object.fromEntries(n.fixedBindings.map((x,I)=>[String(I),x.resource])))]},g=l.length>0?f():void 0;for(let[c,y]of o.entries()){let x=c.index??u.next().value;s[x]=c,a=a.replaceAll(y,String(x))}return{code:a,usedBindGroupLayouts:s,catchall:g}}function Ea(t,e,r){let n=e.map(a=>`${a.value}: ${t.resolve(a.dataType)}`).join(", ");return r.type!=="void"?`(${n}) -> ${he(r)}${t.resolve(r)} `:`(${n}) `}function lr(t){let{externals:e,template:r,names:n,config:a}=t,o={};return Y(o,e??{}),te({"~resolve"(i){return ie(i,o,r??"")},toString:()=>"<root>"},{names:n==="strict"?new W:new ue},a)}function kn(t){return lr(t).code}function Mn(t){let e=j()??new Oe({names:new W}),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,f)=>Array.from({length:a[1]},(g,c)=>Array.from({length:a[2]},(y,x)=>{let I=Math.floor(f/n[0]),w=Math.floor(c/n[1]),S=Math.floor(x/n[2]);return new _r(o,{private:i[f][c][x],workgroup:s[I][w][S]})})));e.pushMode(u[0][0][0]);try{return{value:Ke(e,t),buffers:o,privateVars:i,workgroupVars:s}}finally{e.popMode("simulate")}}function Wn(t,e,r,n){return new mr(t,e,r,n)}function ke(t){let e=t;return e?.resourceType==="query-set"&&!!e[p]}var mr=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[p](){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 T(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[p].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[p].resolveBuffer,0,this[p].readBuffer,0,this.count*BigUint64Array.BYTES_PER_ELEMENT),this._group.device.queue.submit([e.finish()]),await this._group.device.queue.onSubmittedWorkDone();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 Me=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 ht(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 bt(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 wt(t,e){if(!t.timestampWrites)return{};let{querySet:r,beginningOfPassWriteIndex:n,endOfPassWriteIndex:a}=t.timestampWrites,o={querySet:ke(r)?e.unwrap(r):r};return n!==void 0&&(o.beginningOfPassWriteIndex=n),a!==void 0&&(o.endOfPassWriteIndex=a),{timestampWrites:o}}function We({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(!ke(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[p].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 Nn(t,e,r){return new dr(new fr(t,e,r),{})}function zn(t){let e=t;return e?.resourceType==="compute-pipeline"&&!!e[p]}var dr=class t{constructor(e,r){this._core=e;this._priors=r;this[p]={get rawPipeline(){return e.unwrap().pipeline},get priors(){return r}},this[h]=e}[p];resourceType="compute-pipeline";[h];"~resolve"(e){return e.resolve(this._core)}toString(){return`computePipeline:${m(this)??"<unnamed>"}`}get rawPipeline(){return this._core.unwrap().pipeline}with(e,r){return new t(this._core,{...this._priors,bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[e,r]])})}withPerformanceCallback(e){let r=ht(this._priors,e,this._core.branch);return new t(this._core,r)}withTimestampWrites(e){let r=bt(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:m(this._core)??"<unnamed>",...wt(this._priors,o)},i=o.commandEncoder.beginComputePass(s);i.setPipeline(a.pipeline);let u=new Set(a.usedBindGroupLayouts);if(a.usedBindGroupLayouts.forEach((l,f)=>{if(a.catchall&&f===a.catchall[0])i.setBindGroup(f,o.unwrap(a.catchall[1])),u.delete(l);else{let g=this._priors.bindGroupLayoutMap?.get(l);g!==void 0&&(u.delete(l),i.setBindGroup(f,o.unwrap(g)))}}),u.size>0)throw new ne(u);i.dispatchWorkgroups(e,r,n),i.end(),this._priors.performanceCallback&&We({root:o,priors:this._priors})}$name(e){return T(this._core,e),this}},fr=class{constructor(e,r,n){this.branch=e;this._slotBindings=r;this._entryFn=n}_memo;"~resolve"(e){return e.withSlots(this._slotBindings,()=>(e.resolve(this._entryFn),""))}toString(){return"computePipelineCore"}unwrap(){if(this._memo===void 0){let e=this.branch.device,r,n;if(z?.enabled){let u=performance.mark("typegpu:resolution:start");r=te(this,{names:this.branch.nameRegistry}),n=performance.measure("typegpu:resolution",{start:u.name})}else r=te(this,{names:this.branch.nameRegistry});let{code:a,usedBindGroupLayouts:o,catchall:s}=r;s!==void 0&&o[s[0]]?.$name(`${m(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let i=e.createShaderModule({label:`${m(this)??"<unnamed>"} - Shader`,code:a});this._memo={pipeline:e.createComputePipeline({label:m(this)??"<unnamed>",layout:e.createPipelineLayout({label:`${m(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:o.map(u=>this.branch.unwrap(u))}),compute:{module:i}}),usedBindGroupLayouts:o,catchall:s},z?.enabled&&(async()=>{let u=performance.mark("typegpu:compile-start");await e.queue.onSubmittedWorkDone();let l=performance.measure("typegpu:compiled",{start:u.name});z?.record("resolution",{resolveDuration:n?.duration,compileDuration:l.duration,wgslSize:a.length})})()}return this._memo}};function yr(t,e="vertex"){return new cr(t,e)}function vt(t){return t?.resourceType==="vertex-layout"}var gr=Symbol("defaultAttribEntry");function St(t,e,r,n,a){if(je(e)||Nr(e)){let o=R(e);return o!==void 0&&(n[a??gr]=o),St(t,e.inner,A(r,O(e)),n)}if(B(e)){let o=r,s=e.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=A(o,U(u));let l=[i,St(t,u,o,n,i)];return o+=v(u),l}))}if(Q(e)){let o=r,s=e.propTypes;return Object.fromEntries(Object.entries(s).map(([i,u])=>{o=A(o,O(u));let l=[i,St(t,u,o,n,i)];return o+=v(u),l}))}if("type"in e&&typeof e.type=="string"){if(Mr.includes(e.type))return{_layout:t,format:e.type,offset:r};let o=Wr[e.type];if(o)return{_layout:t,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(e)}`)}var cr=class{constructor(e,r){this.schemaForCount=e;this.stepMode=r;let n=e(0);this.stride=A(v(n.elementType),U(n)),this.attrib=St(this,n.elementType,0,this._customLocationMap)}[p]=!0;resourceType="vertex-layout";stride;attrib;_customLocationMap={};get vertexLayout(){if(this._customLocationMap[gr]!==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[gr]}]}}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 T(this,e),this}};function La(t){return typeof t?.loadOp=="string"}function qn(t,e){if(L(t)){if(!La(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=e[n];if(!a)throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Oa(t){return typeof t?.format=="string"}function jn(t,e){if(L(t)){if(Qe(t))return[];if(!Oa(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=e[n];if(!a)throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);r.push(a)}return r}function Qn(t){return new Tr(new xr(t),{})}function Hn(t){let e=t;return e?.resourceType==="render-pipeline"&&!!e[p]}var Tr=class t{[p];resourceType="render-pipeline";[h];hasIndexBuffer=!1;constructor(e,r){this[p]={core:e,priors:r},this[h]=e}"~resolve"(e){return e.resolve(this[p].core)}toString(){return`renderPipeline:${m(this)??"<unnamed>"}`}$name(e){return T(this[p].core,e),this}with(e,r){let n=this[p];if(Tt(e))return new t(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[e,r]])});if(vt(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[p],n=ht(r.priors,e,r.core.options.branch);return new t(r.core,n)}withTimestampWrites(e){let r=this[p],n=bt(r.priors,e,r.core.options.branch);return new t(r.core,n)}withColorAttachment(e){let r=this[p];return new t(r.core,{...r.priors,colorAttachment:e})}withDepthStencilAttachment(e){let r=this[p];return new t(r.core,{...r.priors,depthStencilAttachment:e})}withIndexBuffer(e,r,n,a){let o=this[p];if(De(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*Wt(i):void 0,sizeBytes:a!==void 0?a*Wt(i):void 0}})}setupRenderPass(){let e=this[p],r=e.core.unwrap(),{branch:n,fragmentFn:a}=e.core.options,o=qn(a.shell.out,e.priors.colorAttachment??{}).map(g=>N(g.view)?{...g,view:n.unwrap(g.view).createView()}:g),s={label:m(e.core)??"<unnamed>",colorAttachments:o,...wt(e.priors,n)};if(e.priors.depthStencilAttachment!==void 0){let g=e.priors.depthStencilAttachment;N(g.view)?s.depthStencilAttachment={...g,view:n.unwrap(g.view).createView()}:s.depthStencilAttachment=g}let i=n.commandEncoder.beginRenderPass(s);i.setPipeline(r.pipeline);let u=new Set(r.usedBindGroupLayouts);r.usedBindGroupLayouts.forEach((g,c)=>{if(r.catchall&&c===r.catchall[0])i.setBindGroup(c,n.unwrap(r.catchall[1])),u.delete(g);else{let y=e.priors.bindGroupLayoutMap?.get(g);y!==void 0&&(u.delete(g),i.setBindGroup(c,n.unwrap(y)))}});let l=new Set(e.core.usedVertexLayouts);if(e.core.usedVertexLayouts.forEach((g,c)=>{let y=e.priors.vertexLayoutMap?.get(g);y&&(l.delete(g),i.setVertexBuffer(c,n.unwrap(y)))}),u.size>0)throw new ne(u);if(l.size>0)throw new Ie(l);return i}draw(e,r,n,a){let o=this[p],s=this.setupRenderPass(),{branch:i}=o.core.options;s.draw(e,r,n,a),s.end(),o.priors.performanceCallback?We({root:i,priors:o.priors}):i.flush()}drawIndexed(e,r,n,a,o){let s=this[p];if(!s.priors.indexBuffer)throw new Error("No index buffer set for this render pipeline.");let{buffer:i,indexFormat:u,offsetBytes:l,sizeBytes:f}=s.priors.indexBuffer,g=this.setupRenderPass(),{branch:c}=s.core.options;De(i)?g.setIndexBuffer(i,u,l,f):g.setIndexBuffer(c.unwrap(i),u,l,f),g.drawIndexed(e,r,n,a,o),g.end(),s.priors.performanceCallback?We({root:c,priors:s.priors}):c.flush()}},xr=class{constructor(e){this.options=e;let r=xn(e.vertexFn.shell.in??{},e.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=jn(e.fragmentFn.shell.out,e.targets)}usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;"~resolve"(e){let{vertexFn:r,fragmentFn:n,slotBindings:a}=this.options,o=ka(r.shell.out,n.shell.in,m(r)??"<unnamed>",m(n)??"<unnamed>");return e.withVaryingLocations(o,()=>e.withSlots(a,()=>(e.resolve(r),e.resolve(n),"")))}toString(){return"renderPipelineCore"}unwrap(){if(this._memo===void 0){let{branch:e,primitiveState:r,depthStencilState:n,multisampleState:a}=this.options,o=e.device,s,i;if(z?.enabled){let x=performance.mark("typegpu:resolution:start");s=te(this,{names:e.nameRegistry}),i=performance.measure("typegpu:resolution",{start:x.name})}else s=te(this,{names:e.nameRegistry});let{code:u,usedBindGroupLayouts:l,catchall:f}=s;f!==void 0&&l[f[0]]?.$name(`${m(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let g=o.createShaderModule({label:`${m(this)??"<unnamed>"} - Shader`,code:u}),c={layout:o.createPipelineLayout({label:`${m(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:l.map(x=>e.unwrap(x))}),vertex:{module:g,buffers:this._vertexBufferLayouts},fragment:{module:g,targets:this._targets}},y=m(this);y!==void 0&&(c.label=y),r&&(fe(r.stripIndexFormat)?c.primitive={...r,stripIndexFormat:{u32:"uint32",u16:"uint16"}[r.stripIndexFormat.type]}:c.primitive=r),n&&(c.depthStencil=n),a&&(c.multisample=a),this._memo={pipeline:o.createRenderPipeline(c),usedBindGroupLayouts:l,catchall:f},z?.enabled&&(async()=>{let x=performance.mark("typegpu:compile-start");await o.queue.onSubmittedWorkDone();let I=performance.measure("typegpu:compiled",{start:x.name});z?.record("resolution",{resolveDuration:i?.duration,compileDuration:I.duration,wgslSize:u.length})})()}return this._memo}};function ka(t,e,r,n){let a={},o=new Set;function s(u,l){a[u]=l,o.add(l)}for(let[u,l]of Object.entries(t)){let f=R(l);f!==void 0&&s(u,f)}for(let[u,l]of Object.entries(e??{})){let f=R(l);f!==void 0&&(a[u]===void 0?s(u,f):a[u]!==f&&console.warn(`Mismatched location between vertexFn (${r}) output (${a[u]}) and fragmentFn (${n}) input (${f}) for the key "${u}", using the location set on vertex output.`))}let i=0;for(let u of Object.keys(t??{}))if(!(xe(t[u])||a[u]!==void 0)){for(;o.has(i);)i++;s(u,i)}return a}function hr(t){return t instanceof me}var me=class{constructor(e,r){this.resourceType=e;this.buffer=r;this[h]=r,this.#e=this.buffer.as(this.resourceType)}[p]=!0;[h];#e;$name(e){return T(this[h],e),this}write(e){this.buffer.write(e)}writePartial(e){this.buffer.writePartial(e)}read(){return this.buffer.read()}get $(){return this.#e.$}get value(){return this.$}"~resolve"(e){return e.resolve(this.#e)}};var br=class t{constructor(e,r){this._getRoot=e;this._slotBindings=r}with(e,r){return new t(this._getRoot,[...this._slotBindings,[ae(e)?e.slot:e,r]])}withCompute(e){return new wr(this._getRoot(),this._slotBindings,e)}withVertex(e,r){return new Sr({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 be([]));return new t(this._getRoot,[...this._slotBindings,...r.bindings])}},wr=class{constructor(e,r,n){this._root=e;this._slotBindings=r;this._entryFn=n}createPipeline(){return Nn(this._root,this._slotBindings,this._entryFn)}},Sr=class{constructor(e){this._options=e}withFragment(e,r,n){return re(typeof e!="string","Just type mismatch validation"),re(typeof r!="string","Just type mismatch validation"),new vr({...this._options,fragmentFn:e,targets:r})}},vr=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 Qn(this._options)}},It=class extends br{constructor(r,n,a){super(()=>this,[]);this.device=r;this.nameRegistry=n;this._ownDevice=a;this["~unstable"]=this}"~unstable";_disposables=[];_unwrappedBindGroupLayouts=new Me(r=>r.unwrap(this));_unwrappedBindGroups=new Me(r=>r.unwrap(this));_commandEncoder=null;get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}get enabledFeatures(){return new Set(this.device.features)}createBuffer(r,n){let a=Ge(this,r,n);return this._disposables.push(a),a}createUniform(r,n){let a=Ge(this,r,n).$usage("uniform");return this._disposables.push(a),new me("uniform",a)}createMutable(r,n){let a=Ge(this,r,n).$usage("storage");return this._disposables.push(a),new me("mutable",a)}createReadonly(r,n){let a=Ge(this,r,n).$usage("storage");return this._disposables.push(a),new me("readonly",a)}createQuerySet(r,n,a){return Wn(this,r,n,a)}createBindGroup(r,n){return new ve(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=_n(r,this);return this._disposables.push(n),n}unwrap(r){if(zn(r))return r[p].rawPipeline;if(Hn(r))return r[p].core.unwrap().pipeline;if(Tt(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(sr(r))return this._unwrappedBindGroups.getOrMake(r);if(ee(r))return r.buffer;if(N(r))return r[p].unwrap();if(Ee(r)){if(r[p].unwrap)return r[p].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(Le(r)){if(r[p].unwrap)return r[p].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(vt(r))return r.vertexLayout;if(Ve(r)){if(r[p].unwrap)return r[p].unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if($e(r)){if(r[p].unwrap)return r[p].unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}if(ke(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:l,priors:f}=i[p],g=l.unwrap();a.setPipeline(g.pipeline);let c=new Set(g.usedBindGroupLayouts);g.usedBindGroupLayouts.forEach((x,I)=>{if(g.catchall&&I===g.catchall[0])a.setBindGroup(I,this.unwrap(g.catchall[1])),c.delete(x);else{let w=f.bindGroupLayoutMap?.get(x)??o.get(x);w!==void 0&&(c.delete(x),sr(w)?a.setBindGroup(I,this.unwrap(w)):a.setBindGroup(I,w))}});let y=new Set;if(l.usedVertexLayouts.forEach((x,I)=>{let w=f.vertexLayoutMap?.get(x),S=w?{buffer:w,offset:void 0,size:void 0}:s.get(x);!S||!S.buffer?y.add(x):ee(S.buffer)?a.setVertexBuffer(I,this.unwrap(S.buffer),S.offset,S.size):a.setVertexBuffer(I,S.buffer,S.offset,S.size)}),c.size>0)throw new ne(c);if(y.size>0)throw new Ie(y)};n({setViewport(...l){a.setViewport(...l)},setScissorRect(...l){a.setScissorRect(...l)},setBlendConstant(...l){a.setBlendConstant(...l)},setStencilReference(...l){a.setStencilReference(...l)},beginOcclusionQuery(...l){a.beginOcclusionQuery(...l)},endOcclusionQuery(...l){a.endOcclusionQuery(...l)},executeBundles(...l){a.executeBundles(...l)},setPipeline(l){i=l},setIndexBuffer:(l,f,g,c)=>{ee(l)?a.setIndexBuffer(this.unwrap(l),f,g,c):a.setIndexBuffer(l,f,g,c)},setVertexBuffer(l,f,g,c){s.set(l,{buffer:f,offset:g,size:c})},setBindGroup(l,f){o.set(l,f)},draw(l,f,g,c){u(),a.draw(l,f,g,c)},drawIndexed(...l){u(),a.drawIndexed(...l)},drawIndirect(...l){u(),a.drawIndirect(...l)},drawIndexedIndirect(...l){u(),a.drawIndexedIndirect(...l)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function Kn(t){let{adapter:e,device:r,unstable_names:n="random"}=t??{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let a=await navigator.gpu.requestAdapter(e);if(!a)throw new Error("Could not find a compatible GPU");let o=[];for(let s of r?.requiredFeatures??[]){if(!a.features.has(s))throw new Error(`Requested feature "${s}" is not supported by the adapter.`);o.push(s)}for(let s of r?.optionalFeatures??[])a.features.has(s)?o.push(s):console.warn(`Optional feature "${s}" is not supported by the adapter.`);return new It(await a.requestDevice({...r,requiredFeatures:o}),n==="random"?new ue:new W,!0)}function Yn(t){let{device:e,unstable_names:r="random"}=t??{};return new It(e,r==="random"?new ue:new W,!1)}function Ne(t){return new Ir(t)}var Ir=class{constructor(e=void 0){this.defaultValue=e}[p]=!0;resourceType="slot";$name(e){return T(this,e),this}areEqual(e,r){return Object.is(e,r)}toString(){return`slot:${m(this)??"<unnamed>"}`}[D](e){return Pe(e,e.unwrap(this))}get value(){let e=j();if(!e)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return this[D](e)}get $(){return this.value}};function Jn(t,e){return new Dr(t,e)}var Dr=class{constructor(e,r=void 0){this.schema=e;this.defaultValue=r;this.slot=Ne(r),this[h]=this.slot}[p]=!0;resourceType="accessor";slot;$name(e){return this.slot.$name(e),this}toString(){return`accessor:${m(this)??"<unnamed>"}`}[D](){return new Proxy({"~resolve":e=>e.resolve(this),toString:()=>`.value:${m(this)??"<unnamed>"}`,[b]:this.schema},k)}get value(){if(Te())return this[D]();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}"~resolve"(e){let r=e.unwrap(this.slot);return Lr(r)||hr(r)?e.resolve(r):jt(r)?`${e.resolve(r)}()`:e.resolveValue(r,this.schema)}};function Xn(t){return Wa(t)}function Ma([t,e]){return`${m(t)??"<unnamed>"}=${e}`}function Wa(t){if(j())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{resourceType:"derived","~compute":t,[Ft]:void 0,[Ut]:void 0,[D](r){return Pe(r,r.unwrap(this))},get value(){let r=j();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[D](r)},get $(){return this.value},with(r,n){return Zn(this,[[r,n]])},toString(){return"derived"}}}function Zn(t,e){return{resourceType:"derived",[Ft]:void 0,[Ut]:void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},[G]:{inner:t,pairs:e},[D](n){return Pe(n,n.unwrap(this))},get value(){let n=j();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[D](n)},get $(){return this.value},with(n,a){return Zn(t,[...e,[n,a]])},toString(){return`derived[${e.map(Ma).join(", ")}]`}}}function ea(t,e){return new Dt("private",t,e)}function ta(t){return new Dt("workgroup",t)}var Dt=class{[p]={};#e;#t;#r;constructor(e,r,n){this.#e=e,this.#t=r,this.#r=n}"~resolve"(e){let r=e.names.makeUnique(m(this));return this.#r?e.addDeclaration(`var<${this.#e}> ${r}: ${e.resolve(this.#t)} = ${e.resolveValue(this.#r,this.#t)};`):e.addDeclaration(`var<${this.#e}> ${r}: ${e.resolve(this.#t)};`),r}$name(e){return T(this,e),this}toString(){return`var:${m(this)??"<unnamed>"}`}[D](){return new Proxy({"~resolve":e=>e.resolve(this),toString:()=>`.value:${m(this)??"<unnamed>"}`,[b]:this.#t},k)}get $(){let e=ye(),r=ce();if(e.type==="normal")throw new Ct(r?`Cannot access variable '${m(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[D]():e.type==="simulate"?(e.vars[this.#e].has(this)||e.vars[this.#e].set(this,this.#r),e.vars[this.#e].get(this)):K(e,"tgpuVariable.ts#TgpuVarImpl/$")}set $(e){let r=ye(),n=ce();if(r.type==="normal")throw new Ct(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}K(r,"tgpuVariable.ts#TgpuVarImpl/$")}get value(){return this.$}set value(e){this.$=e}};var Na={fn:qt,bindGroupLayout:yt,vertexLayout:yr,slot:Ne,init:Kn,initFromDevice:Yn,resolve:kn,resolveWithContext:lr,"~unstable":{fn:qt,fragmentFn:yn,vertexFn:Tn,computeFn:gn,vertexLayout:yr,derived:Xn,slot:Ne,accessor:Jn,privateVar:ea,workgroupVar:ta,const:an,declare:sn,sampler:Rn,comparisonSampler:Cn,simulate:Mn}},vl=Na;export{ne as MissingBindGroupsError,Rt as MissingLinksError,Bt as MissingSlotValueError,Ie as MissingVertexBuffersError,At as NotUniformError,de as ResolutionError,vl as default,ee as isBuffer,hr as isBufferShorthand,$e as isComparisonSampler,qe as isDerived,Le as isSampledTextureView,Ve as isSampler,ze as isSlot,Ee as isStorageTextureView,N as isTexture,jt as isTgpuFn,_a as isUsableAsRender,nr as isUsableAsSampled,le as isUsableAsStorage,it as isUsableAsUniform,Va as isUsableAsVertex,Na as tgpu};
31
20
  //# sourceMappingURL=index.js.map