typegpu 0.5.7 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,30 +1,30 @@
1
- import{$ as K,_ as P,a as _,b as Hr,ba as S,c as qr,d as ve,da as at,e as nt,f as Z,g as en,ga as Yt,h as ee,i as $,ia as ut,j as Me,ja as Ie,ka as Qt}from"./chunk-SMTSXYNG.js";import{$ as Ge,A as j,B as z,C as I,D as jt,E as Zr,K as Se,L as rt,M as tn,N as zt,O as De,P as Kt,Q as L,R,S as C,T as f,U as _e,V as O,W as Oe,X as te,Y as re,Z as Ht,_ as fe,a as m,aa as Fe,b,ba as Ae,c as p,ca as qt,d as w,da as F,e as N,ea as We,f as pe,fa as k,g as we,ga as E,h as _t,ha as Jt,i as Ot,ia as rn,j as Gt,ja as ot,k as le,ka as st,l as Ee,la as it,m as Le,n as Kr,o as G,p as Wt,q as Mt,r as de,s as Nt,u as Jr,v as Yr,w as be,x as Qr,y as Xr,z as me}from"./chunk-5RYM4COI.js";function H(e){return e?.resourceType==="slot"}function q(e){return e?.resourceType==="derived"}function Ne(e){return e?.["~providing"]!==void 0}function ge(e){return e?.resourceType==="accessor"}function pt(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var U={type:"unknown"};function je(e){return typeof e?.["~resolve"]=="function"}function J(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||je(e)||j(e)||H(e)||q(e)||Ne(e)}function nn(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function lt(e){return e?.resourceType==="buffer-usage"}function Xt(e){return!!e&&typeof e=="object"&&!!e?.[m]?.dataType}function Zt(e){return!!e?.[m]}var sa=["vec2f","vec2h","vec2i","vec2u","vec2<bool>","vec3f","vec3h","vec3i","vec3u","vec3<bool>","vec4f","vec4h","vec4i","vec4u","vec4<bool>","struct"],ia={f:{1:f,2:O,3:fe,4:F},h:{1:_e,2:Oe,3:Ge,4:We},i:{1:C,2:te,3:Fe,4:k},u:{1:R,2:re,3:Ae,4:E},b:{1:L,2:Ht,3:qt,4:Jt}},an={vec2f:O,vec2h:Oe,vec2i:te,vec2u:re,"vec2<bool>":Ht,vec3f:fe,vec3h:Ge,vec3i:Fe,vec3u:Ae,"vec3<bool>":qt,vec4f:F,vec4h:We,vec4i:k,vec4u:E,"vec4<bool>":Jt,mat2x2f:ot,mat3x3f:st,mat4x4f:it},on={vec2f:f,vec2h:_e,vec2i:C,vec2u:R,"vec2<bool>":L,vec3f:f,vec3h:_e,vec3i:C,vec3u:R,"vec3<bool>":L,vec4f:f,vec4h:_e,vec4i:C,vec4u:R,"vec4<bool>":L,mat2x2f:O,mat3x3f:fe,mat4x4f:F};function ce(e,t){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return U;if(q(e)||H(e)){let o=G();if(!o)throw new Error("Resolution context not found when unwrapping slot or derived");let s=o.unwrap(e);return mt(s)}let r=e;for(Xt(r)&&(r=r[m].dataType);Se(r);)r=r.inner;let n="kind"in r?r.kind:r.type;if(n==="struct")return r.propTypes[t]??U;let a=t.length;if(sa.includes(n)&&a>=1&&a<=4){let o=n.includes("bool")?"b":n[4],s=ia[o][a];if(s)return s}return j(r)?r:U}function er(e){if(j(e)){if(z(e))return e.elementType;if(e.type in on)return on[e.type]}return U}function mt(e){if(Xt(e))return e[m].dataType;if(typeof e=="string")return U;if(typeof e=="number")return ft(String(e))?.dataType??U;if(typeof e=="boolean")return L;if("kind"in e){let t=e.kind;if(t in an)return an[t]}return j(e)||je(e)?e:U}function ft(e){if(/^0x[0-9a-f]+$/i.test(e))return{value:e,dataType:De};if(/^0b[01]+$/i.test(e))return{value:`${Number.parseInt(e.slice(2),2)}`,dataType:De};if(/^-?(?:\d+\.\d*|\d*\.\d+)$/i.test(e))return{value:e,dataType:Kt};if(/^-?\d+(?:\.\d+)?e-?\d+$/i.test(e))return{value:e,dataType:Kt};if(/^-?\d+$/i.test(e))return{value:e,dataType:De}}var tr={rank:Number.POSITIVE_INFINITY,action:"none"};function Ue(e){return e.type==="decorated"?e.inner:e}function sn(e){return be(e)?rn[e.type]:void 0}function dt(e,t){let r=Ue(e),n=Ue(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(be(r)&&be(n)){let a=sn(r),o=sn(n);if(a&&o)return dt(a,o)}return me(r)&&me(n)?{rank:0,action:"none"}:tr}function ua(e,t){let r=Ue(e),n=Ue(t);if(r.type==="ptr"&&dt(r.inner,n).rank<Number.POSITIVE_INFINITY)return{rank:0,action:"deref"};if(n.type==="ptr"&&dt(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,s=n.type;if(o!==s){let i=a[o];return{rank:a[s]<i?10:20,action:"cast",targetType:n}}}return tr}function pa(e,t,r){let n=dt(e,t);return n.rank<Number.POSITIVE_INFINITY?n:r?ua(e,t):tr}function un(e,t,r){let n,a=Number.POSITIVE_INFINITY,o=new Map;for(let u of t){let d=0,g=[],c=!0;for(let y of e){let x=pa(y,u,r);if(x.rank===Number.POSITIVE_INFINITY){c=!1;break}d+=x.rank,g.push(x)}c&&d<a&&(a=d,n=u,o.set(n,g))}if(!n)return;let i=o.get(n).map((u,d)=>({sourceIndex:d,action:u.action,...u.action==="cast"&&{targetType:u.targetType}})),l=i.some(u=>u.action==="cast");return{targetType:n,actions:i,hasImplicitConversions:l}}function rr(e){return e.type==="abstractFloat"?f:e.type==="abstractInt"?C:e}function pn(e,t){if(e.length===0)return;let r=[...new Set(e.map(Ue))],n=t?[...new Set(t.map(Ue))]:r,a=un(e,n,!1);if(a)return a;let o=un(e,n,!0);if(o)return o.hasImplicitConversions=o.actions.some(s=>s.action==="cast"),o}function A(e,t){return J(t.value)?e.resolve(t.value):String(t.value)}function la(e,t,r,n){if(r.action==="none")return{value:t.value,dataType:n};let a=A(e,t);switch(r.action){case"ref":return{value:`&${a}`,dataType:n};case"deref":return{value:`*${a}`,dataType:n};case"cast":return{value:`${e.resolve(n)}(${a})`,dataType:n};default:pt(r.action,"applyActionToSnippet")}}function W(e,t,r){let n=t.map(o=>o.dataType);if(n.some(o=>o===U))return;let a=pn(n,r);if(a)return a.hasImplicitConversions&&console.warn(`Implicit conversions from [
1
+ import{S as V,T as H,V as v,X as st,_ as Yt,a as L,aa as mt,b as Ne,ba as Ue,ca as on}from"./chunk-SFECI7OX.js";import{c as an}from"./chunk-SLWTVY6K.js";import{$ as O,A as qr,Aa as Jt,B as Jr,Ba as nn,C as Y,Ca as ut,D as Yr,Da as pt,E as Qr,Ea as lt,F as Xr,G as me,I as be,J as z,K as A,L as jt,M as Zr,S as ot,T as it,U as Se,V as ve,W as K,X as en,_ as Z,a as f,aa as k,b as S,ba as T,c as I,ca as tn,d as D,da as rn,e as p,ea as zt,f as h,fa as De,g as j,ga as Kt,h as pe,ha as _,i as he,ia as P,j as Gt,ja as C,k as Lt,ka as m,l as Ot,la as Le,m as le,ma as M,n as Ee,na as Oe,o as Ge,oa as ee,p as jr,pa as te,q as X,qa as Ht,r as Mt,ra as de,s as Wt,sa as Me,t as J,ta as Fe,u as zr,ua as Ie,v as Kr,va as qt,w as Nt,wa as B,x as Hr,xa as We,y as we,ya as E,z as at,za as G}from"./chunk-L7HIBZAX.js";function sn(e){if(typeof e?.[I]=="function")return e[I].bind(e)}function dt(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var pa={f:{1:m,2:M,3:de,4:B},h:{1:Le,2:Oe,3:Me,4:We},i:{1:C,2:ee,3:Fe,4:E},u:{1:P,2:te,3:Ie,4:G},b:{1:_,2:Ht,3:qt,4:Jt}},la={vec2f:M,vec2h:Oe,vec2i:ee,vec2u:te,"vec2<bool>":Ht,vec3f:de,vec3h:Me,vec3i:Fe,vec3u:Ie,"vec3<bool>":qt,vec4f:B,vec4h:We,vec4i:E,vec4u:G,"vec4<bool>":Jt,mat2x2f:ut,mat3x3f:pt,mat4x4f:lt},un={vec2f:m,vec2h:Le,vec2i:C,vec2u:P,"vec2<bool>":_,vec3f:m,vec3h:Le,vec3i:C,vec3u:P,"vec3<bool>":_,vec4f:m,vec4h:Le,vec4i:C,vec4u:P,"vec4<bool>":_,mat2x2f:M,mat3x3f:de,mat4x4f:B};function je(e,t){if(A(e)||K(e))return e.propTypes[t]??k;if(e===_||an(e))return k;let r=t.length;if(Y(e)&&r>=1&&r<=4){let n=e.type.includes("bool")?"b":e.type[4],a=pa[n][r];if(a)return a}return k}function Qt(e){return z(e)||ve(e)?e.elementType:e.type in un?un[e.type]:k}function Xt(e){if(/^0x[0-9a-f]+$/i.test(e))return T(e,De);if(/^0b[01]+$/i.test(e))return T(`${Number.parseInt(e.slice(2),2)}`,De);if(/^-?(?:\d+\.\d*|\d*\.\d+)$/i.test(e))return T(e,Kt);if(/^-?\d+(?:\.\d+)?e-?\d+$/i.test(e))return T(e,Kt);if(/^-?\d+$/i.test(e))return T(e,De)}var Zt={rank:Number.POSITIVE_INFINITY,action:"none"};function Ae(e){return e.type==="decorated"?e.inner:e}function pn(e){return Y(e)?nn[e.type]:void 0}function ft(e,t){let r=Ae(e),n=Ae(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(Y(r)&&Y(n)){let a=pn(r),o=pn(n);if(a&&o)return ft(a,o)}return me(r)&&me(n)?{rank:0,action:"none"}:Zt}function ma(e,t){let r=Ae(e),n=Ae(t);if(r.type==="ptr"&&ft(r.inner,n).rank<Number.POSITIVE_INFINITY)return{rank:0,action:"deref"};if(n.type==="ptr"&&ft(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 Zt}function da(e,t,r){let n=ft(e,t);return n.rank<Number.POSITIVE_INFINITY?n:r?ma(e,t):Zt}function ln(e,t,r){let n,a=Number.POSITIVE_INFINITY,o=new Map;for(let u of t){let d=0,g=[],c=!0;for(let y of e){let x=da(y,u,r);if(x.rank===Number.POSITIVE_INFINITY){c=!1;break}d+=x.rank,g.push(x)}c&&d<a&&(a=d,n=u,o.set(n,g))}if(!n)return;let s=o.get(n).map((u,d)=>({sourceIndex:d,action:u.action,...u.action==="cast"&&{targetType:u.targetType}})),l=s.some(u=>u.action==="cast");return{targetType:n,actions:s,hasImplicitConversions:l}}function er(e){return e.type==="abstractFloat"?m:e.type==="abstractInt"?C:e}function mn(e,t){if(e.length===0)return;let r=[...new Set(e.map(Ae))],n=t?[...new Set(t.map(Ae))]:r,a=ln(e,n,!1);if(a)return a;let o=ln(e,n,!0);if(o)return o.hasImplicitConversions=o.actions.some(i=>i.action==="cast"),o}function fa(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:dt(r.action,"applyActionToSnippet")}}function W(e,t,r){let n=t.map(o=>o.dataType);if(n.some(o=>o===k))return;let a=mn(n,r);if(a)return a.hasImplicitConversions&&console.warn(`Implicit conversions from [
2
2
  ${t.map(o=>` ${o.value}: ${o.dataType.type}`).join(`,
3
3
  `)}
4
4
  ] to ${a.targetType.type} are supported, but not recommended.
5
- Consider using explicit conversions instead.`),t.map((o,s)=>{let i=a.actions[s];return pe(i,"Action should not be undefined"),la(e,o,i,a.targetType)})}function nr(e,t,r){return Object.keys(t.propTypes).map(a=>{let o=r[a];if(!o)throw new Error(`Missing property ${a}`);let s=t.propTypes[a];return W(e,[o],[s])?.[0]??o})}function ar(e){if(J(e))return{value:e,dataType:mt(e)};if(Array.isArray(e)){let t=e.map(ar).filter(Boolean),r=G();if(!r)throw new Error("Tried to coerce array without a context");let n=W(r,t),a=pn(t.map(o=>o.dataType))?.targetType;return!n||!a?{value:e,dataType:U}:{value:n.map(o=>o.value).join(", "),dataType:at(rr(a),e.length)}}if(typeof e!="object"){let t=ft(String(e));if(t)return t}return{value:e,dataType:U}}var Y={get(e,t){if(t in e)return Reflect.get(e,t);if(t!=="~providing")return t==="toString"||t===Symbol.toStringTag||t===Symbol.toPrimitive?()=>e.toString():new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>`.value(...).${String(t)}:${p(e)??"<unnamed>"}`,[m]:{dataType:ce(e[m].dataType,String(t))}},Y)}};function ze(e){let t=e;for(;H(t)||q(t)||ge(t)||lt(t);)t=t.value;return t}function ln(e,t){return new or(e,t)}var or=class{constructor(t,r){this.dataType=t;this._value=r;this[m]={dataType:t}}[m];$name(t){return w(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.resolveValue(this._value,this.dataType);return t.addDeclaration(`const ${r} = ${n};`),r}toString(){return`const:${p(this)??"<unnamed>"}`}get value(){return de()?new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[m]:{dataType:this.dataType}},Y):this._value}};function Q(e,t){for(let[r,n]of Object.entries(t))e[r]=n,N(n)&&p(n)===void 0&&n.$name(r)}function dn(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 s=n?n[o]:void 0;return I(a)&&s!==void 0?[[s,a]]:[]})))}function Be(e,t,r){let n=e.match(/->\s(?<output>[\w\d_]+)\s{/),a=n?n[1]?.trim():void 0;I(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function da(e){return new RegExp(`(?<![\\w\\$_.])${e.replaceAll(".","\\.").replaceAll("$","\\$")}(?![\\w\\$_])`,"g")}function ye(e,t,r){return Object.entries(t).reduce((n,[a,o])=>J(o)||ve(o)?n.replaceAll(da(a),e.resolve(o)):o!==null&&typeof o=="object"?([...r.matchAll(new RegExp(`${a.replaceAll(".","\\.").replaceAll("$","\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`,"g"))].map(i=>i[1])??[]).reduce((i,l)=>l&&l in o?ye(e,{[`${a}.${l}`]:o[l]},i):i,n):n,r)}function mn(e){return new sr(e)}var sr=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)Q(r,a);let n=ye(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var fn=new WeakMap;function gn(e){return fn.get(e)}function cn(e,t,r){return fn.set(e,{ast:t,externals:r}),e}function yn(e){return()=>{throw new Error(`The function "${e??"<unnamed>"}" is invokable only on the GPU. If you want to use it on the CPU, mark it with the "kernel & js" directive.`)}}function Ke(e){return typeof e?.format=="string"}function Tn(e,t){let r=[];if($(e)){if(!Ke(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:ee(e)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[s,i]of Object.entries(e)){if(ut(i))continue;let l=t[s];if(!l)throw new Error(`An attribute by the name of '${s}' was not provided to the shader.`);let u=l._layout,d=a.get(u);d||(r.push(u),d=[],n.push({arrayStride:u.stride,stepMode:u.stepMode,attributes:d}),a.set(u,d)),o=ee(i)??o,d.push({format:l.format,offset:l.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var ma=["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 fa(e){return ma.includes(e.type)}function ir(e,[t,r]){return` ${Ie(r)}${t}: ${e.resolve(r)},
6
- `}function ga(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(`
5
+ Consider using explicit conversions instead.`),t.map((o,i)=>{let s=a.actions[i];return pe(s,"Action should not be undefined"),fa(e,o,s,a.targetType)})}function tr(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 W(e,[o],[i])?.[0]??o})}function fe(e){if(tn(e))return e;if(Hr(e))return T(e,e[S]);if(at(e)||Yr(e))return T(e,la[e.kind]);if(Array.isArray(e)){let t=e.map(fe).filter(Boolean),r=X();if(!r)throw new Error("Tried to coerce array without a context");let n=W(r,t),a=mn(t.map(o=>o.dataType))?.targetType;return!n||!a?T(e,k):T(n.map(o=>o.value).join(", "),st(er(a),e.length))}return typeof e=="string"||typeof e=="function"||typeof e=="object"||typeof e=="symbol"||typeof e>"u"||e===null?T(e,k):typeof e=="number"||typeof e=="bigint"?T(e,Xt(String(e))?.dataType??k):typeof e=="boolean"?T(e,_):T(e,k)}var q={get(e,t){if(t in e)return Reflect.get(e,t);if(t!=="~providing")return t==="toString"||t===Symbol.toStringTag||t===Symbol.toPrimitive?()=>e.toString():new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>`.value(...).${String(t)}:${p(e)??"<unnamed>"}`,[S]:je(e[S],String(t))},q)}};function ze(e,t){let r=t,n;for(;n=sn(r);)r=n(e);return r}function dn(e,t){return new rr(e,t)}var rr=class{constructor(t,r){this.dataType=t;this._value=r;this[f]={dataType:t}}[f];$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.resolveValue(this._value,this.dataType);return t.addDeclaration(`const ${r} = ${n};`),r}toString(){return`const:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.dataType},q)}get value(){return J()?this[I]():this._value}};function Be(e){return e?.resourceType==="slot"}function Re(e){return e?.resourceType==="derived"}function Ke(e){return e?.["~providing"]!==void 0}function He(e){return e?.resourceType==="accessor"}function nr(e){return typeof e?.["~resolve"]=="function"}function gt(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||nr(e)||be(e)||Be(e)||Re(e)||Ke(e)}function fn(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function gn(e){return e?.resourceType==="buffer-usage"}function ar(e){return!!e?.[f]}function ge(e,t){for(let[r,n]of Object.entries(t))e[r]=n,j(n)&&p(n)===void 0&&n.$name(r)}function cn(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 A(a)&&i!==void 0?[[i,a]]:[]})))}function Pe(e,t,r){let n=e.match(/->\s(?<output>[\w\d_]+)\s{/),a=n?n[1]?.trim():void 0;A(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function ga(e){return new RegExp(`(?<![\\w\\$_.])${e.replaceAll(".","\\.").replaceAll("$","\\$")}(?![\\w\\$_])`,"g")}function ce(e,t,r){return Object.entries(t).reduce((n,[a,o])=>gt(o)||Se(o)?n.replaceAll(ga(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,l)=>l&&l in o?ce(e,{[`${a}.${l}`]:o[l]},s):s,n):n,r)}function yn(e){return new or(e)}var or=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)ge(r,a);let n=ce(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var Tn=new WeakMap;function xn(e){return Tn.get(e)}function hn(e,t,r){return Tn.set(e,{ast:t,externals:r}),e}function wn(e){return()=>{throw new Error(`The function "${e??"<unnamed>"}" is invokable only on the GPU. If you want to use it on the CPU, mark it with the "kernel & js" directive.`)}}import{FuncParameterType as bn}from"tinyest";function re(e,t){let r=[];typeof t=="string"&&(e.isEntry?(A(e.argTypes[0])&&r.push({In:e.argTypes[0]}),A(e.returnType)&&r.push({Out:e.returnType})):(cn(t,e.argTypes,o=>r.push(o)),Pe(t,e.returnType,o=>r.push(o))));let n={applyExternals(o){r.push(o)},resolve(o,i=""){let s={};for(let u of r)ge(s,u);let l=o.names.makeUnique(p(this));if(typeof t=="string"){let u="";if(e.isEntry){let g=A(e.argTypes[0])?"(in: In)":"()",c=be(e.returnType)?Ue(e.returnType):"",y=e.returnType!==we?A(e.returnType)?"-> Out":`-> ${c!==""?c:"@location(0)"} ${o.resolve(e.returnType)}`:"";u=`${g} ${y} `}let d=ce(o,s,`${u}${t.trim()}`);o.addDeclaration(`${i}fn ${l}${d}`)}else{let u=xn(t);if(u?.externals){let x=Object.fromEntries(Object.entries(u.externals).filter(([w])=>!(w in s)));ge(s,x)}let d=u?.ast??o.transpileFn(String(t)),g=d.externalNames.filter(x=>!(x in s));if(g.length>0)throw new Ot(p(this),g);let{head:c,body:y}=o.fnToWgsl({args:e.argTypes.map((x,w)=>T(d.params[w]?.type===bn.identifier?d.params[w].name:`_arg_${w}`,x)),argAliases:Object.fromEntries(d.params.flatMap((x,w)=>x.type===bn.destructuredObject?x.props.map(({name:b,alias:U})=>[U,T(`_arg_${w}.${b}`,e.argTypes[w].propTypes[b])]):[])),returnType:e.returnType,body:d.body,externalMap:s});o.addDeclaration(`${i}fn ${l}${o.resolve(c)}${o.resolve(y)}`)}return l}},a=p(t);return a!==void 0&&h(n,a),n}function ca(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(mt(n))return[r,n];let a=Z(n);return a!==void 0?(t=a+1,[r,n]):[r,Yt(t++,n)]}))}function ne(e){return O(e)?it(e)||Z(e)!==void 0?e:Yt(0,e):on(ca(e))}function ae(e,...t){return ya(e)?Ta(e,...t):e}function ya(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)&&e.raw.every(t=>typeof t=="string")}function Ta(e,...t){return e.slice(1).reduce((r,n,a)=>`${r}${t[a]}${n}`,e[0])}function Sn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],returnType:we,workgroupSize:[e.workgroupSize[0]??1,e.workgroupSize[1]??1,e.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>xa(t,e.workgroupSize,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function xa(e,t,r){let n=re(e,r),a=e.argTypes[0];return{shell:e,$uses(o){return n.applyExternals(o),this},[D]:n,$name(o){return h(n,o),j(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){return n.resolve(o,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){return`computeFn:${p(n)??"<unnamed>"}`}}}function vn(e,t){let r={[f]:!0,argTypes:e,returnType:t??we,isEntry:!1},n=(a,...o)=>wa(r,ae(a,...o));return Object.assign(Object.assign(n,r),{does:n})}function ir(e){return!!e?.[f]&&e?.resourceType==="function"}function ha([e,t]){return`${p(e)??"<unnamed>"}=${t}`}function wa(e,t){let r=re(e,t),n={[f]:{implementation:t,argTypes:e.argTypes},shell:e,resourceType:"function",$uses(i){return r.applyExternals(i),this},[D]:r,$name(i){return h(r,i),this},with(i,s){return Dn(o,[[He(i)?i.slot:i,s]])},"~resolve"(i){if(typeof t=="string")return r.resolve(i);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)}finally{s.callStack.pop()}}},a=zt((...i)=>{if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...i)},(...i)=>T(new ct(o,i.map(s=>s.value)),e.returnType??k),e.argTypes);a[f].implementation=t;let o=Object.assign(a,n);return Object.defineProperty(o,"toString",{value(){return`fn:${p(r)??"<unnamed>"}`}}),o}function Dn(e,t){let r={[f]:{implementation:e[f].implementation,argTypes:e[f].argTypes},resourceType:"function",shell:e.shell,"~providing":{inner:e,pairs:t},$uses(o){return e.$uses(o),this},[D]:e,$name(o){return e.$name(o),this},with(o,i){return Dn(a,[...t,[He(o)?o.slot:o,i]])}},n=zt((...o)=>e(...o),(...o)=>T(new ct(a,o.map(i=>i.value)),e.shell.returnType??k),e.shell.argTypes),a=Object.assign(n,r);return Object.defineProperty(a,"toString",{value(){return`fn:${p(e)??"<unnamed>"}[${t.map(ha).join(", ")}]`}}),a[f].implementation=e[f].implementation,a}var ct=class{constructor(t,r){this._fn=t;this._params=r;this[D]=t}[D];"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){return`call:${p(this)??"<unnamed>"}`}};function Fn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],targets:e.out,returnType:ne(e.out),isEntry:!0},r=(n,...a)=>ba(t,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function ba(e,t){let r=re(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Pe(t,n,i=>r.applyExternals(i)),{shell:e,outputType:n,$uses(i){return r.applyExternals(i),this},[D]:r,$name(i){return h(r,i),j(n)&&n.$name(`${i}_Output`),j(a)&&a.$name(`${i}_Input`),this},"~resolve"(i){if(typeof t=="string")return r.resolve(i,"@fragment ");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(n),r.resolve(i,"@fragment ")}finally{s.callStack.pop()}},toString(){return`fragmentFn:${p(r)??"<unnamed>"}`}}}function In(e){let t={attributes:[e.in??{}],returnType:Object.keys(e.out).length!==0?ne(e.out):void 0,argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],isEntry:!0},r=(n,...a)=>Sa(t,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Sa(e,t){let r=re(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Pe(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,inputType:a,$uses(o){return r.applyExternals(o),this},[D]:r,$name(o){return h(r,o),j(n)&&n.$name(`${o}_Output`),j(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){if(typeof t=="string")return r.resolve(o,"@vertex ");let i=o;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(n),r.resolve(o,"@vertex ")}finally{i.callStack.pop()}},toString(){return`vertexFn:${p(r)??"<unnamed>"}`}}}var oe=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++}`}},ie=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 qe(e){return typeof e?.format=="string"}function Un(e,t){let r=[];if(O(e)){if(!qe(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:Z(e)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[i,s]of Object.entries(e)){if(mt(s))continue;let l=t[i];if(!l)throw new Error(`An attribute by the name of '${i}' was not provided to the shader.`);let u=l._layout,d=a.get(u);d||(r.push(u),d=[],n.push({arrayStride:u.stride,stepMode:u.stepMode,attributes:d}),a.set(u,d)),o=Z(s)??o,d.push({format:l.format,offset:l.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var va=["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 Da(e){return va.includes(e.type)}function sr(e,[t,r]){return` ${Ue(r)}${t}: ${e.resolve(r)},
6
+ `}function Fa(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(`
7
7
  struct ${r} {
8
- ${Object.entries(t.propTypes).map(n=>ir(e,n)).join("")}}
9
- `),r}function ca(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(`
8
+ ${Object.entries(t.propTypes).map(n=>sr(e,n)).join("")}}
9
+ `),r}function Ia(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(`
10
10
  struct ${r} {
11
- ${Object.entries(t.propTypes).map(n=>Ke(n[1])?ir(e,[n[0],Me[n[1].format]]):ir(e,n)).join("")}
11
+ ${Object.entries(t.propTypes).map(n=>qe(n[1])?sr(e,[n[0],Ne[n[1].format]]):sr(e,n)).join("")}
12
12
  }
13
- `),r}function ya(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Ta(e,t){let r=e.resolve(Ke(t.elementType)?Me[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function ur(e,t){if(ve(t))return t.type==="unstruct"?ca(e,t):t.type==="disarray"?Ta(e,t):t.type==="loose-decorated"?e.resolve(Ke(t.inner)?Me[t.inner.format]:t.inner):e.resolve(Me[t.type]);if(fa(t))return t.type;if(t.type==="struct")return ga(e,t);if(t.type==="array")return ya(e,t);if(t.type==="atomic")return`atomic<${ur(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner)}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner)}>`;if(t.type==="abstractInt"||t.type==="abstractFloat")throw new Error("Abstract types have no concrete representation in WGSL");if(t.type==="void")throw new Error("Void has no representation in WGSL");pt(t,"resolveData")}import{BufferReader as cr,BufferWriter as yr,getSystemEndianness as Sa}from"typed-binary";import{Measurer as ha}from"typed-binary";function xa(e,t){let r="size"in e?e.size:e.currentByteOffset,n=t-1,a=r&n;"skipBytes"in e?e.skipBytes(t-a&n):e.add(t-a&n)}var B=xa;var xn=new WeakMap;function gt(e){let t=xn.get(e);if(t)return t;let r=new ha,n={},a;for(let o in e.propTypes){let s=e.propTypes[o];if(s===void 0)throw new Error(`Property ${o} is undefined in struct`);let i=r.size;B(r,Z(e)?K(s):P(s)),a&&(a.padding=r.size-i);let l=S(s);n[o]={offset:r.size,size:l},a=n[o],r.add(l)}return a&&(a.padding=_(S(e),P(e))-r.size),xn.set(e,n),n}var yt=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),pr=new WeakMap,lr={u32:"u32",vec2u:"u32",vec3u:"u32",vec4u:"u32",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"};function ct(e,t,r){if(Zr(e)||Se(e))return ct(e.inner,t,r);if(I(e)||Z(e)){let a=gt(e),o=Object.entries(a).sort((i,l)=>i[1].offset-l[1].offset),s="";for(let[i,l]of o){let u=e.propTypes[i];u&&(s+=ct(u,`(${t} + ${l.offset})`,`${r}.${i}`))}return s}if(z(e)||nt(e)){let a=e,o=_(S(a.elementType),P(a.elementType)),s="";return s+=`for (let i = 0; i < ${a.elementCount}; i++) {
14
- `,s+=ct(a.elementType,`(${t} + i * ${o})`,`${r}[i]`),s+=`}
15
- `,s}if(be(e)){let a=lr[e.type],o="",s=dr[a],i=["x","y","z","w"],l=Jr(e)?2:Yr(e)?3:4;for(let u=0;u<l;u++)o+=`output.${s}((${t} + ${u*4}), ${r}.${i[u]}, littleEndian);
16
- `;return o}if(me(e)){let a=lr[e.type],o=dr[a],s=Qr(e)?2:Xr(e)?3:4,i=s*s,l=_(s*4,8),u="";for(let d=0;d<i;d++){let g=Math.floor(d/s),c=d%s,y=g*l+c*4;u+=`output.${o}((${t} + ${y}), ${r}.columns[${g}].${["x","y","z","w"][c]}, littleEndian);
17
- `}return u}let n=lr[e.type];return`output.${dr[n]}(${t}, ${r}, littleEndian);
18
- `}function Tt(e){if(pr.has(e))return pr.get(e);let t=ct(e,"offset","value"),r=new Function("output","offset","value","littleEndian=true",t);return pr.set(e,r),r}var Re={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)},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=P(t);B(e,n);for(let[a,o]of Object.entries(t.propTypes))B(e,P(o)),ne(e,o,r[a]);B(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=P(t);B(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)B(e,n),ne(e,t.elementType,r[o]);e.seekTo(a+S(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){Re[t.inner.type]?.(e,t,r)},decorated(e,t,r){let n=K(t);B(e,n);let a=e.currentByteOffset;Re[t.inner?.type]?.(e,t.inner,r),e.seekTo(a+S(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=P(t);B(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)B(e,n),Re[t.elementType?.type]?.(e,t.elementType,r[o]);e.seekTo(a+S(t))},unstruct(e,t,r){for(let[n,a]of Object.entries(t.propTypes))Re[a.type]?.(e,a,r[n])},"loose-decorated"(e,t,r){let n=K(t);B(e,n);let a=e.currentByteOffset,o=Re[t.inner?.type];return o?.(e,t.inner,r),e.seekTo(a+S(t)),r}};function ne(e,t,r){let n=Re[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var Te={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()},vec2f(e){return O(e.readFloat32(),e.readFloat32())},vec3f(e){return fe(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Oe(e.readFloat16(),e.readFloat16())},vec3h(e){return Ge(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return We(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return te(e.readInt32(),e.readInt32())},vec3i(e){return Fe(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return k(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return re(e.readUint32(),e.readUint32())},vec3u(e){return Ae(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return E(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 ot(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return st(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return it(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=P(t);B(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))B(e,P(o)),n[a]=M(e,o);return B(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=P(t),n=[];for(let a=0;a<t.elementCount;a++){B(e,r);let o=t.elementType,s=M(e,o);n.push(s)}return B(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return M(e,t.inner)},decorated(e,t){let r=K(t);B(e,r);let n=e.currentByteOffset,a=M(e,t.inner);return e.seekTo(n+S(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>re(e.readUint8(),e.readUint8()),uint8x4:e=>E(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>te(e.readInt8(),e.readInt8()),sint8x4:e=>k(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>O(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=>O((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=>re(e.readUint16(),e.readUint16()),uint16x4:e=>E(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>te(e.readInt16(),e.readInt16()),sint16x4:e=>k(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>O(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=>O(Te.snorm16(e),Te.snorm16(e)),snorm16x4:e=>F(Te.snorm16(e),Te.snorm16(e),Te.snorm16(e),Te.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>O(e.readFloat16(),e.readFloat16()),float16x4:e=>F(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>O(e.readFloat32(),e.readFloat32()),float32x3:e=>fe(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>F(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>re(e.readUint32(),e.readUint32()),uint32x3:e=>Ae(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>E(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>te(e.readInt32(),e.readInt32()),sint32x3:e=>Fe(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>k(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]=M(e,a);return r},disarray(e,t){let r=P(t),n=[];for(let a=0;a<t.elementCount;a++)B(e,r),n.push(M(e,t.elementType));return B(e,r),n},"loose-decorated"(e,t){B(e,K(t));let r=e.currentByteOffset,n=M(e,t.inner);return e.seekTo(r+S(t)),n}};function M(e,t){let r=Te[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as ba}from"typed-binary";function hn(e,t){let r=S(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new ba(n),o=[];function s(u,d,g,c){if(d!=null){if(I(u)||Z(u)){let y=gt(u);for(let[x,h]of Object.entries(y)){let T=u.propTypes[x];if(!T)continue;let D=d[x];D!==void 0&&s(T,D,g+h.offset,h.padding??c)}return}if(z(u)||nt(u)){let y=u,x=_(S(y.elementType),P(y.elementType));if(!Array.isArray(d))throw new Error("Partial value for array must be an array");let h=d??[];h.sort((T,D)=>T.idx-D.idx);for(let{idx:T,value:D}of h)s(y.elementType,D,g+T*x,x-S(y.elementType))}else{let y=S(u);a.seekTo(g),ne(a,u,d),o.push({start:g,end:g+y,padding:c})}}}if(s(e,t,0),o.length===0)return[];let i=[],l=o[0];for(let u=1;u<o.length;u++){let d=o[u];if(!d||!l)throw new Error("Internal error: missing segment");d.start===l.end+(l.padding??0)?(l.end=d.end,l.padding=d.padding):(i.push({data:new Uint8Array(n,l.start,l.end-l.start)}),l=d)}if(!l)throw new Error("Internal error: missing segment");return i.push({data:new Uint8Array(n,l.start,l.end-l.start)}),i}function xe(e){return!!e?.usableAsStorage}var He=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function xt(e){return!!e.usableAsUniform}var vn={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},qe=class{constructor(t,r){this.usage=t;this.buffer=r;this[m]={dataType:r.dataType},this[b]=r}resourceType="buffer-usage";[m];[b];$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}write(t){this.buffer.write(t)}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}get value(){if(!de())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[m]:{dataType:this.buffer.dataType}},Y)}},Je=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;this[m]={dataType:r},w(this,n.key)}resourceType="buffer-usage";[m];"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}get value(){if(!de())throw new Error("Cannot access buffer's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[m]:{dataType:this.dataType}},Y)}},wn=new WeakMap;function mr(e){if(!xe(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=wn.get(e);return t||(t=new qe("mutable",e),wn.set(e,t)),t}var bn=new WeakMap;function fr(e){if(!xe(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=bn.get(e);return t||(t=new qe("readonly",e),bn.set(e,t)),t}var Sn=new WeakMap;function gr(e){if(!xt(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=Sn.get(e);return t||(t=new qe("uniform",e),Sn.set(e,t)),t}var va={uniform:gr,mutable:mr,readonly:fr};function Fn(e,t,r){return j(t)?new ht(e,t,r):new ht(e,t,r,["storage","uniform"])}function ae(e){return e.resourceType==="buffer"}function Da(e){return!!e.usableAsVertex}var Dn=Sa(),ht=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;nn(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}resourceType="buffer";flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC;_buffer=null;_ownBuffer;_destroyed=!1;_hostBuffer;initial;usableAsUniform=!1;usableAsStorage=!1;usableAsVertex=!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:S(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:p(this)??"<unnamed>"}),this.initial)){let r=new yr(this._buffer.getMappedRange());ne(r,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(t){return w(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.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex"}return this}$addFlags(t){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return t&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):t&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=t,this)}compileWriter(){if(yt)Tt(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(yt){Tt(this.dataType)(new DataView(o),0,t,Dn==="little");return}ne(new yr(o),this.dataType,t);return}let a=S(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(a)),this._group.flush(),yt?Tt(this.dataType)(new DataView(this._hostBuffer),0,t,Dn==="little"):ne(new yr(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=hn(this.dataType,t);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(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=S(this.dataType);this._group.commandEncoder.copyBufferToBuffer(t.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let t=this.buffer,r=this._group.device;if(t.mapState==="mapped"){let s=t.getMappedRange();return M(new cr(s),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let s=t.getMappedRange(),i=M(new cr(s),this.dataType);return t.unmap(),i}let n=r.createBuffer({size:S(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,S(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,S(this.dataType));let o=M(new cr(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){return va[t]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${p(this)??"<unnamed>"}`}};function An(e){return new Tr(e)}function In(e){return new xr(e)}function Ye(e){let t=e;return t?.resourceType==="sampler"&&!!t[m]}function Qe(e){let t=e;return t?.resourceType==="sampler-comparison"&&!!t[m]}var wt=class{constructor(t){this._membership=t;this[m]={},w(this,t.key)}[m];resourceType="sampler";"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},bt=class{constructor(t){this._membership=t;this[m]={},w(this,t.key)}[m];resourceType="sampler-comparison";"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}},Tr=class{constructor(t){this._props=t;this[m]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)},this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}[m];resourceType="sampler";_filtering;_sampler=null;$name(t){return w(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}},xr=class{constructor(t){this._props=t;this[m]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)}}[m];resourceType="sampler-comparison";_sampler=null;$name(t){return w(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}};var St=class{constructor(t){this._membership=t;w(this,t.key)}resourceType="external-texture";"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}};var Un={r8unorm:f,r8snorm:f,r8uint:R,r8sint:C,r16uint:R,r16sint:C,r16float:f,rg8unorm:f,rg8snorm:f,rg8uint:R,rg8sint:C,r32uint:R,r32sint:C,r32float:f,rg16uint:R,rg16sint:C,rg16float:f,rgba8unorm:f,"rgba8unorm-srgb":f,rgba8snorm:f,rgba8uint:R,rgba8sint:C,bgra8unorm:f,"bgra8unorm-srgb":f,rgb9e5ufloat:f,rgb10a2uint:R,rgb10a2unorm:f,rg11b10ufloat:f,rg32uint:R,rg32sint:C,rg32float:f,rgba16uint:R,rgba16sint:C,rgba16float:f,rgba32uint:R,rgba32sint:C,rgba32float:f,stencil8:f,depth16unorm:f,depth24plus:f,"depth24plus-stencil8":f,depth32float:f,"depth32float-stencil8":f,"bc1-rgba-unorm":f,"bc1-rgba-unorm-srgb":f,"bc2-rgba-unorm":f,"bc2-rgba-unorm-srgb":f,"bc3-rgba-unorm":f,"bc3-rgba-unorm-srgb":f,"bc4-r-unorm":f,"bc4-r-snorm":f,"bc5-rg-unorm":f,"bc5-rg-snorm":f,"bc6h-rgb-ufloat":f,"bc6h-rgb-float":f,"bc7-rgba-unorm":f,"bc7-rgba-unorm-srgb":f,"etc2-rgb8unorm":f,"etc2-rgb8unorm-srgb":f,"etc2-rgb8a1unorm":f,"etc2-rgb8a1unorm-srgb":f,"etc2-rgba8unorm":f,"etc2-rgba8unorm-srgb":f,"eac-r11unorm":f,"eac-r11snorm":f,"eac-rg11unorm":f,"eac-rg11snorm":f,"astc-4x4-unorm":f,"astc-4x4-unorm-srgb":f,"astc-5x4-unorm":f,"astc-5x4-unorm-srgb":f,"astc-5x5-unorm":f,"astc-5x5-unorm-srgb":f,"astc-6x5-unorm":f,"astc-6x5-unorm-srgb":f,"astc-6x6-unorm":f,"astc-6x6-unorm-srgb":f,"astc-8x5-unorm":f,"astc-8x5-unorm-srgb":f,"astc-8x6-unorm":f,"astc-8x6-unorm-srgb":f,"astc-8x8-unorm":f,"astc-8x8-unorm-srgb":f,"astc-10x5-unorm":f,"astc-10x5-unorm-srgb":f,"astc-10x6-unorm":f,"astc-10x6-unorm-srgb":f,"astc-10x8-unorm":f,"astc-10x8-unorm-srgb":f,"astc-10x10-unorm":f,"astc-10x10-unorm-srgb":f,"astc-12x10-unorm":f,"astc-12x10-unorm-srgb":f,"astc-12x12-unorm":f,"astc-12x12-unorm-srgb":f},Xe={rgba8unorm:F,rgba8snorm:F,rgba8uint:E,rgba8sint:k,rgba16uint:E,rgba16sint:k,rgba16float:F,r32uint:E,r32sint:k,r32float:F,rg32uint:E,rg32sint:k,rg32float:F,rgba32uint:E,rgba32sint:k,rgba32float:F,bgra8unorm:F},Bn={f32:"float",u32:"uint",i32:"sint"},Rn={float:f,"unfilterable-float":f,uint:R,sint:C,depth:f};function Cn(e,t){return new hr(e,t)}function X(e){return e?.resourceType==="texture"&&!!e[m]}function Ze(e){return e?.resourceType==="texture-storage-view"&&!!e[m]}function et(e){return e?.resourceType==="texture-sampled-view"&&!!e[m]}var Pn={mutable:"read_write",readonly:"read",writeonly:"write"},hr=class{constructor(t,r){this.props=t;this._branch=r;this[m]={unwrap:()=>{if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:p(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}}}[m];resourceType="texture";usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;_destroyed=!1;_flags=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;_texture=null;$name(t){return w(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=Xe[n];return pe(!!a,`Unsupported storage texture format: ${n}`),new wr(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(!Xe[r])throw new Error(`Unsupported storage texture format: ${r}`);return new br(t,this)}destroy(){this._destroyed||(this._destroyed=!0,this._texture?.destroy())}},Ft={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},wr=class{constructor(t,r,n){this.access=r;this._texture=n;this[m]={unwrap:()=>(this._view||(this._view=this._texture[m].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view)},this[b]=n,this.dimension=t?.dimension??n.props.dimension??"2d",this._format=t?.format??n.props.format,this.texelDataType=Xe[this._format]}[m];[b];resourceType="texture-storage-view";texelDataType;dimension;_view;_format;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Ft[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${Pn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},vt=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;this[m]={},this.texelDataType=Xe[this._format],w(this,a.key)}[m];resourceType="texture-storage-view";texelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Ft[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${Pn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},br=class{constructor(t,r){this._props=t;this._texture=r;this[m]={unwrap:()=>(this._view||(this._view=this._texture[m].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,...this._props})),this._view)},this[b]=r,this.dimension=t?.dimension??r.props.dimension??"2d",this._format=t?.format??r.props.format,this.channelDataType=Un[this._format]}[m];[b];resourceType="texture-sampled-view";channelDataType;dimension;_format;_view;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=(this._texture.props.sampleCount??1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:Bn[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),s=n?"texture_multisampled_2d":`texture_${Ft[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${s}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},Dt=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;this[m]={},w(this,a.key),this.channelDataType=Rn[t]}[m];resourceType="texture-sampled-view";channelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Ft[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}};function Sr(e){return!!e?.usableAsSampled}function Fa(e){return!!e?.usableAsRender}var At=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function It(e){return new Dr(e)}function Ut(e){return!!e&&e.resourceType==="bind-group-layout"}function Fr(e){return!!e&&e.resourceType==="bind-group"}var vr=class e extends Error{constructor(t,r){super(`Bind group '${t??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},Vn=["compute"],Ce=["compute","vertex","fragment"],Dr=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 Je("uniform",a.uniform,o)),"storage"in a){let s="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Je(a.access??"readonly",s,o)}"texture"in a&&(this.bound[n]=new Dt(a.texture,a.viewDimension??"2d",a.multisampled??!1,o)),"storageTexture"in a&&(this.bound[n]=new vt(a.storageTexture,a.viewDimension??"2d",a.access??"writeonly",o)),"externalTexture"in a&&(this.bound[n]=new St(o)),"sampler"in a&&(a.sampler==="comparison"?this.bound[n]=new bt(o):this.bound[n]=new wt(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++}}_index;resourceType="bind-group-layout";bound={};value={};$=this.value;toString(){return`bindGroupLayout:${p(this)??"<unnamed>"}`}get index(){return this._index}$name(t){return w(this,t),this}$idx(t){return this._index=t,this}unwrap(t){return t.device.createBindGroupLayout({label:p(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??Ce,s.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?Vn:Ce),s.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??Ce,s.sampler={type:n.sampler};else if("texture"in n)o=o??Ce,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"?Ce:Vn),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??Ce,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)})}},Pe=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 vr(p(t),n)}resourceType="bind-group";unwrap(t){return t.device.createBindGroup({label:p(this.layout)??"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([n,a],o)=>{if(a===null)return null;let s=this.entries[n];if(s===void 0)throw new Error(`'${n}' is a resource required to populate bind group layout '${p(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let i;if(ae(s)){if(!xt(s))throw new Ot(s);i={buffer:t.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("storage"in a){let i;if(ae(s)){if(!xe(s))throw new He(s);i={buffer:t.unwrap(s)}}else i={buffer:s};return{binding:o,resource:i}}if("texture"in a){let i;if(X(s)){if(!Sr(s))throw new At(s);i=t.unwrap(s.createView("sampled"))}else et(s)?i=t.unwrap(s):i=s;return{binding:o,resource:i}}if("storageTexture"in a){let i;if(X(s)){if(!xe(s))throw new He(s);a.access==="readonly"?i=t.unwrap(s.createView("readonly")):a.access==="mutable"?i=t.unwrap(s.createView("mutable")):i=t.unwrap(s.createView("writeonly"))}else Ze(s)?i=t.unwrap(s):i=s;return{binding:o,resource:i}}if("sampler"in a)return Ye(s)||Qe(s)?{binding:o,resource:t.unwrap(s)}:{binding:o,resource:s};if("externalTexture"in a)return{binding:o,resource:s};throw new Error(`Malformed bind group entry: ${s} (${JSON.stringify(s)})`)}).filter(n=>n!==null)})}};import*as Aa from"tinyest";var{NodeTypeCatalog:v}=Aa,Ia=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"],Ua=["&&","||","==","!=","<","<=",">",">="];function $n(e,t,r){return r?Ua.includes(t)?L:t==="="?r:e:t==="!"||t==="~"?L:e}function Ba(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function kn(e,t){return{value:t?"true":"false",dataType:L}}function En(e,[t,r]){e.pushBlockScope();try{return`${e.indent()}{
19
- ${r.map(n=>he(e,n)).join(`
13
+ `),r}function Ua(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Aa(e,t){let r=e.resolve(qe(t.elementType)?Ne[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function ur(e,t){if(Se(t))return t.type==="unstruct"?Ia(e,t):t.type==="disarray"?Aa(e,t):t.type==="loose-decorated"?e.resolve(qe(t.inner)?Ne[t.inner.format]:t.inner):e.resolve(Ne[t.type]);if(Da(t))return t.type;if(t.type==="struct")return Fa(e,t);if(t.type==="array")return Ua(e,t);if(t.type==="atomic")return`atomic<${ur(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner)}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner)}>`;if(t.type==="abstractInt"||t.type==="abstractFloat")throw new Error("Abstract types have no concrete representation in WGSL");if(t.type==="void")throw new Error("Void has no representation in WGSL");dt(t,"resolveData")}import{BufferReader as cr,BufferWriter as yr,getSystemEndianness as Va}from"typed-binary";import{Measurer as Ra}from"typed-binary";function Ba(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 R=Ba;var An=new WeakMap;function yt(e){let t=An.get(e);if(t)return t;let r=new Ra,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;R(r,K(e)?H(i):V(i)),a&&(a.padding=r.size-s);let l=v(i);n[o]={offset:r.size,size:l},a=n[o],r.add(l)}return a&&(a.padding=L(v(e),V(e))-r.size),An.set(e,n),n}var xt=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),pr=new WeakMap,lr={u32:"u32",vec2u:"u32",vec3u:"u32",vec4u:"u32",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"},mr={u32:"setUint32",i32:"setInt32",f32:"setFloat32"};function Tt(e,t,r){if(Zr(e)||ot(e))return Tt(e.inner,t,r);if(A(e)||K(e)){let a=yt(e),o=Object.entries(a).sort((s,l)=>s[1].offset-l[1].offset),i="";for(let[s,l]of o){let u=e.propTypes[s];u&&(i+=Tt(u,`(${t} + ${l.offset})`,`${r}.${s}`))}return i}if(z(e)||ve(e)){let a=e,o=L(v(a.elementType),V(a.elementType)),i="";return i+=`for (let i = 0; i < ${a.elementCount}; i++) {
14
+ `,i+=Tt(a.elementType,`(${t} + i * ${o})`,`${r}[i]`),i+=`}
15
+ `,i}if(Y(e)){let a=lr[e.type],o="",i=mr[a],s=["x","y","z","w"],l=qr(e)?2:Jr(e)?3:4;for(let u=0;u<l;u++)o+=`output.${i}((${t} + ${u*4}), ${r}.${s[u]}, littleEndian);
16
+ `;return o}if(me(e)){let a=lr[e.type],o=mr[a],i=Qr(e)?2:Xr(e)?3:4,s=i*i,l=L(i*4,8),u="";for(let d=0;d<s;d++){let g=Math.floor(d/i),c=d%i,y=g*l+c*4;u+=`output.${o}((${t} + ${y}), ${r}.columns[${g}].${["x","y","z","w"][c]}, littleEndian);
17
+ `}return u}let n=lr[e.type];return`output.${mr[n]}(${t}, ${r}, littleEndian);
18
+ `}function ht(e){if(pr.has(e))return pr.get(e);let t=Tt(e,"offset","value"),r=new Function("output","offset","value","littleEndian=true",t);return pr.set(e,r),r}var Ce={bool(){throw new Error("Booleans are not host-shareable")},f32(e,t,r){e.writeFloat32(r)},f16(e,t,r){e.writeFloat16(r)},i32(e,t,r){e.writeInt32(r)},u32(e,t,r){e.writeUint32(r)},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=V(t);R(e,n);for(let[a,o]of Object.entries(t.propTypes))R(e,V(o)),se(e,o,r[a]);R(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=V(t);R(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)R(e,n),se(e,t.elementType,r[o]);e.seekTo(a+v(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){Ce[t.inner.type]?.(e,t,r)},decorated(e,t,r){let n=H(t);R(e,n);let a=e.currentByteOffset;Ce[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=V(t);R(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)R(e,n),Ce[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))Ce[a.type]?.(e,a,r[n])},"loose-decorated"(e,t,r){let n=H(t);R(e,n);let a=e.currentByteOffset,o=Ce[t.inner?.type];return o?.(e,t.inner,r),e.seekTo(a+v(t)),r}};function se(e,t,r){let n=Ce[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var ye={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()},vec2f(e){return M(e.readFloat32(),e.readFloat32())},vec3f(e){return de(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return B(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Oe(e.readFloat16(),e.readFloat16())},vec3h(e){return Me(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return We(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return ee(e.readInt32(),e.readInt32())},vec3i(e){return Fe(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return E(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return te(e.readUint32(),e.readUint32())},vec3u(e){return Ie(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return G(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 ut(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return pt(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return lt(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},struct(e,t){let r=V(t);R(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))R(e,V(o)),n[a]=N(e,o);return R(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=V(t),n=[];for(let a=0;a<t.elementCount;a++){R(e,r);let o=t.elementType,i=N(e,o);n.push(i)}return R(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return N(e,t.inner)},decorated(e,t){let r=H(t);R(e,r);let n=e.currentByteOffset,a=N(e,t.inner);return e.seekTo(n+v(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>te(e.readUint8(),e.readUint8()),uint8x4:e=>G(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>ee(e.readInt8(),e.readInt8()),sint8x4:e=>E(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>M(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>B(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>(e.readUint8()-128)/127,snorm8x2:e=>M((e.readUint8()-128)/127,(e.readUint8()-128)/127),snorm8x4:e=>B((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>te(e.readUint16(),e.readUint16()),uint16x4:e=>G(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>ee(e.readInt16(),e.readInt16()),sint16x4:e=>E(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>M(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>B(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>M(ye.snorm16(e),ye.snorm16(e)),snorm16x4:e=>B(ye.snorm16(e),ye.snorm16(e),ye.snorm16(e),ye.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>M(e.readFloat16(),e.readFloat16()),float16x4:e=>B(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>M(e.readFloat32(),e.readFloat32()),float32x3:e=>de(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>B(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>te(e.readUint32(),e.readUint32()),uint32x3:e=>Ie(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>G(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>ee(e.readInt32(),e.readInt32()),sint32x3:e=>Fe(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>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 B(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 B(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=N(e,a);return r},disarray(e,t){let r=V(t),n=[];for(let a=0;a<t.elementCount;a++)R(e,r),n.push(N(e,t.elementType));return R(e,r),n},"loose-decorated"(e,t){R(e,H(t));let r=e.currentByteOffset,n=N(e,t.inner);return e.seekTo(r+v(t)),n}};function N(e,t){let r=ye[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as Ca}from"typed-binary";function Bn(e,t){let r=v(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new Ca(n),o=[];function i(u,d,g,c){if(d!=null){if(A(u)||K(u)){let y=yt(u);for(let[x,w]of Object.entries(y)){let b=u.propTypes[x];if(!b)continue;let U=d[x];U!==void 0&&i(b,U,g+w.offset,w.padding??c)}return}if(z(u)||ve(u)){let y=u,x=L(v(y.elementType),V(y.elementType));if(!Array.isArray(d))throw new Error("Partial value for array must be an array");let w=d??[];w.sort((b,U)=>b.idx-U.idx);for(let{idx:b,value:U}of w)i(y.elementType,U,g+b*x,x-v(y.elementType))}else{let y=v(u);a.seekTo(g),se(a,u,d),o.push({start:g,end:g+y,padding:c})}}}if(i(e,t,0),o.length===0)return[];let s=[],l=o[0];for(let u=1;u<o.length;u++){let d=o[u];if(!d||!l)throw new Error("Internal error: missing segment");d.start===l.end+(l.padding??0)?(l.end=d.end,l.padding=d.padding):(s.push({data:new Uint8Array(n,l.start,l.end-l.start)}),l=d)}if(!l)throw new Error("Internal error: missing segment");return s.push({data:new Uint8Array(n,l.start,l.end-l.start)}),s}function Te(e){return!!e?.usableAsStorage}var Je=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function wt(e){return!!e.usableAsUniform}var Vn={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Ye=class{constructor(t,r){this.usage=t;this.buffer=r;this[f]={dataType:r.dataType},this[D]=r}resourceType="buffer-usage";[f];[D];$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}write(t){this.buffer.write(t)}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.buffer.dataType},q)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[I]()}},Qe=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;this[f]={dataType:r},h(this,n.key)}resourceType="buffer-usage";[f];"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=Vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.dataType},q)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[I]()}},Rn=new WeakMap;function dr(e){if(!Te(e))throw new Error(`Cannot pass ${e} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Rn.get(e);return t||(t=new Ye("mutable",e),Rn.set(e,t)),t}var Pn=new WeakMap;function fr(e){if(!Te(e))throw new Error(`Cannot pass ${e} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Pn.get(e);return t||(t=new Ye("readonly",e),Pn.set(e,t)),t}var Cn=new WeakMap;function gr(e){if(!wt(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=Cn.get(e);return t||(t=new Ye("uniform",e),Cn.set(e,t)),t}var $a={uniform:gr,mutable:dr,readonly:fr};function kn(e,t,r){return be(t)?new bt(e,t,r):new bt(e,t,r,["storage","uniform"])}function ue(e){return e.resourceType==="buffer"}function ka(e){return!!e.usableAsVertex}var $n=Va(),bt=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;fn(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}resourceType="buffer";flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC;_buffer=null;_ownBuffer;_destroyed=!1;_hostBuffer;initial;usableAsUniform=!1;usableAsStorage=!1;usableAsVertex=!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:p(this)??"<unnamed>"}),this.initial)){let r=new yr(this._buffer.getMappedRange());se(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.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex"}return this}$addFlags(t){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return t&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):t&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=t,this)}compileWriter(){if(xt)ht(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(xt){ht(this.dataType)(new DataView(o),0,t,$n==="little");return}se(new yr(o),this.dataType,t);return}let a=v(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(a)),this._group.flush(),xt?ht(this.dataType)(new DataView(this._hostBuffer),0,t,$n==="little"):se(new yr(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=Bn(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 N(new cr(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),s=N(new cr(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=N(new cr(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){return $a[t]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${p(this)??"<unnamed>"}`}};function _n(e){return new Tr(e)}function En(e){return new xr(e)}function Xe(e){let t=e;return t?.resourceType==="sampler"&&!!t[f]}function Ze(e){let t=e;return t?.resourceType==="sampler-comparison"&&!!t[f]}var St=class{constructor(t){this._membership=t;this[S]=this,this[f]={},h(this,t.key)}[S];[f];resourceType="sampler";"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},vt=class{constructor(t){this._membership=t;this[S]=this,this[f]={},h(this,t.key)}[S];[f];resourceType="sampler-comparison";"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}},Tr=class{constructor(t){this._props=t;this[S]=this,this[f]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)},this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}[S];[f];resourceType="sampler";_filtering;_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}},xr=class{constructor(t){this._props=t;this[S]=this,this[f]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)}}[S];[f];resourceType="sampler-comparison";_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}};var Dt=class{constructor(t){this._membership=t;h(this,t.key)}resourceType="external-texture";"~resolve"(t){let r=t.names.makeUnique(p(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}:${p(this)??"<unnamed>"}`}};var Gn={r8unorm:m,r8snorm:m,r8uint:P,r8sint:C,r16uint:P,r16sint:C,r16float:m,rg8unorm:m,rg8snorm:m,rg8uint:P,rg8sint:C,r32uint:P,r32sint:C,r32float:m,rg16uint:P,rg16sint:C,rg16float:m,rgba8unorm:m,"rgba8unorm-srgb":m,rgba8snorm:m,rgba8uint:P,rgba8sint:C,bgra8unorm:m,"bgra8unorm-srgb":m,rgb9e5ufloat:m,rgb10a2uint:P,rgb10a2unorm:m,rg11b10ufloat:m,rg32uint:P,rg32sint:C,rg32float:m,rgba16uint:P,rgba16sint:C,rgba16float:m,rgba32uint:P,rgba32sint:C,rgba32float:m,stencil8:m,depth16unorm:m,depth24plus:m,"depth24plus-stencil8":m,depth32float:m,"depth32float-stencil8":m,"bc1-rgba-unorm":m,"bc1-rgba-unorm-srgb":m,"bc2-rgba-unorm":m,"bc2-rgba-unorm-srgb":m,"bc3-rgba-unorm":m,"bc3-rgba-unorm-srgb":m,"bc4-r-unorm":m,"bc4-r-snorm":m,"bc5-rg-unorm":m,"bc5-rg-snorm":m,"bc6h-rgb-ufloat":m,"bc6h-rgb-float":m,"bc7-rgba-unorm":m,"bc7-rgba-unorm-srgb":m,"etc2-rgb8unorm":m,"etc2-rgb8unorm-srgb":m,"etc2-rgb8a1unorm":m,"etc2-rgb8a1unorm-srgb":m,"etc2-rgba8unorm":m,"etc2-rgba8unorm-srgb":m,"eac-r11unorm":m,"eac-r11snorm":m,"eac-rg11unorm":m,"eac-rg11snorm":m,"astc-4x4-unorm":m,"astc-4x4-unorm-srgb":m,"astc-5x4-unorm":m,"astc-5x4-unorm-srgb":m,"astc-5x5-unorm":m,"astc-5x5-unorm-srgb":m,"astc-6x5-unorm":m,"astc-6x5-unorm-srgb":m,"astc-6x6-unorm":m,"astc-6x6-unorm-srgb":m,"astc-8x5-unorm":m,"astc-8x5-unorm-srgb":m,"astc-8x6-unorm":m,"astc-8x6-unorm-srgb":m,"astc-8x8-unorm":m,"astc-8x8-unorm-srgb":m,"astc-10x5-unorm":m,"astc-10x5-unorm-srgb":m,"astc-10x6-unorm":m,"astc-10x6-unorm-srgb":m,"astc-10x8-unorm":m,"astc-10x8-unorm-srgb":m,"astc-10x10-unorm":m,"astc-10x10-unorm-srgb":m,"astc-12x10-unorm":m,"astc-12x10-unorm-srgb":m,"astc-12x12-unorm":m,"astc-12x12-unorm-srgb":m},et={rgba8unorm:B,rgba8snorm:B,rgba8uint:G,rgba8sint:E,rgba16uint:G,rgba16sint:E,rgba16float:B,r32uint:G,r32sint:E,r32float:B,rg32uint:G,rg32sint:E,rg32float:B,rgba32uint:G,rgba32sint:E,rgba32float:B,bgra8unorm:B},Ln={f32:"float",u32:"uint",i32:"sint"},On={float:m,"unfilterable-float":m,uint:P,sint:C,depth:m};function Mn(e,t){return new hr(e,t)}function Q(e){return e?.resourceType==="texture"&&!!e[f]}function tt(e){return e?.resourceType==="texture-storage-view"&&!!e[f]}function rt(e){return e?.resourceType==="texture-sampled-view"&&!!e[f]}var Wn={mutable:"read_write",readonly:"read",writeonly:"write"},hr=class{constructor(t,r){this.props=t;this._branch=r;this[f]={unwrap:()=>{if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:p(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}}}[f];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=et[n];return pe(!!a,`Unsupported storage texture format: ${n}`),new wr(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(!et[r])throw new Error(`Unsupported storage texture format: ${r}`);return new br(t,this)}destroy(){this._destroyed||(this._destroyed=!0,this._texture?.destroy())}},Ut={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},wr=class{constructor(t,r,n){this.access=r;this._texture=n;this[S]=this,this[f]={unwrap:()=>(this._view||(this._view=this._texture[f].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view)},this[D]=n,this.dimension=t?.dimension??n.props.dimension??"2d",this._format=t?.format??n.props.format,this.texelDataType=et[this._format]}[S];[f];[D];resourceType="texture-storage-view";texelDataType;dimension;_view;_format;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${Wn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},Ft=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;this[S]=this,this[f]={},this.texelDataType=et[this._format],h(this,a.key)}[S];[f];resourceType="texture-storage-view";texelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${Wn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},br=class{constructor(t,r){this._props=t;this._texture=r;this[S]=this,this[f]={unwrap:()=>(this._view||(this._view=this._texture[f].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,...this._props})),this._view)},this[D]=r,this.dimension=t?.dimension??r.props.dimension??"2d",this._format=t?.format??r.props.format,this.channelDataType=Gn[this._format]}[S];[f];[D];resourceType="texture-sampled-view";channelDataType;dimension;_format;_view;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=(this._texture.props.sampleCount??1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:Ln[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},It=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;this[S]=this,this[f]={},h(this,a.key),this.channelDataType=On[t]}[S];[f];resourceType="texture-sampled-view";channelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}};function Sr(e){return!!e?.usableAsSampled}function _a(e){return!!e?.usableAsRender}var At=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Bt(e){return new Dr(e)}function Rt(e){return!!e&&e.resourceType==="bind-group-layout"}function Fr(e){return!!e&&e.resourceType==="bind-group"}var vr=class e extends Error{constructor(t,r){super(`Bind group '${t??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},Nn=["compute"],Ve=["compute","vertex","fragment"],Dr=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 Qe("uniform",a.uniform,o)),"storage"in a){let i="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Qe(a.access??"readonly",i,o)}"texture"in a&&(this.bound[n]=new It(a.texture,a.viewDimension??"2d",a.multisampled??!1,o)),"storageTexture"in a&&(this.bound[n]=new Ft(a.storageTexture,a.viewDimension??"2d",a.access??"writeonly",o)),"externalTexture"in a&&(this.bound[n]=new Dt(o)),"sampler"in a&&(a.sampler==="comparison"?this.bound[n]=new vt(o):this.bound[n]=new St(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++}}_index;resourceType="bind-group-layout";bound={};value={};$=this.value;toString(){return`bindGroupLayout:${p(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:p(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??Ve,i.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?Nn:Ve),i.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??Ve,i.sampler={type:n.sampler};else if("texture"in n)o=o??Ve,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"?Ve:Nn),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??Ve,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)})}},$e=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 vr(p(t),n)}resourceType="bind-group";unwrap(t){return t.device.createBindGroup({label:p(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 '${p(this.layout)??"<unnamed>"}'.`);if("uniform"in a){let s;if(ue(i)){if(!wt(i))throw new Lt(i);s={buffer:t.unwrap(i)}}else s={buffer:i};return{binding:o,resource:s}}if("storage"in a){let s;if(ue(i)){if(!Te(i))throw new Je(i);s={buffer:t.unwrap(i)}}else s={buffer:i};return{binding:o,resource:s}}if("texture"in a){let s;if(Q(i)){if(!Sr(i))throw new At(i);s=t.unwrap(i.createView("sampled"))}else rt(i)?s=t.unwrap(i):s=i;return{binding:o,resource:s}}if("storageTexture"in a){let s;if(Q(i)){if(!Te(i))throw new Je(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 tt(i)?s=t.unwrap(i):s=i;return{binding:o,resource:s}}if("sampler"in a)return Xe(i)||Ze(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 Ea from"tinyest";var{NodeTypeCatalog:F}=Ea,Ga=["==","!=","<","<=",">",">=","<<",">>","+","-","*","/","%","|","^","&","&&","||"],La=["&&","||","==","!=","<","<=",">",">="];function jn(e,t,r){return r?La.includes(t)?_:t==="="?r:e:t==="!"||t==="~"?_:e}function Oa(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function zn(e,[t,r]){e.pushBlockScope();try{return`${e.indent()}{
19
+ ${r.map(n=>xe(e,n)).join(`
20
20
  `)}
21
- ${e.dedent()}}`}finally{e.popBlockScope()}}function Ra(e,t,r){return e.defineVariable(t,r)}function Ar(e,t){let r=e.getById(t);if(!r)throw new Error(`Identifier ${t} not found`);return r}function V(e,t){if(typeof t=="string")return Ar(e,t);if(typeof t=="boolean")return kn(e,t);if(t[0]===v.logicalExpr||t[0]===v.binaryExpr||t[0]===v.assignmentExpr){let[r,n,a,o]=t,s=V(e,n),i=V(e,o),l=W(e,[s,i]),[u,d]=l||[s,i],g=A(e,u),c=A(e,d),y=$n(u.dataType,a,d.dataType);return{value:Ia.includes(a)?`(${g} ${a} ${c})`:`${g} ${a} ${c}`,dataType:y}}if(t[0]===v.postUpdate){let[r,n,a]=t,o=V(e,a);return{value:`${A(e,o)}${n}`,dataType:o.dataType}}if(t[0]===v.unaryExpr){let[r,n,a]=t,o=V(e,a),s=A(e,o),i=$n(o.dataType,n);return{value:`${n}${s}`,dataType:i}}if(t[0]===v.memberAccess){let[r,n,a]=t,o=V(e,n);if(jt(o.dataType))return{value:`(*${o.value}).${a}`,dataType:$(o.dataType.inner)?ce(o.dataType.inner,a):U};if(typeof o.value=="string")return{value:`${o.value}.${a}`,dataType:$(o.dataType)?ce(o.dataType,a):U};if(z(o.dataType)&&a==="length")return o.dataType.elementCount===0?{value:`arrayLength(&${e.resolve(o.value)})`,dataType:R}:{value:String(o.dataType.elementCount),dataType:De};let s=o.value[a];if(o.dataType.type!=="unknown")return me(o.dataType)&&a==="columns"?{value:o.value,dataType:o.dataType}:{value:s,dataType:ce(o.dataType,a)};if(J(o.value))return{value:s,dataType:ce(o.value,a)};if(typeof o.value=="object"){let i=J(s)?mt(s):U;return{value:s,dataType:i}}throw new Error(`Cannot access member ${a} of ${o.value}`)}if(t[0]===v.indexAccess){let[r,n,a]=t,o=V(e,n),s=V(e,a),i=A(e,o),l=A(e,s);return jt(o.dataType)?{value:`(*${i})[${l}]`,dataType:$(o.dataType.inner)?er(o.dataType.inner):U}:{value:`${i}[${l}]`,dataType:$(o.dataType)?er(o.dataType):U}}if(t[0]===v.numericLiteral){let r=ft(t[1]);if(!r)throw new Error(`Invalid numeric literal ${t[1]}`);return r}if(t[0]===v.call){let[r,n,a]=t,o=V(e,n),s=o.value;e.callStack.push(s);let i=a.map(y=>V(e,y)),l=i.map(y=>({value:A(e,y),dataType:y.dataType})),u=l.map(y=>y.value);if(e.callStack.pop(),typeof s=="string")return{value:`${s}(${u.join(", ")})`,dataType:o.dataType};if(I(s))return{value:`${e.resolve(s)}(${u.join(", ")})`,dataType:o.dataType};if(!Zt(s))throw new Error(`Function ${String(s)} has not been created using TypeGPU APIs. Did you mean to wrap the function with tgpu.fn(args, return)(...) ?`);let d=s[m]?.argTypes,g;!d||d==="keep"?g=l:d==="coerce"?g=W(e,l)??l:g=(Array.isArray(d)?d.map((x,h)=>[x,l[h]]).filter(([,x])=>!!x):typeof d=="function"?d(...l).map((x,h)=>[x,l[h]]).filter(([,x])=>!!x):Object.entries(d).map(([x,h])=>{let T=(i[0]?.value)[x];if(!T)throw new Error(`Missing argument ${x} in function call`);return[h,T]})).map(([x,h])=>{let T=W(e,[h],[x])?.[0];if(!T)throw new Error(`Cannot convert ${e.resolve(h.dataType)} to ${e.resolve(x)}`);return T});let c=s(...g);return{value:A(e,c),dataType:c.dataType}}if(t[0]===v.objectExpr){let r=t[1],n=e.callStack[e.callStack.length-1];if(I(n)){let a=Object.keys(n.propTypes),o=Object.fromEntries(a.map(i=>{let l=r[i];if(l===void 0)throw new Error(`Missing property ${i} in object literal for struct ${n}`);return[i,V(e,l)]}));return{value:nr(e,n,o).map(i=>A(e,i)).join(", "),dataType:n}}if(Zt(n)){let a=n[m]?.argTypes;if(typeof a=="object"&&a!==null){let o=Object.keys(a),s={};for(let i of o){let l=r[i];if(l===void 0)throw new Error(`Missing property ${i} in object literal for function ${n}`);let u=V(e,l),d=a[i],g=W(e,[u],[d]);s[i]=g?.[0]??u}return{value:s,dataType:U}}}throw new Error("Object expressions are only allowed as return values of functions or as arguments to structs.")}if(t[0]===v.arrayExpr){let[r,n]=t,a=n.map(g=>V(e,g));if(a.length===0)throw new Error("Cannot create empty array literal.");let o=W(e,a);if(!o)throw new Error("The given values cannot be automatically converted to a common type. Consider explicitly casting them.");let s=o[0]?.dataType,i=s.type==="abstractFloat"?f:s.type==="abstractInt"?C:s,u=`array<${e.resolve(i)}, ${a.length}>`,d=o.map(g=>A(e,g));return{value:`${u}( ${d.join(", ")} )`,dataType:at(i,a.length)}}if(t[0]===v.stringLiteral)throw new Error("Cannot use string literals in TGSL.");if(t[0]===v.preUpdate)throw new Error("Cannot use pre-updates in TGSL.");Ba(t)}function Bt(e){return typeof e!="object"||e[0]!==v.block?[v.block,[e]]:e}function he(e,t){if(typeof t=="string")return`${e.pre}${A(e,Ar(e,t))};`;if(typeof t=="boolean")return`${e.pre}${A(e,kn(e,t))};`;if(t[0]===v.return){let r=t[1],n=r!==void 0?A(e,V(e,r)):void 0;if(I(e.callStack[e.callStack.length-1])&&typeof r=="object"&&r[0]===v.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]===v.if){let[r,n,a,o]=t,s=V(e,n),i=s,l=W(e,[s],[L]);l?.[0]&&([i]=l);let u=A(e,i);e.indent();let d=he(e,Bt(a));e.dedent(),e.indent();let g=o?he(e,Bt(o)):void 0;return e.dedent(),g?`${e.pre}if (${u})
21
+ ${e.dedent()}}`}finally{e.popBlockScope()}}function Ma(e,t,r){return e.defineVariable(t,r)}function Ir(e,t){let r=e.getById(t);if(!r)throw new Error(`Identifier ${t} not found`);return r}function $(e,t){if(typeof t=="string")return Ir(e,t);if(typeof t=="boolean")return T(t?"true":"false",_);if(t[0]===F.logicalExpr||t[0]===F.binaryExpr||t[0]===F.assignmentExpr){let[r,n,a,o]=t,i=$(e,n),s=$(e,o),l=W(e,[i,s]),[u,d]=l||[i,s],g=e.resolve(u.value),c=e.resolve(d.value),y=jn(u.dataType,a,d.dataType);return T(Ga.includes(a)?`(${g} ${a} ${c})`:`${g} ${a} ${c}`,y)}if(t[0]===F.postUpdate){let[r,n,a]=t,o=$(e,a),i=e.resolve(o.value);return T(`${i}${n}`,o.dataType)}if(t[0]===F.unaryExpr){let[r,n,a]=t,o=$(e,a),i=e.resolve(o.value),s=jn(o.dataType,n);return T(`${n}${i}`,s)}if(t[0]===F.memberAccess){let[r,n,a]=t,o=$(e,n);if(o.dataType.type==="unknown"){let i=o.value[a];return fe(i)}return jt(o.dataType)?T(`(*${e.resolve(o.value)}).${a}`,je(o.dataType.inner,a)):z(o.dataType)&&a==="length"?o.dataType.elementCount===0?T(`arrayLength(&${e.resolve(o.value)})`,P):T(String(o.dataType.elementCount),De):me(o.dataType)&&a==="columns"?T(o.value,o.dataType):Y(o.dataType)&&at(o.value)?fe(o.value[a]):T(`${e.resolve(o.value)}.${a}`,je(o.dataType,a))}if(t[0]===F.indexAccess){let[r,n,a]=t,o=$(e,n),i=$(e,a),s=e.resolve(o.value),l=e.resolve(i.value);if(o.dataType.type==="unknown"){if(Array.isArray(a)&&a[0]===F.numericLiteral)return fe(o.value[a[1]]);throw new Error(`Cannot index value ${s} of unknown type with index ${l}`)}return jt(o.dataType)?T(`(*${s})[${l}]`,Qt(o.dataType.inner)):T(`${s}[${l}]`,O(o.dataType)?Qt(o.dataType):k)}if(t[0]===F.numericLiteral){let r=Xt(t[1]);if(!r)throw new Error(`Invalid numeric literal ${t[1]}`);return r}if(t[0]===F.call){let[r,n,a]=t,o=$(e,n);e.callStack.push(o.value);let s=a.map(c=>$(e,c)).map(c=>T(e.resolve(c.value),c.dataType)),l=s.map(c=>c.value);if(e.callStack.pop(),s.forEach((c,y)=>{if(c.dataType===k)throw new Error(`Tried to pass '${c.value}' of unknown type as argument #${y} to '${typeof o.value=="string"?o.value:p(o.value)??"<unnamed>"}()'`)}),typeof o.value=="string")return T(`${o.value}(${l.join(", ")})`,o.dataType);if(A(o.value)){let c=e.resolve(o.value);return T(`${c}(${l.join(", ")})`,o.value)}if(!ar(o.value))throw new Error(`Function ${String(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[f]?.argTypes,d;!u||u==="keep"?d=s:u==="coerce"?d=W(e,s)??s:d=(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 w=W(e,[x],[y])?.[0];if(!w)throw new Error(`Cannot convert ${e.resolve(x.dataType)} to ${e.resolve(y)}`);return w});let g=o.value(...d);return T(e.resolve(g.value),g.dataType)}if(t[0]===F.objectExpr){let r=t[1],n=e.callStack[e.callStack.length-1];if(A(n)){let a=Object.keys(n.propTypes),o=Object.fromEntries(a.map(s=>{let l=r[s];if(l===void 0)throw new Error(`Missing property ${s} in object literal for struct ${n}`);return[s,$(e,l)]})),i=tr(e,n,o);return T(i.map(s=>e.resolve(s.value)).join(", "),n)}if(ar(n)){let a=n[f]?.argTypes;if(typeof a=="object"&&a!==null){let o=Object.keys(a),i={};for(let s of o){let l=r[s];if(l===void 0)throw new Error(`Missing property ${s} in object literal for function ${n}`);let u=$(e,l),d=a[s],g=W(e,[u],[d]);i[s]=g?.[0]??u}return T(i,k)}}throw new Error("Object expressions are only allowed as return values of functions or as arguments to structs.")}if(t[0]===F.arrayExpr){let[r,n]=t,a=n.map(g=>$(e,g));if(a.length===0)throw new Error("Cannot create empty array literal.");let o=W(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"?m:i.type==="abstractInt"?C:i,u=`array<${e.resolve(s)}, ${a.length}>`,d=o.map(g=>e.resolve(g.value));return T(`${u}( ${d.join(", ")} )`,st(s,a.length))}if(t[0]===F.stringLiteral)throw new Error("Cannot use string literals in TGSL.");if(t[0]===F.preUpdate)throw new Error("Cannot use pre-updates in TGSL.");Oa(t)}function Pt(e){return typeof e!="object"||e[0]!==F.block?[F.block,[e]]:e}function xe(e,t){if(typeof t=="string")return`${e.pre}${e.resolve(Ir(e,t).value)};`;if(typeof t=="boolean")return`${e.pre}${t?"true":"false"};`;if(t[0]===F.return){let r=t[1],n=r!==void 0?e.resolve($(e,r).value):void 0;if(A(e.callStack[e.callStack.length-1])&&typeof r=="object"&&r[0]===F.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]===F.if){let[r,n,a,o]=t,i=$(e,n),s=i,l=W(e,[i],[_]);l?.[0]&&([s]=l);let u=e.resolve(s.value);e.indent();let d=xe(e,Pt(a));e.dedent(),e.indent();let g=o?xe(e,Pt(o)):void 0;return e.dedent(),g?`${e.pre}if (${u})
22
22
  ${d}
23
23
  ${e.pre}else
24
24
  ${g}`:`${e.pre}if (${u})
25
- ${d}`}if(t[0]===v.let||t[0]===v.const){let[r,n,a]=t,o=a!==void 0?V(e,a):void 0;if(!o)throw new Error(`Cannot create variable '${n}' without an initial value.`);if(ve(o.dataType))throw new Error(`Cannot create variable '${n}' with loose data type.`);Ra(e,n,rr(o.dataType));let s=A(e,Ar(e,n));if(typeof a=="object"&&a[0]===v.objectExpr&&I(e.callStack[e.callStack.length-1])){let i=e.callStack[e.callStack.length-1],l=a[1],u={};for(let[c,y]of Object.entries(l)){if(!y)throw new Error(`Missing property ${c} in object literal`);u[c]=V(e,y)}let d=nr(e,i,u),g=e.resolve(i);return`${e.pre}var ${s} = ${g}(${d.map(c=>A(e,c)).join(", ")});`}return`${e.pre}var ${s} = ${A(e,o)};`}if(t[0]===v.block)return En(e,t);if(t[0]===v.for){let[r,n,a,o,s]=t,i=n?he(e,n):void 0,l=i?i.slice(0,-1):"",u=a?V(e,a):void 0,d=u;if(u){let h=W(e,[u],[L]);h?.[0]&&([d]=h)}let g=d?A(e,d):"",c=o?he(e,o):void 0,y=c?c.slice(0,-1):"";e.indent();let x=he(e,Bt(s));return e.dedent(),`${e.pre}for (${l}; ${g}; ${y})
26
- ${x}`}if(t[0]===v.while){let[r,n,a]=t,o=V(e,n),s=o;if(o){let u=W(e,[o],[L]);u?.[0]&&([s]=u)}let i=A(e,s);e.indent();let l=he(e,Bt(a));return e.dedent(),`${e.pre}while (${i})
27
- ${l}`}return t[0]===v.continue?`${e.pre}continue;`:t[0]===v.break?`${e.pre}break;`:`${e.pre}${A(e,V(e,t))};`}function Ln(e,t){return En(e,t)}var _n="#CATCHALL#",Ur=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){this._stack.push({type:"functionScope",args:t,returnType:r,externalMap:n})}popFunctionScope(){this.pop("functionScope")}pushBlockScope(){this._stack.push({type:"blockScope",declarations:new Map})}popBlockScope(){this.pop("blockScope")}pop(t){let r=this._stack[this._stack.length-1];if(!r||t&&r.type!==t)throw new Error(`Internal error, expected a ${t} layer to be on top.`);this._stack.pop(),t==="item"&&this._itemDepth--}readSlot(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="item")n.usedSlots.add(t);else if(n?.type==="slotBinding"){let a=n.bindingMap.get(t);if(a!==void 0)return a}else if(!(n?.type==="functionScope"||n?.type==="blockScope"))throw new Error("Unknown layer type.")}return t.defaultValue}getSnippetById(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if(n?.type==="functionScope"){let a=n.args.find(s=>s.value===t);if(a!==void 0)return a;let o=n.externalMap[t];return o!=null?ar(o):void 0}if(n?.type==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return{value:t,dataType:a}}}}defineBlockVariable(t,r){for(let n=this._stack.length-1;n>=0;--n){let a=this._stack[n];if(a?.type==="blockScope")return a.declarations.set(t,r),{value:t,dataType:r}}throw new Error("No block scope found to define a variable in.")}},Rt=[""," "," "," "," "," "," "," "," "],Ir=Rt.length-1,Br=class{identLevel=0;get pre(){return Rt[this.identLevel]??Rt[Ir].repeat(this.identLevel/Ir)+Rt[this.identLevel%Ir]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Rr=class{_memoizedResolves=new WeakMap;_memoizedDerived=new WeakMap;_indentController=new Br;_jitTranspiler;_itemStateStack=new Ur;_declarations=[];[m]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];callStack=[];names;constructor(t){this.names=t.names,this._jitTranspiler=t.jitTranspiler}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){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()}transpileFn(t){if(!this._jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._jitTranspiler.transpileFn(t)}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.returnType,t.externalMap);try{return{head:Cr(this,t.args,t.returnType),body:Ln(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:_n,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new _t(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.popSlotBindings()}}unwrap(t){if(Ne(t))return this.withSlots(t["~providing"].pairs,()=>this.unwrap(t["~providing"].inner));let r=t;for(;;)if(H(r))r=this.readSlot(r);else if(q(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(([i,l])=>i.areEqual(this._itemStateStack.readSlot(i),l)))return o.result;Wt(Le.CPU);let n;try{n=t["~compute"]()}finally{Mt(Le.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 we?n.appendToTrace(t):new we(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(([i,l])=>i.areEqual(this._itemStateStack.readSlot(i),l)))return o.result;let n;$(t)?n=ur(this,t):q(t)||H(t)?n=this.resolve(this.unwrap(t)):je(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 we?n.appendToTrace(t):new we(n,[t])}finally{this._itemStateStack.popItem()}}resolve(t){if(Ne(t))return this.withSlots(t["~providing"].pairs,()=>this.resolve(t["~providing"].inner));if(t&&typeof t=="object"||typeof t=="function"){if(this._itemStateStack.itemDepth===0)try{Wt(Le.GPU);let r=Kr(this,()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
25
+ ${d}`}if(t[0]===F.let||t[0]===F.const){let[r,n,a]=t,o=a!==void 0?$(e,a):void 0;if(!o)throw new Error(`Cannot create variable '${n}' without an initial value.`);if(Se(o.dataType))throw new Error(`Cannot create variable '${n}' with loose data type.`);Ma(e,n,er(o.dataType));let i=e.resolve(Ir(e,n).value);if(typeof a=="object"&&a[0]===F.objectExpr&&A(e.callStack[e.callStack.length-1])){let s=e.callStack[e.callStack.length-1],l=a[1],u={};for(let[c,y]of Object.entries(l)){if(!y)throw new Error(`Missing property ${c} in object literal`);u[c]=$(e,y)}let d=tr(e,s,u),g=e.resolve(s);return`${e.pre}var ${i} = ${g}(${d.map(c=>e.resolve(c.value)).join(", ")});`}return`${e.pre}var ${i} = ${e.resolve(o.value)};`}if(t[0]===F.block)return zn(e,t);if(t[0]===F.for){let[r,n,a,o,i]=t,s=n?xe(e,n):void 0,l=s?s.slice(0,-1):"",u=a?$(e,a):void 0,d=u;if(u){let w=W(e,[u],[_]);w?.[0]&&([d]=w)}let g=d?e.resolve(d.value):"",c=o?xe(e,o):void 0,y=c?c.slice(0,-1):"";e.indent();let x=xe(e,Pt(i));return e.dedent(),`${e.pre}for (${l}; ${g}; ${y})
26
+ ${x}`}if(t[0]===F.while){let[r,n,a]=t,o=$(e,n),i=o;if(o){let u=W(e,[o],[_]);u?.[0]&&([i]=u)}let s=e.resolve(i.value);e.indent();let l=xe(e,Pt(a));return e.dedent(),`${e.pre}while (${s})
27
+ ${l}`}return t[0]===F.continue?`${e.pre}continue;`:t[0]===F.break?`${e.pre}break;`:`${e.pre}${e.resolve($(e,t).value)};`}function Kn(e,t){return zn(e,t)}var Hn="#CATCHALL#",Ar=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?fe(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.")}},Ct=[""," "," "," "," "," "," "," "," "],Ur=Ct.length-1,Br=class{identLevel=0;get pre(){return Ct[this.identLevel]??Ct[Ur].repeat(this.identLevel/Ur)+Ct[this.identLevel%Ur]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Rr=class{_memoizedResolves=new WeakMap;_memoizedDerived=new WeakMap;_indentController=new Br;_jitTranspiler;_itemStateStack=new Ar;_declarations=[];[f]={itemStateStack:this._itemStateStack};bindGroupLayoutsToPlaceholderMap=new Map;_nextFreeLayoutPlaceholderIdx=0;fixedBindings=[];callStack=[];names;constructor(t){this.names=t.names,this._jitTranspiler=t.jitTranspiler}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){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()}transpileFn(t){if(!this._jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._jitTranspiler.transpileFn(t)}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.argAliases,t.returnType,t.externalMap);try{return{head:Wa(this,t.args,t.returnType),body:Kn(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:Hn,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new Gt(t);return r}withSlots(t,r){this._itemStateStack.pushSlotBindings(t);try{return r()}finally{this._itemStateStack.popSlotBindings()}}unwrap(t){if(Ke(t))return this.withSlots(t["~providing"].pairs,()=>this.unwrap(t["~providing"].inner));let r=t;for(;;)if(Be(r))r=this.readSlot(r);else if(Re(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,l])=>s.areEqual(this._itemStateStack.readSlot(s),l)))return o.result;Mt(Ge.CPU);let n;try{n=t["~compute"]()}finally{Wt(Ge.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 he?n.appendToTrace(t):new he(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,l])=>s.areEqual(this._itemStateStack.readSlot(s),l)))return o.result;let n;O(t)?n=ur(this,t):Re(t)||Be(t)?n=this.resolve(this.unwrap(t)):nr(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 he?n.appendToTrace(t):new he(n,[t])}finally{this._itemStateStack.popItem()}}resolve(t){if(Ke(t))return this.withSlots(t["~providing"].pairs,()=>this.resolve(t["~providing"].inner));if(t&&typeof t=="object"||typeof t=="function"){if(this._itemStateStack.itemDepth===0)try{Mt(Ge.GPU);let r=jr(this,()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
28
28
 
29
- `)}${r}`}finally{Mt(Le.GPU)}return this._getOrInstantiate(t)}return String(t)}resolveValue(t,r){if(J(t))return this.resolve(t);if(r&&z(r))return`array(${t.map(n=>this.resolveValue(n,r.elementType))})`;if(Array.isArray(t))return`array(${t.map(n=>this.resolveValue(n))})`;if(r&&I(r))return`${this.resolve(r)}(${Object.entries(r.propTypes).map(([n,a])=>this.resolveValue(t[n],a))})`;throw new Error(`Value ${t} (as json: ${JSON.stringify(t)}) of schema ${r} is not resolvable to WGSL`)}};function Ve(e,t){let r=new Rr(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],s=new Set([...a.keys()].map(g=>g.index).filter(g=>g!==void 0)),i=tn(s),l=r.fixedBindings.map((g,c)=>[String(c),g.layoutEntry]),u=()=>{let g=i.next().value,c=It(Object.fromEntries(l));return o[g]=c,n=n.replaceAll(_n,String(g)),[g,new Pe(c,Object.fromEntries(r.fixedBindings.map((y,x)=>[String(x),y.resource])))]},d=l.length>0?u():null;for(let[g,c]of a.entries()){let y=g.index??i.next().value;o[y]=g,n=n.replaceAll(c,String(y))}return{code:n,bindGroupLayouts:o,catchall:d}}function Cr(e,t,r){let n=t.map(a=>`${a.value}: ${e.resolve(a.dataType)}`).join(", ");return r!==void 0?`(${n}) -> ${Ie(r)} ${e.resolve(r)}`:`(${n})`}function oe(e,t){let r=[];typeof t=="string"&&(e.isEntry?(Array.isArray(e.argTypes)&&I(e.argTypes[0])&&r.push({In:e.argTypes[0]}),I(e.returnType)&&r.push({Out:e.returnType})):Array.isArray(e.argTypes)&&(dn(t,Array.isArray(e.argTypes)?e.argTypes:Object.values(e.argTypes),o=>r.push(o)),Be(t,e.returnType,o=>r.push(o))));let n={applyExternals(o){r.push(o)},resolve(o,s=""){let i={};for(let u of r)Q(i,u);let l=o.names.makeUnique(p(this));if(typeof t=="string"){let u="";if(!e.isEntry)u=Array.isArray(e.argTypes)?"":Cr(o,Object.entries(e.argTypes).map(([g,c])=>({value:g,dataType:c})),e.returnType);else{let g=Array.isArray(e.argTypes)&&I(e.argTypes[0])?"(in: In)":"()",c=j(e.returnType)?Ie(e.returnType):"",y=e.returnType!==void 0?I(e.returnType)?"-> Out":`-> ${c!==""?c:"@location(0)"} ${o.resolve(e.returnType)}`:"";u=`${g} ${y} `}let d=ye(o,i,`${u}${t.trim()}`);o.addDeclaration(`${s}fn ${l}${d}`)}else{let u=gn(t);if(u?.externals){let h=Object.fromEntries(Object.entries(u.externals).filter(([T])=>!(T in i)));Q(i,h)}let d=u?.ast??o.transpileFn(String(t));d.argNames.type==="destructured-object"&&Q(i,Object.fromEntries(d.argNames.props.map(({prop:h,alias:T})=>[T,h]))),!Array.isArray(e.argTypes)&&d.argNames.type==="identifiers"&&d.argNames.names[0]!==void 0&&Q(i,{[d.argNames.names[0]]:Object.fromEntries(Object.keys(e.argTypes).map(h=>[h,h]))});let g=d.externalNames.filter(h=>!(h in i));if(g.length>0)throw new Gt(p(this),g);let c=Array.isArray(e.argTypes)?d.argNames.type==="identifiers"?e.argTypes.map((h,T)=>({value:(d.argNames.type==="identifiers"?d.argNames.names[T]:void 0)??`arg_${T}`,dataType:h})):[]:Object.entries(e.argTypes).map(([h,T])=>({value:h,dataType:T})),{head:y,body:x}=o.fnToWgsl({args:c,returnType:e.returnType,body:d.body,externalMap:i});o.addDeclaration(`${s}fn ${l}${o.resolve(y)}${o.resolve(x)}`)}return l}},a=p(t);return a!==void 0&&w(n,a),n}function On(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(ut(n))return[r,n];let a=ee(n);return a!==void 0?(t=a+1,[r,n]):[r,Yt(t++,n)]}))}function Ct(e){return $(e)?rt(e)?void 0:ee(e)!==void 0?e:Yt(0,e):Qt(On(e))}function $e(e){return Qt(On(e))}function se(e,...t){return Ca(e)?Pa(e,...t):e}function Ca(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)&&e.raw.every(t=>typeof t=="string")}function Pa(e,...t){return e.slice(1).reduce((r,n,a)=>`${r}${t[a]}${n}`,e[0])}function Gn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[$e(e.in)]:[],returnType:void 0,workgroupSize:[e.workgroupSize[0]??1,e.workgroupSize[1]??1,e.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>Va(t,e.workgroupSize,se(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Va(e,t,r){let n=oe(e,r),a=e.argTypes[0];return{shell:e,$uses(o){return n.applyExternals(o),this},[b]:n,$name(o){return w(n,o),N(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){return n.resolve(o,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){return`computeFn:${p(n)??"<unnamed>"}`}}}function Wn(e,t){let r={[m]:!0,argTypes:e,returnType:t,isEntry:!1},n=(a,...o)=>ka(r,se(a,...o));return Object.assign(Object.assign(n,r),{does:n})}function Pr(e){return e?.resourceType==="function"}function $a([e,t]){return`${p(e)??"<unnamed>"}=${t}`}function ka(e,t){let r=oe(e,t),n={[m]:{implementation:t,argTypes:e.argTypes},shell:e,resourceType:"function",$uses(s){return r.applyExternals(s),this},[b]:r,$name(s){return w(r,s),this},with(s,i){return Mn(o,[[ge(s)?s.slot:s,i]])},"~resolve"(s){if(typeof t=="string")return r.resolve(s);let i=s;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(e.returnType),r.resolve(s)}finally{i.callStack.pop()}}},a=zt((...s)=>{if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...s)},(...s)=>({value:new Pt(o,s.map(i=>i.value)),dataType:e.returnType??U}),e.argTypes);a[m].implementation=t;let o=Object.assign(a,n);return Object.defineProperty(o,"toString",{value(){return`fn:${p(r)??"<unnamed>"}`}}),o}function Mn(e,t){let r={[m]:{implementation:e[m].implementation,argTypes:e[m].argTypes},resourceType:"function",shell:e.shell,"~providing":{inner:e,pairs:t},$uses(o){return e.$uses(o),this},[b]:e,$name(o){return e.$name(o),this},with(o,s){return Mn(a,[...t,[ge(o)?o.slot:o,s]])}},n=zt((...o)=>e(...o),(...o)=>({value:new Pt(a,o.map(s=>s.value)),dataType:e.shell.returnType??U}),e.shell.argTypes),a=Object.assign(n,r);return Object.defineProperty(a,"toString",{value(){return`fn:${p(e)??"<unnamed>"}[${t.map($a).join(", ")}]`}}),a[m].implementation=e[m].implementation,a}var Pt=class{constructor(t,r){this._fn=t;this._params=r;this[b]=t}[b];"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){return`call:${p(this)??"<unnamed>"}`}};function Nn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[$e(e.in)]:[],targets:e.out,returnType:Ct(e.out),isEntry:!0},r=(n,...a)=>Ea(t,se(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Ea(e,t){let r=oe(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Be(t,n,s=>r.applyExternals(s)),{shell:e,outputType:n,$uses(s){return r.applyExternals(s),this},[b]:r,$name(s){return w(r,s),N(n)&&n.$name(`${s}_Output`),N(a)&&a.$name(`${s}_Input`),this},"~resolve"(s){if(typeof t=="string")return r.resolve(s,"@fragment ");let i=s;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(n),r.resolve(s,"@fragment ")}finally{i.callStack.pop()}},toString(){return`fragmentFn:${p(r)??"<unnamed>"}`}}}function jn(e){let t={attributes:[e.in??{}],returnType:Object.keys(e.out).length!==0?Ct(e.out):void 0,argTypes:e.in&&Object.keys(e.in).length!==0?[$e(e.in)]:[],isEntry:!0},r=(n,...a)=>La(t,se(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function La(e,t){let r=oe(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Be(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,inputType:a,$uses(o){return r.applyExternals(o),this},[b]:r,$name(o){return w(r,o),N(n)&&n.$name(`${o}_Output`),N(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){if(typeof t=="string")return r.resolve(o,"@vertex ");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,"@vertex ")}finally{s.callStack.pop()}},toString(){return`vertexFn:${p(r)??"<unnamed>"}`}}}var ie=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++}`}},ue=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 zn(e){let{externals:t,template:r,names:n,unstable_jitTranspiler:a}=e,o={};Q(o,t??{});let s={"~resolve"(l){return ye(l,o,r??"")},toString:()=>"<root>"},{code:i}=Ve(s,{names:n==="strict"?new ue:new ie,jitTranspiler:a});return i}var tt=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 Kn(e,t,r){return new Vr(new $r(e,t,r),{})}function Hn(e){let t=e;return t?.resourceType==="compute-pipeline"&&!!t[m]}var Vr=class e{constructor(t,r){this._core=t;this._priors=r;this[m]={get rawPipeline(){return t.unwrap().pipeline}},this[b]=t}[m];resourceType="compute-pipeline";[b];get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){return new e(this._core,{bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[t,r]])})}dispatchWorkgroups(t,r,n){let a=this._core.unwrap(),{branch:o}=this._core,s=o.commandEncoder.beginComputePass({label:p(this._core)??"<unnamed>"});s.setPipeline(a.pipeline);let i=new Set(a.bindGroupLayouts);if(a.bindGroupLayouts.forEach((l,u)=>{if(a.catchall&&u===a.catchall[0])s.setBindGroup(u,o.unwrap(a.catchall[1])),i.delete(l);else{let d=this._priors.bindGroupLayoutMap?.get(l);d!==void 0&&(i.delete(l),s.setBindGroup(u,o.unwrap(d)))}}),i.size>0)throw new le(i);s.dispatchWorkgroups(t,r,n),s.end()}$name(t){return w(this._core,t),this}},$r=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n}_memo;unwrap(){if(this._memo===void 0){let t=this.branch.device,{code:r,bindGroupLayouts:n,catchall:a}=Ve({"~resolve":o=>(o.withSlots(this._slotBindings,()=>{o.resolve(this._entryFn)}),""),toString:()=>`computePipeline:${p(this)??"<unnamed>"}`},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});a!==null&&n[a[0]]?.$name(`${p(this)??"<unnamed>"} - Automatic Bind Group & Layout`),this._memo={pipeline:t.createComputePipeline({label:p(this)??"<unnamed>",layout:t.createPipelineLayout({label:`${p(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:n.map(o=>this.branch.unwrap(o))}),compute:{module:t.createShaderModule({label:`${p(this)??"<unnamed>"} - Shader`,code:r})}}),bindGroupLayouts:n,catchall:a}}return this._memo}};function Lr(e,t="vertex"){return new Er(e,t)}function $t(e){return e?.resourceType==="vertex-layout"}var kr=Symbol("defaultAttribEntry");function Vt(e,t,r,n,a){if(Se(t)||en(t)){let o=ee(t);return o!==void 0&&(n[a??kr]=o),Vt(e,t.inner,_(r,K(t)),n)}if(I(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([s,i])=>{o=_(o,P(i));let l=[s,Vt(e,i,o,n,s)];return o+=S(i),l}))}if(Z(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([s,i])=>{o=_(o,K(i));let l=[s,Vt(e,i,o,n,s)];return o+=S(i),l}))}if("type"in t&&typeof t.type=="string"){if(Hr.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=qr[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var Er=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;let n=t(0);this.stride=_(S(n.elementType),P(n)),this.attrib=Vt(this,n.elementType,0,this._customLocationMap)}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 w(this,t),this}};function _a(e){return typeof e?.loadOp=="string"}function qn(e,t){if($(e)){if(!_a(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 Oa(e){return typeof e?.format=="string"}function Jn(e,t){if($(e)){if(rt(e))return[];if(!Oa(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 Yn(e){return new _r(new Or(e),{})}function Qn(e){let t=e;return t?.resourceType==="render-pipeline"&&!!t[m]}var _r=class e{[m];resourceType="render-pipeline";[b];constructor(t,r){this[m]={core:t,priors:r},this[b]=t}$name(t){return w(this[m].core,t),this}with(t,r){let n=this[m];if(Ut(t))return new e(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[t,r]])});if($t(t))return new e(n.core,{...n.priors,vertexLayoutMap:new Map([...n.priors.vertexLayoutMap??[],[t,r]])});throw new Error("Unsupported value passed into .with()")}withColorAttachment(t){let r=this[m];return new e(r.core,{...r.priors,colorAttachment:t})}withDepthStencilAttachment(t){let r=this[m];return new e(r.core,{...r.priors,depthStencilAttachment:t})}draw(t,r,n,a){let o=this[m],s=o.core.unwrap(),{branch:i,fragmentFn:l}=o.core.options,d={colorAttachments:qn(l.shell.targets,o.priors.colorAttachment??{}).map(T=>X(T.view)?{...T,view:i.unwrap(T.view).createView()}:T)},g=p(o.core);if(g!==void 0&&(d.label=g),o.priors.depthStencilAttachment!==void 0){let T=o.priors.depthStencilAttachment;X(T.view)?d.depthStencilAttachment={...T,view:i.unwrap(T.view).createView()}:d.depthStencilAttachment=T}let c=i.commandEncoder.beginRenderPass(d);c.setPipeline(s.pipeline);let y=new Set(s.bindGroupLayouts);s.bindGroupLayouts.forEach((T,D)=>{if(s.catchall&&D===s.catchall[0])c.setBindGroup(D,i.unwrap(s.catchall[1])),y.delete(T);else{let ke=o.priors.bindGroupLayoutMap?.get(T);ke!==void 0&&(y.delete(T),c.setBindGroup(D,i.unwrap(ke)))}});let x=new Set(o.core.usedVertexLayouts);if(o.core.usedVertexLayouts.forEach((T,D)=>{let ke=o.priors.vertexLayoutMap?.get(T);ke&&(x.delete(T),c.setVertexBuffer(D,i.unwrap(ke)))}),y.size>0)throw new le(y);if(x.size>0)throw new Ee(x);c.draw(t,r,n,a),c.end(),i.flush()}},Or=class{constructor(t){this.options=t;let r=Tn(t.vertexFn.shell.attributes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=Jn(t.fragmentFn.shell.targets,t.targets)}usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;unwrap(){if(this._memo===void 0){let{branch:t,vertexFn:r,fragmentFn:n,slotBindings:a,primitiveState:o,depthStencilState:s,multisampleState:i}=this.options,{code:l,bindGroupLayouts:u,catchall:d}=Ve({"~resolve":h=>(h.withSlots(a,()=>{h.resolve(r),h.resolve(n)}),""),toString:()=>`renderPipeline:${p(this)??"<unnamed>"}`},{names:t.nameRegistry,jitTranspiler:t.jitTranspiler});d!==null&&u[d[0]]?.$name(`${p(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let g=t.device,c=g.createShaderModule({label:`${p(this)??"<unnamed>"} - Shader`,code:l}),y={layout:g.createPipelineLayout({label:`${p(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:u.map(h=>t.unwrap(h))}),vertex:{module:c,buffers:this._vertexBufferLayouts},fragment:{module:c,targets:this._targets}},x=p(this);x!==void 0&&(y.label=x),o&&(y.primitive=o),s&&(y.depthStencil=s),i&&(y.multisample=i),this._memo={pipeline:g.createRenderPipeline(y),bindGroupLayouts:u,catchall:d}}return this._memo}};var Gr=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[ge(t)?t.slot:t,r]])}withCompute(t){return new Wr(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new Mr({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r,multisampleState:void 0})}},Wr=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return Kn(this._root,this._slotBindings,this._entryFn)}},Mr=class{constructor(t){this._options=t}withFragment(t,r,n){return pe(typeof t!="string","Just type mismatch validation"),pe(typeof r!="string","Just type mismatch validation"),new Nr({...this._options,fragmentFn:t,targets:r})}},Nr=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 Yn(this._options)}},kt=class extends Gr{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;this["~unstable"]=this}"~unstable";_disposables=[];_unwrappedBindGroupLayouts=new tt(r=>r.unwrap(this));_unwrappedBindGroups=new tt(r=>r.unwrap(this));_commandEncoder=null;get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=Fn(this,r,n);return this._disposables.push(a),a}createUniform(r,n){return this.createBuffer(r,n).$usage("uniform").as("uniform")}createMutable(r,n){return this.createBuffer(r,n).$usage("storage").as("mutable")}createReadonly(r,n){return this.createBuffer(r,n).$usage("storage").as("readonly")}createBindGroup(r,n){return new Pe(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=Cn(r,this);return this._disposables.push(n),n}unwrap(r){if(Hn(r))return r[m].rawPipeline;if(Qn(r))return r[m].core.unwrap().pipeline;if(Ut(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(Fr(r))return this._unwrappedBindGroups.getOrMake(r);if(ae(r))return r.buffer;if(X(r))return r[m].unwrap();if(Ze(r)){if(r[m].unwrap)return r[m].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(et(r)){if(r[m].unwrap)return r[m].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if($t(r))return r.vertexLayout;if(Ye(r)){if(r[m].unwrap)return r[m].unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if(Qe(r)){if(r[m].unwrap)return r[m].unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,s=new Map,i,l=()=>{if(!i)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:u,priors:d}=i[m],g=u.unwrap();a.setPipeline(g.pipeline);let c=new Set(g.bindGroupLayouts);g.bindGroupLayouts.forEach((x,h)=>{if(g.catchall&&h===g.catchall[0])a.setBindGroup(h,this.unwrap(g.catchall[1])),c.delete(x);else{let T=d.bindGroupLayoutMap?.get(x)??o.get(x);T!==void 0&&(c.delete(x),Fr(T)?a.setBindGroup(h,this.unwrap(T)):a.setBindGroup(h,T))}});let y=new Set;if(u.usedVertexLayouts.forEach((x,h)=>{let T=d.vertexLayoutMap?.get(x),D=T?{buffer:T,offset:void 0,size:void 0}:s.get(x);!D||!D.buffer?y.add(x):ae(D.buffer)?a.setVertexBuffer(h,this.unwrap(D.buffer),D.offset,D.size):a.setVertexBuffer(h,D.buffer,D.offset,D.size)}),c.size>0)throw new le(c);if(y.size>0)throw new Ee(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){i=u},setIndexBuffer:(u,d,g,c)=>{ae(u)?a.setIndexBuffer(this.unwrap(u),d,g,c):a.setIndexBuffer(u,d,g,c)},setVertexBuffer(u,d,g,c){s.set(u,{buffer:d,offset:g,size:c})},setBindGroup(u,d){o.set(u,d)},draw(u,d,g,c){l(),a.draw(u,d,g,c)},drawIndexed(...u){l(),a.drawIndexed(...u)},drawIndirect(...u){l(),a.drawIndirect(...u)},drawIndexedIndirect(...u){l(),a.drawIndexedIndirect(...u)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function Xn(e){let{adapter:t,device:r,unstable_names:n="random",unstable_jitTranspiler:a}=e??{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(t);if(!o)throw new Error("Could not find a compatible GPU");return new kt(await o.requestDevice(r),n==="random"?new ie:new ue,a,!0)}function Zn(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e??{};return new kt(t,r==="random"?new ie:new ue,n,!1)}function Et(e){return new jr(e)}var jr=class{constructor(t=void 0){this.defaultValue=t}resourceType="slot";$name(t){return w(this,t),this}areEqual(t,r){return Object.is(t,r)}toString(){return`slot:${p(this)??"<unnamed>"}`}get value(){let t=G();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return ze(t.unwrap(this))}};function ea(e,t){return new zr(e,t)}var zr=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;this.slot=Et(r),this[b]=this.slot}resourceType="accessor";slot;[b];$name(t){return this.slot.$name(t),this}toString(){return`accessor:${p(this)??"<unnamed>"}`}get value(){if(!G())throw new Error("Cannot access tgpu.accessor's value outside of resolution.");return new Proxy({"~resolve":r=>r.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[m]:{dataType:this.schema}},Y)}"~resolve"(t){let r=t.unwrap(this.slot);return lt(r)?t.resolve(r):Pr(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function ta(e){return Wa(e)}function Ga([e,t]){return`${p(e)??"<unnamed>"}=${t}`}function Wa(e){if(G())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{resourceType:"derived","~compute":e,[Nt]:void 0,get value(){let r=G();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ze(r.unwrap(this))},with(r,n){return ra(this,[[r,n]])},toString(){return"derived"}}}function ra(e,t){return{resourceType:"derived",[Nt]:void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},"~providing":{inner:e,pairs:t},get value(){let n=G();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return ze(n.unwrap(this))},with(n,a){return ra(e,[...t,[n,a]])},toString(){return`derived[${t.map(Ga).join(", ")}]`}}}function na(e,t){return new Lt("private",e,t)}function aa(e){return new Lt("workgroup",e)}var Lt=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n}"~resolve"(t){let r=t.names.makeUnique(p(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 w(this,t),this}toString(){return`var:${p(this)??"<unnamed>"}`}get value(){if(!de())throw new Error("Cannot access tgpu.var's value directly in JS.");return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[m]:{dataType:this._dataType}},Y)}};var oa={bindGroupLayout:It,vertexLayout:Lr,init:Xn,initFromDevice:Zn,resolve:zn,"~unstable":{fn:Wn,fragmentFn:Nn,vertexFn:jn,computeFn:Gn,vertexLayout:Lr,derived:ta,slot:Et,accessor:ea,privateVar:na,workgroupVar:aa,const:ln,declare:mn,sampler:An,comparisonSampler:In}},jp=oa;Object.assign(oa,{__assignAst:cn,__removedJsImpl:yn});export{le as MissingBindGroupsError,Gt as MissingLinksError,_t as MissingSlotValueError,Ee as MissingVertexBuffersError,Ot as NotUniformError,ie as RandomNameRegistry,we as ResolutionError,ue as StrictNameRegistry,jp as default,ae as isBuffer,Qe as isComparisonSampler,q as isDerived,et as isSampledTextureView,Ye as isSampler,H as isSlot,Ze as isStorageTextureView,X as isTexture,Pr as isTgpuFn,Fa as isUsableAsRender,Sr as isUsableAsSampled,xe as isUsableAsStorage,xt as isUsableAsUniform,Da as isUsableAsVertex,oa as tgpu,mr as unstable_asMutable,fr as unstable_asReadonly,gr as unstable_asUniform};
29
+ `)}${r}`}finally{Wt(Ge.GPU)}return this._getOrInstantiate(t)}return String(t)}resolveValue(t,r){if(gt(t))return this.resolve(t);if(r&&z(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&&A(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 ke(e,t){let r=new Rr(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],i=new Set([...a.keys()].map(g=>g.index).filter(g=>g!==void 0)),s=rn(i),l=r.fixedBindings.map((g,c)=>[String(c),g.layoutEntry]),u=()=>{let g=s.next().value,c=Bt(Object.fromEntries(l));return o[g]=c,n=n.replaceAll(Hn,String(g)),[g,new $e(c,Object.fromEntries(r.fixedBindings.map((y,x)=>[String(x),y.resource])))]},d=l.length>0?u():null;for(let[g,c]of a.entries()){let y=g.index??s.next().value;o[y]=g,n=n.replaceAll(c,String(y))}return{code:n,bindGroupLayouts:o,catchall:d}}function Wa(e,t,r){let n=t.map(a=>`${a.value}: ${e.resolve(a.dataType)}`).join(", ");return r.type!=="void"?`(${n}) -> ${Ue(r)} ${e.resolve(r)}`:`(${n})`}function qn(e){let{externals:t,template:r,names:n,unstable_jitTranspiler:a}=e,o={};ge(o,t??{});let i={"~resolve"(l){return ce(l,o,r??"")},toString:()=>"<root>"},{code:s}=ke(i,{names:n==="strict"?new ie:new oe,jitTranspiler:a});return s}var nt=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 Jn(e,t,r){return new Pr(new Cr(e,t,r),{})}function Yn(e){let t=e;return t?.resourceType==="compute-pipeline"&&!!t[f]}var Pr=class e{constructor(t,r){this._core=t;this._priors=r;this[f]={get rawPipeline(){return t.unwrap().pipeline}},this[D]=t}[f];resourceType="compute-pipeline";[D];get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){return new e(this._core,{bindGroupLayoutMap:new Map([...this._priors.bindGroupLayoutMap??[],[t,r]])})}dispatchWorkgroups(t,r,n){let a=this._core.unwrap(),{branch:o}=this._core,i=o.commandEncoder.beginComputePass({label:p(this._core)??"<unnamed>"});i.setPipeline(a.pipeline);let s=new Set(a.bindGroupLayouts);if(a.bindGroupLayouts.forEach((l,u)=>{if(a.catchall&&u===a.catchall[0])i.setBindGroup(u,o.unwrap(a.catchall[1])),s.delete(l);else{let d=this._priors.bindGroupLayoutMap?.get(l);d!==void 0&&(s.delete(l),i.setBindGroup(u,o.unwrap(d)))}}),s.size>0)throw new le(s);i.dispatchWorkgroups(t,r,n),i.end()}$name(t){return h(this._core,t),this}},Cr=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n}_memo;unwrap(){if(this._memo===void 0){let t=this.branch.device,{code:r,bindGroupLayouts:n,catchall:a}=ke({"~resolve":o=>(o.withSlots(this._slotBindings,()=>{o.resolve(this._entryFn)}),""),toString:()=>`computePipeline:${p(this)??"<unnamed>"}`},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});a!==null&&n[a[0]]?.$name(`${p(this)??"<unnamed>"} - Automatic Bind Group & Layout`),this._memo={pipeline:t.createComputePipeline({label:p(this)??"<unnamed>",layout:t.createPipelineLayout({label:`${p(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:n.map(o=>this.branch.unwrap(o))}),compute:{module:t.createShaderModule({label:`${p(this)??"<unnamed>"} - Shader`,code:r})}}),bindGroupLayouts:n,catchall:a}}return this._memo}};function kr(e,t="vertex"){return new $r(e,t)}function $t(e){return e?.resourceType==="vertex-layout"}var Vr=Symbol("defaultAttribEntry");function Vt(e,t,r,n,a){if(ot(t)||en(t)){let o=Z(t);return o!==void 0&&(n[a??Vr]=o),Vt(e,t.inner,L(r,H(t)),n)}if(A(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,s])=>{o=L(o,V(s));let l=[i,Vt(e,s,o,n,i)];return o+=v(s),l}))}if(K(t)){let o=r;return Object.fromEntries(Object.entries(t.propTypes).map(([i,s])=>{o=L(o,H(s));let l=[i,Vt(e,s,o,n,i)];return o+=v(s),l}))}if("type"in t&&typeof t.type=="string"){if(zr.includes(t.type))return{_layout:e,format:t.type,offset:r};let o=Kr[t.type];if(o)return{_layout:e,format:o,offset:r}}throw new Error(`Unsupported data used in vertex layout: ${String(t)}`)}var $r=class{constructor(t,r){this.schemaForCount=t;this.stepMode=r;let n=t(0);this.stride=L(v(n.elementType),V(n)),this.attrib=Vt(this,n.elementType,0,this._customLocationMap)}resourceType="vertex-layout";stride;attrib;_customLocationMap={};get vertexLayout(){if(this._customLocationMap[Vr]!==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[Vr]}]}}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 Na(e){return typeof e?.loadOp=="string"}function Qn(e,t){if(O(e)){if(!Na(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 ja(e){return typeof e?.format=="string"}function Xn(e,t){if(O(e)){if(it(e))return[];if(!ja(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 Zn(e){return new _r(new Er(e),{})}function ea(e){let t=e;return t?.resourceType==="render-pipeline"&&!!t[f]}var _r=class e{[f];resourceType="render-pipeline";[D];constructor(t,r){this[f]={core:t,priors:r},this[D]=t}$name(t){return h(this[f].core,t),this}with(t,r){let n=this[f];if(Rt(t))return new e(n.core,{...n.priors,bindGroupLayoutMap:new Map([...n.priors.bindGroupLayoutMap??[],[t,r]])});if($t(t))return new e(n.core,{...n.priors,vertexLayoutMap:new Map([...n.priors.vertexLayoutMap??[],[t,r]])});throw new Error("Unsupported value passed into .with()")}withColorAttachment(t){let r=this[f];return new e(r.core,{...r.priors,colorAttachment:t})}withDepthStencilAttachment(t){let r=this[f];return new e(r.core,{...r.priors,depthStencilAttachment:t})}draw(t,r,n,a){let o=this[f],i=o.core.unwrap(),{branch:s,fragmentFn:l}=o.core.options,d={colorAttachments:Qn(l.shell.targets,o.priors.colorAttachment??{}).map(b=>Q(b.view)?{...b,view:s.unwrap(b.view).createView()}:b)},g=p(o.core);if(g!==void 0&&(d.label=g),o.priors.depthStencilAttachment!==void 0){let b=o.priors.depthStencilAttachment;Q(b.view)?d.depthStencilAttachment={...b,view:s.unwrap(b.view).createView()}:d.depthStencilAttachment=b}let c=s.commandEncoder.beginRenderPass(d);c.setPipeline(i.pipeline);let y=new Set(i.bindGroupLayouts);i.bindGroupLayouts.forEach((b,U)=>{if(i.catchall&&U===i.catchall[0])c.setBindGroup(U,s.unwrap(i.catchall[1])),y.delete(b);else{let _e=o.priors.bindGroupLayoutMap?.get(b);_e!==void 0&&(y.delete(b),c.setBindGroup(U,s.unwrap(_e)))}});let x=new Set(o.core.usedVertexLayouts);if(o.core.usedVertexLayouts.forEach((b,U)=>{let _e=o.priors.vertexLayoutMap?.get(b);_e&&(x.delete(b),c.setVertexBuffer(U,s.unwrap(_e)))}),y.size>0)throw new le(y);if(x.size>0)throw new Ee(x);c.draw(t,r,n,a),c.end(),s.flush()}},Er=class{constructor(t){this.options=t;let r=Un(t.vertexFn.shell.attributes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=Xn(t.fragmentFn.shell.targets,t.targets)}usedVertexLayouts;_memo;_vertexBufferLayouts;_targets;unwrap(){if(this._memo===void 0){let{branch:t,vertexFn:r,fragmentFn:n,slotBindings:a,primitiveState:o,depthStencilState:i,multisampleState:s}=this.options,{code:l,bindGroupLayouts:u,catchall:d}=ke({"~resolve":w=>(w.withSlots(a,()=>{w.resolve(r),w.resolve(n)}),""),toString:()=>`renderPipeline:${p(this)??"<unnamed>"}`},{names:t.nameRegistry,jitTranspiler:t.jitTranspiler});d!==null&&u[d[0]]?.$name(`${p(this)??"<unnamed>"} - Automatic Bind Group & Layout`);let g=t.device,c=g.createShaderModule({label:`${p(this)??"<unnamed>"} - Shader`,code:l}),y={layout:g.createPipelineLayout({label:`${p(this)??"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:u.map(w=>t.unwrap(w))}),vertex:{module:c,buffers:this._vertexBufferLayouts},fragment:{module:c,targets:this._targets}},x=p(this);x!==void 0&&(y.label=x),o&&(y.primitive=o),i&&(y.depthStencil=i),s&&(y.multisample=s),this._memo={pipeline:g.createRenderPipeline(y),bindGroupLayouts:u,catchall:d}}return this._memo}};var Gr=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[He(t)?t.slot:t,r]])}withCompute(t){return new Lr(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new Or({branch:this._getRoot(),primitiveState:void 0,depthStencilState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r,multisampleState:void 0})}},Lr=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return Jn(this._root,this._slotBindings,this._entryFn)}},Or=class{constructor(t){this._options=t}withFragment(t,r,n){return pe(typeof t!="string","Just type mismatch validation"),pe(typeof r!="string","Just type mismatch validation"),new Mr({...this._options,fragmentFn:t,targets:r})}},Mr=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 Zn(this._options)}},kt=class extends Gr{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;this["~unstable"]=this}"~unstable";_disposables=[];_unwrappedBindGroupLayouts=new nt(r=>r.unwrap(this));_unwrappedBindGroups=new nt(r=>r.unwrap(this));_commandEncoder=null;get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=kn(this,r,n);return this._disposables.push(a),a}createUniform(r,n){return this.createBuffer(r,n).$usage("uniform").as("uniform")}createMutable(r,n){return this.createBuffer(r,n).$usage("storage").as("mutable")}createReadonly(r,n){return this.createBuffer(r,n).$usage("storage").as("readonly")}createBindGroup(r,n){return new $e(r,n)}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}createTexture(r){let n=Mn(r,this);return this._disposables.push(n),n}unwrap(r){if(Yn(r))return r[f].rawPipeline;if(ea(r))return r[f].core.unwrap().pipeline;if(Rt(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(Fr(r))return this._unwrappedBindGroups.getOrMake(r);if(ue(r))return r.buffer;if(Q(r))return r[f].unwrap();if(tt(r)){if(r[f].unwrap)return r[f].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if(rt(r)){if(r[f].unwrap)return r[f].unwrap();throw new Error("Cannot unwrap laid-out texture view.")}if($t(r))return r.vertexLayout;if(Xe(r)){if(r[f].unwrap)return r[f].unwrap(this);throw new Error("Cannot unwrap laid-out sampler.")}if(Ze(r)){if(r[f].unwrap)return r[f].unwrap(this);throw new Error("Cannot unwrap laid-out comparison sampler.")}throw new Error(`Unknown resource type: ${r}`)}beginRenderPass(r,n){let a=this.commandEncoder.beginRenderPass(r),o=new Map,i=new Map,s,l=()=>{if(!s)throw new Error("Cannot draw without a call to pass.setPipeline");let{core:u,priors:d}=s[f],g=u.unwrap();a.setPipeline(g.pipeline);let c=new Set(g.bindGroupLayouts);g.bindGroupLayouts.forEach((x,w)=>{if(g.catchall&&w===g.catchall[0])a.setBindGroup(w,this.unwrap(g.catchall[1])),c.delete(x);else{let b=d.bindGroupLayoutMap?.get(x)??o.get(x);b!==void 0&&(c.delete(x),Fr(b)?a.setBindGroup(w,this.unwrap(b)):a.setBindGroup(w,b))}});let y=new Set;if(u.usedVertexLayouts.forEach((x,w)=>{let b=d.vertexLayoutMap?.get(x),U=b?{buffer:b,offset:void 0,size:void 0}:i.get(x);!U||!U.buffer?y.add(x):ue(U.buffer)?a.setVertexBuffer(w,this.unwrap(U.buffer),U.offset,U.size):a.setVertexBuffer(w,U.buffer,U.offset,U.size)}),c.size>0)throw new le(c);if(y.size>0)throw new Ee(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,d,g,c)=>{ue(u)?a.setIndexBuffer(this.unwrap(u),d,g,c):a.setIndexBuffer(u,d,g,c)},setVertexBuffer(u,d,g,c){i.set(u,{buffer:d,offset:g,size:c})},setBindGroup(u,d){o.set(u,d)},draw(u,d,g,c){l(),a.draw(u,d,g,c)},drawIndexed(...u){l(),a.drawIndexed(...u)},drawIndirect(...u){l(),a.drawIndirect(...u)},drawIndexedIndirect(...u){l(),a.drawIndexedIndirect(...u)}}),a.end()}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function ta(e){let{adapter:t,device:r,unstable_names:n="random",unstable_jitTranspiler:a}=e??{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(t);if(!o)throw new Error("Could not find a compatible GPU");return new kt(await o.requestDevice(r),n==="random"?new oe:new ie,a,!0)}function ra(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e??{};return new kt(t,r==="random"?new oe:new ie,n,!1)}function _t(e){return new Wr(e)}var Wr=class{constructor(t=void 0){this.defaultValue=t}resourceType="slot";$name(t){return h(this,t),this}areEqual(t,r){return Object.is(t,r)}toString(){return`slot:${p(this)??"<unnamed>"}`}[I](t){return ze(t,t.unwrap(this))}get value(){let t=X();if(!t)throw new Error("Cannot access tgpu.slot's value outside of resolution.");return this[I](t)}};function na(e,t){return new Nr(e,t)}var Nr=class{constructor(t,r=void 0){this.schema=t;this.defaultValue=r;this.slot=_t(r),this[D]=this.slot}resourceType="accessor";slot;$name(t){return this.slot.$name(t),this}toString(){return`accessor:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.schema},q)}get value(){if(!J())throw new Error("`tgpu.accessor` values are only accessible on the GPU");return this[I]()}"~resolve"(t){let r=t.unwrap(this.slot);return gn(r)?t.resolve(r):ir(r)?`${t.resolve(r)}()`:t.resolveValue(r,this.schema)}};function aa(e){return Ka(e)}function za([e,t]){return`${p(e)??"<unnamed>"}=${t}`}function Ka(e){if(X())throw new Error("Cannot create tgpu.derived objects at the resolution stage.");return{resourceType:"derived","~compute":e,[Nt]:void 0,"~gpuRepr":void 0,[I](r){return ze(r,r.unwrap(this))},get value(){let r=X();if(!r)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[I](r)},with(r,n){return oa(this,[[r,n]])},toString(){return"derived"}}}function oa(e,t){return{resourceType:"derived",[Nt]:void 0,"~gpuRepr":void 0,"~compute"(){throw new Error("'~compute' should never be read on bound derived items.")},"~providing":{inner:e,pairs:t},[I](n){return ze(n,n.unwrap(this))},get value(){let n=X();if(!n)throw new Error("Cannot access tgpu.derived's value outside of resolution.");return this[I](n)},with(n,a){return oa(e,[...t,[n,a]])},toString(){return`derived[${t.map(za).join(", ")}]`}}}function ia(e,t){return new Et("private",e,t)}function sa(e){return new Et("workgroup",e)}var Et=class{constructor(t,r,n){this.scope=t;this._dataType=r;this._initialValue=n;this[f]={scope:t}}"~resolve"(t){let r=t.names.makeUnique(p(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:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this._dataType},q)}get value(){if(!J())throw new Error("`tgpu.var` values are only accessible on the GPU");return this[I]()}};var ua={bindGroupLayout:Bt,vertexLayout:kr,init:ta,initFromDevice:ra,resolve:qn,"~unstable":{fn:vn,fragmentFn:Fn,vertexFn:In,computeFn:Sn,vertexLayout:kr,derived:aa,slot:_t,accessor:na,privateVar:ia,workgroupVar:sa,const:dn,declare:yn,sampler:_n,comparisonSampler:En}},rl=ua;Object.assign(ua,{__assignAst:hn,__removedJsImpl:wn});export{le as MissingBindGroupsError,Ot as MissingLinksError,Gt as MissingSlotValueError,Ee as MissingVertexBuffersError,Lt as NotUniformError,oe as RandomNameRegistry,he as ResolutionError,ie as StrictNameRegistry,rl as default,ue as isBuffer,Ze as isComparisonSampler,Re as isDerived,rt as isSampledTextureView,Xe as isSampler,Be as isSlot,tt as isStorageTextureView,Q as isTexture,ir as isTgpuFn,_a as isUsableAsRender,Sr as isUsableAsSampled,Te as isUsableAsStorage,wt as isUsableAsUniform,ka as isUsableAsVertex,ua as tgpu,dr as unstable_asMutable,fr as unstable_asReadonly,gr as unstable_asUniform};
30
30
  //# sourceMappingURL=index.js.map