typegpu 0.2.0 → 0.3.0-alpha.1
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +2 -2
- package/chunk-CKSBATTP.cjs +2 -0
- package/chunk-CKSBATTP.cjs.map +1 -0
- package/chunk-IQYHODCR.js +2 -0
- package/chunk-IQYHODCR.js.map +1 -0
- package/data/index.cjs +1 -1
- package/data/index.d.cts +122 -379
- package/data/index.d.ts +122 -379
- package/data/index.js +1 -1
- package/index.cjs +14 -47
- package/index.cjs.map +1 -1
- package/index.d.cts +505 -168
- package/index.d.ts +505 -168
- package/index.js +14 -47
- package/index.js.map +1 -1
- package/package.json +3 -14
- package/utilityTypes-0b50gROn.d.cts +1122 -0
- package/utilityTypes-0b50gROn.d.ts +1122 -0
- package/chunk-5EPBCOO4.js +0 -8
- package/chunk-5EPBCOO4.js.map +0 -1
- package/chunk-SBJR5ZQJ.cjs +0 -8
- package/chunk-SBJR5ZQJ.cjs.map +0 -1
- package/types-CGmVkuAt.d.cts +0 -880
- package/types-CGmVkuAt.d.ts +0 -880
package/index.js
CHANGED
@@ -1,52 +1,19 @@
|
|
1
|
-
import{A as
|
2
|
-
|
1
|
+
import{A as H,Aa as rt,B as X,Ba as nt,C as be,Ca as at,D as he,E as we,F as y,G as B,H as F,a as E,b as R,c as s,d as M,ma as P,na as Q,pa as w,q as ce,r as $,s as Qe,t as Ze,u as xe,ua as et,v as D,va as tt,w as v,x as u,z as L}from"./chunk-IQYHODCR.js";var V=class{constructor(){s(this,"lastUniqueId",0)}makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},k=class{constructor(){s(this,"_usedNames",new Set)}makeUnique(t){if(t===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=t;for(;this._usedNames.has(n);)r++,n=`${t}_${r}`;return this._usedNames.add(n),n}};function ot(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var Gt=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","mat2x2f","mat3x3f","mat4x4f"];function It(e){return Gt.includes(e.type)}function Ct(e,[t,r]){return` ${tt(r)}${t}: ${e.resolve(r)},
|
2
|
+
`}function Vt(e,t){let r=e.names.makeUnique(t.label);return e.addDeclaration(`
|
3
|
+
struct ${r} {
|
4
|
+
${Object.entries(t.propTypes).map(n=>Ct(e,n)).join("")}}
|
5
|
+
`),r}function kt(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function De(e,t){if(It(t))return t.type;if(t.type==="struct")return Vt(e,t);if(t.type==="array")return kt(e,t);if(t.type==="atomic")return`atomic<${De(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);ot(t,"resolveData")}var Se="Invariant failed";function Z(e,t){if(e)return;throw new Error(Se)}var O=class e extends Error{constructor(r,n){let a=n.map(o=>`- ${o}`);a.length>20&&(a=[...a.slice(0,11),"...",...a.slice(-10)]);super(`Resolution of the following tree failed:
|
6
|
+
${a.join(`
|
7
|
+
`)}`);this.cause=r;this.trace=n;Object.setPrototypeOf(this,e.prototype)}appendToTrace(r){let n=[r,...this.trace];return new e(this.cause,n)}},ne=class e extends Error{constructor(r){super(`Missing value for '${r}'`);this.slot=r;Object.setPrototypeOf(this,e.prototype)}},W=class e extends Error{constructor(t){var r;super(`Buffer '${(r=t.label)!=null?r:"<unnamed>"}' is not bindable as a uniform. Use .$usage('uniform') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};var N=class e extends Error{constructor(t){super(`Bind group was not provided for '${t!=null?t:"<unnamed>"}' layout.`),Object.setPrototypeOf(this,e.prototype)}};function*it(e){let t=0;for(;;)e.has(t)||(yield t),t++}var S=Symbol("Unknown data type");function j(e){return!!e&&(typeof e=="object"||typeof e=="function")&&"resolve"in e}function st(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||j(e)}function ut(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function pt(e){return e.__brand==="TgpuSlot"}function x(e,t){return st(t.value)||M(t.value)?e.resolve(t.value):String(t.value)}function Mt(e){throw new Error(`'${JSON.stringify(e)}' was not handled by the WGSL generator.`)}function lt(e,t){return t?{value:"true",dataType:xe}:{value:"false",dataType:xe}}function dt(e,t){return`${e.indent()}{
|
8
|
+
${t.block.map(r=>ve(e,r)).join(`
|
3
9
|
`)}
|
4
|
-
${
|
10
|
+
${e.dedent()}}`}function Ue(e,t){return e.getById(t)}function U(e,t){if(typeof t=="string")return Ue(e,t);if(typeof t=="boolean")return lt(e,t);if("x2"in t){let[r,n,a]=t.x2,o=x(e,U(e,r)),i=x(e,U(e,a));return{value:`${o} ${n} ${i}`,dataType:S}}if("."in t){let[r,n]=t["."],a=U(e,r),o=x(e,U(e,n));return j(a.value)||typeof a.value=="object"?o==="value"?{value:x(e,a),dataType:S}:{value:a.value[o],dataType:S}:{value:`${x(e,a)}.${o}`,dataType:S}}if("[]"in t){let[r,n]=t["[]"],a=x(e,U(e,r)),o=x(e,U(e,n));return{value:`${a}[${o}]`,dataType:S}}if("num"in t)return{value:t.num,dataType:S};if("call"in t){let n=U(e,t.call).value,o=t.args.map(i=>U(e,i)).map(i=>x(e,i));return j(n)||typeof n=="function"?{value:n(...o),dataType:S}:{value:`${String(n)}(${o.join(", ")})`,dataType:S}}Mt(t)}function ve(e,t){if(typeof t=="string")return`${e.pre}${x(e,Ue(e,t))};`;if(typeof t=="boolean")return`${e.pre}${x(e,lt(e,t))};`;if("return"in t)return t.return===null?`${e.pre}return;`:`${e.pre}return ${x(e,U(e,t.return))};`;if("if"in t){let r=x(e,U(e,t.if));e.indent();let n=ve(e,t.do);e.dedent(),e.indent();let a=t.else?ve(e,t.else):void 0;return e.dedent(),a?`${e.pre}if (${r})
|
5
11
|
${n}
|
6
|
-
${
|
7
|
-
${a}`:`${
|
8
|
-
${n}`}if("let"in e||"const"in e){let r=x(t,he(t,"let"in e?e.let:e.const)),n=e.eq?b(t,e.eq):void 0;if(!n)throw new Error("Cannot create variable without an initial value.");return`${t.pre}var ${r} = ${x(t,n)};`}return"block"in e?et(t,e):`${t.pre}${x(t,b(t,e))};`}function be(t,e){return et(t,e)}var ht={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Be=class{constructor(e,r,n){this.names=e;this._bindingGroup=r;this.jitTranspiler=n;o(this,"_nextFreeBindingIdx",0);o(this,"_nextFreeVertexBindingIdx",0);o(this,"_usedBindables",new Set);o(this,"_usedRenderResources",new Set);o(this,"_resourceToIndexMap",new WeakMap);o(this,"_vertexBufferToIndexMap",new WeakMap);o(this,"_usedBuiltins",new Set);o(this,"_declarations",[])}get usedBindables(){return this._usedBindables}get usedRenderResources(){return this._usedRenderResources}get declarations(){return this._declarations}get usedBuiltins(){return this._usedBuiltins}reserveBindingEntry(e){this._usedBindables.add(e);let r=this._nextFreeBindingIdx++;return this._resourceToIndexMap.set(e,r),{group:this._bindingGroup,idx:r}}registerVertexEntry(e){this._usedBindables.add(e);let r=this._nextFreeVertexBindingIdx++;this._vertexBufferToIndexMap.set(e,r)}reserveRenderResourceEntry(e){this._usedRenderResources.add(e);let r=this._nextFreeBindingIdx++;return this._resourceToIndexMap.set(e,r),{group:this._bindingGroup,idx:r}}getBindingIndex(e){return this._resourceToIndexMap.get(e)}addDeclaration(e){this._declarations.push(e)}addBuiltin(e){this._usedBuiltins.add(e)}},Pe=class{constructor(){o(this,"_stack",[]);o(this,"_itemDepth",0)}get itemDepth(){return this._itemDepth}get topItem(){let e=this._stack[this._stack.length-1];if(!e||e.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return e}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}pushSlotBindings(e){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(e)})}pushFunctionScope(e,r,n){this._stack.push({type:"functionScope",args:e,returnType:r,externalMap:n})}pop(){let e=this._stack.pop();(e==null?void 0:e.type)==="item"&&this._itemDepth--}readSlot(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="item")n.usedSlots.add(e);else if((n==null?void 0:n.type)==="slotBinding"){let a=n.bindingMap.get(e);if(a!==void 0)return a}else if(!((n==null?void 0:n.type)==="functionScope"||(n==null?void 0:n.type)==="blockScope"))throw new Error("Unknown layer type.")}return e.defaultValue}getResourceById(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="functionScope"){let a=n.args.find(u=>u.value===e);if(a!==void 0)return a;let i=n.externalMap[e];if(i!==void 0)return{value:i,dataType:v}}else if((n==null?void 0:n.type)==="blockScope"){let a=n.declarations.get(e);if(a!==void 0)return{value:e,dataType:a}}}}},oe=[""," "," "," "," "," "," "," "," "],we=oe.length-1,Se=class{constructor(){o(this,"identLevel",0)}get pre(){var e;return(e=oe[this.identLevel])!=null?e:oe[we].repeat(this.identLevel/we)+oe[this.identLevel%we]}indent(){let e=this.pre;return this.identLevel++,e}dedent(){return this.identLevel--,this.pre}},_=class{constructor(e){o(this,"_memoizedResolves",new WeakMap);o(this,"_shared");o(this,"_indentController",new Se);o(this,"_itemStateStack",new Pe);var r;this._shared=new Be(e.names,(r=e.bindingGroup)!=null?r:0,e.jitTranspiler)}get usedBindables(){return this._shared.usedBindables}get usedRenderResources(){return this._shared.usedRenderResources}get usedBuiltins(){return this._shared.usedBuiltins}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(e){var r;return(r=this._itemStateStack.getResourceById(e))!=null?r:{value:e,dataType:v}}transpileFn(e){if(!this._shared.jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._shared.jitTranspiler.transpileFn(e)}fnToWgsl(e,r,n,a){let i=r.map((l,d)=>({value:l,dataType:e.argTypes[d]}));this._itemStateStack.pushFunctionScope(i,e.returnType,a);let u=be(this,n);this._itemStateStack.pop();let s=i.map(l=>`${l.value}: ${this.resolve(l.dataType)}`).join(", ");return{head:e.returnType!==void 0?`(${s}) -> ${this.resolve(e.returnType)}`:`(${s})`,body:u}}addDeclaration(e){this._shared.addDeclaration(this.resolve(e))}addBinding(e,r){if(e.usage==="vertex"){this._shared.registerVertexEntry(e);return}let{group:n,idx:a}=this._shared.reserveBindingEntry(e);this.addDeclaration(g`@group(${n}) @binding(${a}) var<${ht[e.usage]}> ${r}: ${e.allocatable.dataType};`)}addRenderResource(e,r){let{group:n,idx:a}=this._shared.reserveRenderResourceEntry(e);if(We(e.type)||qe(e.type)||Ke(e.type)){this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type};`);return}if(ue(e)){if(e.access!==void 0){this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type}<${e.texture.descriptor.format}, ${e.access}>;`);return}this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type}<${e.dataType}>;`);return}throw new Error(`Unsupported resource type: ${e.type}`)}addBuiltin(e){this._shared.addBuiltin(e)}nameFor(e){return this._shared.names.nameFor(e)}readSlot(e){let r=this._itemStateStack.readSlot(e);if(r===void 0)throw new Oe(e);return r}unwrap(e){let r=e;for(;Ye(r);)r=this.readSlot(r);return r}_getOrInstantiate(e){var n;let r=(n=this._memoizedResolves.get(e))!=null?n:[];this._itemStateStack.pushItem();try{for(let u of r)if([...u.slotToValueMap.entries()].every(([l,d])=>this._itemStateStack.readSlot(l)===d))return u.result;let a=e.resolve(this),i=new Map;for(let u of this._itemStateStack.topItem.usedSlots)i.set(u,this._itemStateStack.readSlot(u));return r.push({slotToValueMap:i,result:a}),this._memoizedResolves.set(e,r),a}catch(a){throw a instanceof Te?a.appendToTrace(e):new Te(a,[e])}finally{this._itemStateStack.pop()}}resolve(e,r=[]){if(!j(e))return String(e);let n=!1;r.length>0&&(n=!0,this._itemStateStack.pushSlotBindings(r));try{if(this._itemStateStack.itemDepth===0){let a=ee(()=>this._getOrInstantiate(e));return`${[...this._shared.declarations].join(`
|
12
|
+
${e.pre}else
|
13
|
+
${a}`:`${e.pre}if (${r})
|
14
|
+
${n}`}if("let"in t||"const"in t){let r=x(e,Ue(e,"let"in t?t.let:t.const)),n=t.eq?U(e,t.eq):void 0;if(!n)throw new Error("Cannot create variable without an initial value.");return`${e.pre}var ${r} = ${x(e,n)};`}return"block"in t?dt(e,t):`${e.pre}${x(e,U(e,t))};`}function Be(e,t){return dt(e,t)}import{BufferReader as Fe,BufferWriter as _e}from"typed-binary";function $t(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 T=$t;function z(e,t){t>=0?e.writeByte(t&127):e.writeByte(t&127|128)}function q(e){let t=e.readByte();return t&128?(t&127)-128:t&127}var h={bool(e,t,r){e.writeBool(r)},f32(e,t,r){e.writeFloat32(r)},f16(e,t,r){e.writeFloat16(r)},i32(e,t,r){e.writeInt32(r)},u32(e,t,r){e.writeUint32(r)},vec2f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},vec2i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},vec2u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},vec3f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},vec3i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},vec3u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},vec4f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},vec4i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},vec4u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},mat2x2f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat3x3f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat4x4f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},struct(e,t,r){let n=P(t);T(e,n);for(let[a,o]of Object.entries(t.propTypes))T(e,P(o)),K(e,o,r[a]);T(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=P(t);T(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)T(e,n),K(e,t.elementType,r[o]);e.seekTo(a+w(t))},atomic(e,t,r){var n;(n=h[t.inner.type])==null||n.call(h,e,t,r)},decorated(e,t,r){var o,i;let n=Q(t);T(e,n);let a=e.currentByteOffset;(i=h[(o=t.inner)==null?void 0:o.type])==null||i.call(h,e,t.inner,r),e.seekTo(a+w(t))},uint8x2(e,t,r){e.writeByte(r.x),e.writeByte(r.y)},uint8x4(e,t,r){e.writeByte(r.x),e.writeByte(r.y),e.writeByte(r.z),e.writeByte(r.w)},sint8x2(e,t,r){z(e,r.x),z(e,r.y)},sint8x4(e,t,r){z(e,r.x),z(e,r.y),z(e,r.z),z(e,r.w)},unorm8x2(e,t,r){e.writeByte(Math.floor(r.x*255)),e.writeByte(Math.floor(r.y*255))},unorm8x4(e,t,r){e.writeByte(Math.floor(r.x*255)),e.writeByte(Math.floor(r.y*255)),e.writeByte(Math.floor(r.z*255)),e.writeByte(Math.floor(r.w*255))},snorm8x2(e,t,r){e.writeByte(Math.floor(r.x*127+128)),e.writeByte(Math.floor(r.y*127+128))},snorm8x4(e,t,r){e.writeByte(Math.floor(r.x*127+128)),e.writeByte(Math.floor(r.y*127+128)),e.writeByte(Math.floor(r.z*127+128)),e.writeByte(Math.floor(r.w*127+128))},uint16x2(e,t,r){let n=new ArrayBuffer(4),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,r.x,o),a.setUint16(2,r.y,o),e.writeSlice(new Uint8Array(n))},uint16x4(e,t,r){let n=new ArrayBuffer(8),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,r.x,o),a.setUint16(2,r.y,o),a.setUint16(4,r.z,o),a.setUint16(6,r.w,o),e.writeSlice(new Uint8Array(n))},sint16x2(e,t,r){let n=new ArrayBuffer(4),a=new DataView(n),o=e.endianness==="little";a.setInt16(0,r.x,o),a.setInt16(2,r.y,o),e.writeSlice(new Uint8Array(n))},sint16x4(e,t,r){let n=new ArrayBuffer(8),a=new DataView(n),o=e.endianness==="little";a.setInt16(0,r.x,o),a.setInt16(2,r.y,o),a.setInt16(4,r.z,o),a.setInt16(6,r.w,o),e.writeSlice(new Uint8Array(n))},unorm16x2(e,t,r){let n=new ArrayBuffer(4),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,Math.floor(r.x*65535),o),a.setUint16(2,Math.floor(r.y*65535),o),e.writeSlice(new Uint8Array(n))},unorm16x4(e,t,r){let n=new ArrayBuffer(8),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,Math.floor(r.x*65535),o),a.setUint16(2,Math.floor(r.y*65535),o),a.setUint16(4,Math.floor(r.z*65535),o),a.setUint16(6,Math.floor(r.w*65535),o),e.writeSlice(new Uint8Array(n))},snorm16x2(e,t,r){let n=new ArrayBuffer(4),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,Math.floor(r.x*32767+32768),o),a.setUint16(2,Math.floor(r.y*32767+32768),o),e.writeSlice(new Uint8Array(n))},snorm16x4(e,t,r){let n=new ArrayBuffer(8),a=new DataView(n),o=e.endianness==="little";a.setUint16(0,Math.floor(r.x*32767+32768),o),a.setUint16(2,Math.floor(r.y*32767+32768),o),a.setUint16(4,Math.floor(r.z*32767+32768),o),a.setUint16(6,Math.floor(r.w*32767+32768),o),e.writeSlice(new Uint8Array(n))},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)},"loose-array"(e,t,r){var o,i;let n=P(t);T(e,n);let a=e.currentByteOffset;for(let p=0;p<Math.min(t.elementCount,r.length);p++)T(e,n),(i=h[(o=t.elementType)==null?void 0:o.type])==null||i.call(h,e,t.elementType,r[p]);e.seekTo(a+w(t))},"loose-struct"(e,t,r){var n;for(let[a,o]of Object.entries(t.propTypes))(n=h[o.type])==null||n.call(h,e,o,r[a])},"loose-decorated"(e,t,r){var i;let n=Q(t);T(e,n);let a=e.currentByteOffset,o=h[(i=t.inner)==null?void 0:i.type];return o==null||o(e,t.inner,r),e.seekTo(a+w(t)),r}};function K(e,t,r){let n=h[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var Ot={bool(e){return e.readBool()},f32(e){return e.readFloat32()},f16(e){return e.readFloat16()},i32(e){return e.readInt32()},u32(e){return e.readUint32()},vec2f(e){return L(e.readFloat32(),e.readFloat32())},vec3f(e){return be(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return y(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2i(e){return H(e.readInt32(),e.readInt32())},vec3i(e){return he(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return B(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return X(e.readUint32(),e.readUint32())},vec3u(e){return we(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return F(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},mat2x2f(e){return rt(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return nt(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return at(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);T(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))T(e,P(o)),n[a]=_(e,o);return T(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++){T(e,r);let o=t.elementType,i=_(e,o);n.push(i)}return T(e,r),n},atomic(e,t){return _(e,t.inner)},decorated(e,t){let r=Q(t);T(e,r);let n=e.currentByteOffset,a=_(e,t.inner);return e.seekTo(n+w(t)),a},uint8x2:e=>X(e.readByte(),e.readByte()),uint8x4:e=>F(e.readByte(),e.readByte(),e.readByte(),e.readByte()),sint8x2:e=>H(q(e),q(e)),sint8x4:e=>B(q(e),q(e),q(e),q(e)),unorm8x2:e=>L(e.readByte()/255,e.readByte()/255),unorm8x4:e=>y(e.readByte()/255,e.readByte()/255,e.readByte()/255,e.readByte()/255),snorm8x2:e=>L((e.readByte()-128)/127,(e.readByte()-128)/127),snorm8x4:e=>y((e.readByte()-128)/127,(e.readByte()-128)/127,(e.readByte()-128)/127,(e.readByte()-128)/127),uint16x2(e){let t=new ArrayBuffer(4);e.readSlice(new Uint8Array(t),0,4);let r=new DataView(t),n=e.endianness==="little";return X(r.getUint16(0,n),r.getUint16(2,n))},uint16x4(e){let t=new ArrayBuffer(8);e.readSlice(new Uint8Array(t),0,8);let r=new DataView(t),n=e.endianness==="little";return F(r.getUint16(0,n),r.getUint16(2,n),r.getUint16(4,n),r.getUint16(6,n))},sint16x2(e){let t=new ArrayBuffer(4);e.readSlice(new Uint8Array(t),0,4);let r=new DataView(t),n=e.endianness==="little";return H(r.getInt16(0,n),r.getInt16(2,n))},sint16x4(e){let t=new ArrayBuffer(8);e.readSlice(new Uint8Array(t),0,8);let r=new DataView(t),n=e.endianness==="little";return B(r.getInt16(0,n),r.getInt16(2,n),r.getInt16(4,n),r.getInt16(6,n))},unorm16x2(e){let t=new ArrayBuffer(4);e.readSlice(new Uint8Array(t),0,4);let r=new DataView(t),n=e.endianness==="little";return L(r.getUint16(0,n)/65535,r.getUint16(2,n)/65535)},unorm16x4(e){let t=new ArrayBuffer(8);e.readSlice(new Uint8Array(t),0,8);let r=new DataView(t),n=e.endianness==="little";return y(r.getUint16(0,n)/65535,r.getUint16(2,n)/65535,r.getUint16(4,n)/65535,r.getUint16(6,n)/65535)},snorm16x2(e){let t=new ArrayBuffer(4);e.readSlice(new Uint8Array(t),0,4);let r=new DataView(t),n=e.endianness==="little";return L((r.getUint16(0,n)-32768)/32767,(r.getUint16(2,n)-32768)/32767)},snorm16x4(e){let t=new ArrayBuffer(8);e.readSlice(new Uint8Array(t),0,8);let r=new DataView(t),n=e.endianness==="little";return y((r.getUint16(0,n)-32768)/32767,(r.getUint16(2,n)-32768)/32767,(r.getUint16(4,n)-32768)/32767,(r.getUint16(6,n)-32768)/32767)},float16x2:e=>L(e.readFloat16(),e.readFloat16()),float16x4:e=>y(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>L(e.readFloat32(),e.readFloat32()),float32x3:e=>be(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>y(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>X(e.readUint32(),e.readUint32()),uint32x3:e=>we(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>F(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>H(e.readInt32(),e.readInt32()),sint32x3:e=>he(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>B(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 y(r,n,a,o)},"loose-struct"(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=_(e,a);return r},"loose-array"(e,t){let r=P(t),n=[];for(let a=0;a<t.elementCount;a++)T(e,r),n.push(_(e,t.elementType));return T(e,r),n},"loose-decorated"(e,t){T(e,Q(t));let r=e.currentByteOffset,n=_(e,t.inner);return e.seekTo(r+w(t)),n}};function _(e,t){let r=Ot[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}function mt(e,t,r){return new Ae(e,t,r)}function G(e){return e.resourceType==="buffer"}function Ee(e){return!!e.usableAsUniform}function Wt(e){return!!e.usableAsVertex}var Ae=class{constructor(t,r,n){this._group=t;this.dataType=r;this.initialOrBuffer=n;s(this,"resourceType","buffer");s(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);s(this,"_device",null);s(this,"_buffer",null);s(this,"_destroyed",!1);s(this,"_label");s(this,"initial");s(this,"usableAsUniform",!1);s(this,"usableAsStorage",!1);s(this,"usableAsVertex",!1);ut(n)?this._buffer=n:this.initial=n}get label(){return this._label}get buffer(){var t;if(!this._device)throw new Error("Create this buffer using `root.createBuffer` instead of `tgpu.createBuffer`.");if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=this._device.createBuffer({size:w(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:(t=this.label)!=null?t:"<unnamed>"}),this.initial)){let r=new _e(this._buffer.getMappedRange());K(r,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get device(){if(!this._device)throw new Error("This buffer has not been assigned a device. Use .$device(device) to assign a device");return this._device}get destroyed(){return this._destroyed}$name(t){return this._label=t,this._buffer&&(this._buffer.label=t),this}$usage(...t){for(let r of t)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){return this.flags|=t,this}$device(t){return this._device=t,this}write(t){let r=this.buffer,n=this.device;if(r.mapState==="mapped"){let o=r.getMappedRange();if(G(t))throw new Error("Cannot copy to a mapped buffer.");K(new _e(o),this.dataType,t);return}let a=w(this.dataType);if(G(t)){let o=t.buffer;if(this._group)this._group.commandEncoder.copyBufferToBuffer(o,0,r,0,a);else{let i=n.createCommandEncoder();i.copyBufferToBuffer(o,0,r,0,a),n.queue.submit([i.finish()])}}else{this._group&&this._group.flush();let o=new ArrayBuffer(a);K(new _e(o),this.dataType,t),n.queue.writeBuffer(r,0,o,0,a)}}async read(){this._group&&this._group.flush();let t=this.buffer,r=this.device;if(t.mapState==="mapped"){let i=t.getMappedRange();return _(new Fe(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),p=_(new Fe(i),this.dataType);return t.unmap(),p}let n=r.createBuffer({size:w(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,w(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,w(this.dataType));let o=_(new Fe(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}destroy(){var t;this._destroyed||(this._destroyed=!0,(t=this._buffer)==null||t.destroy())}toString(){var t;return`buffer:${(t=this._label)!=null?t:"<unnamed>"}`}};function oe(e){return!!(e!=null&&e.usableAsStorage)}var ae=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};var Nt={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"};var ee=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;s(this,"~repr");s(this,"resourceType","buffer-usage")}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=Nt[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){var t;return`${this.usage}:${(t=this.label)!=null?t:"<unnamed>"}`}get value(){if(!Ze())throw new Error("Cannot access buffer's value directly in JS.");return this}};function jt(e){return(e==null?void 0:e.resourceType)==="sampler"}function zt(e){return(e==null?void 0:e.resourceType)==="sampler-comparison"}var ie=class{constructor(t){this._membership=t;s(this,"resourceType","sampler")}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}},se=class{constructor(t){this._membership=t;s(this,"resourceType","sampler-comparison")}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}};var ue=class{constructor(t){this._membership=t;s(this,"resourceType","external-texture")}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}};var gt={r8unorm:u,r8snorm:u,r8uint:D,r8sint:v,r16uint:D,r16sint:v,r16float:u,rg8unorm:u,rg8snorm:u,rg8uint:D,rg8sint:v,r32uint:D,r32sint:v,r32float:u,rg16uint:D,rg16sint:v,rg16float:u,rgba8unorm:u,"rgba8unorm-srgb":u,rgba8snorm:u,rgba8uint:D,rgba8sint:v,bgra8unorm:u,"bgra8unorm-srgb":u,rgb9e5ufloat:u,rgb10a2uint:D,rgb10a2unorm:u,rg11b10ufloat:u,rg32uint:D,rg32sint:v,rg32float:u,rgba16uint:D,rgba16sint:v,rgba16float:u,rgba32uint:D,rgba32sint:v,rgba32float:u,stencil8:u,depth16unorm:u,depth24plus:u,"depth24plus-stencil8":u,depth32float:u,"depth32float-stencil8":u,"bc1-rgba-unorm":u,"bc1-rgba-unorm-srgb":u,"bc2-rgba-unorm":u,"bc2-rgba-unorm-srgb":u,"bc3-rgba-unorm":u,"bc3-rgba-unorm-srgb":u,"bc4-r-unorm":u,"bc4-r-snorm":u,"bc5-rg-unorm":u,"bc5-rg-snorm":u,"bc6h-rgb-ufloat":u,"bc6h-rgb-float":u,"bc7-rgba-unorm":u,"bc7-rgba-unorm-srgb":u,"etc2-rgb8unorm":u,"etc2-rgb8unorm-srgb":u,"etc2-rgb8a1unorm":u,"etc2-rgb8a1unorm-srgb":u,"etc2-rgba8unorm":u,"etc2-rgba8unorm-srgb":u,"eac-r11unorm":u,"eac-r11snorm":u,"eac-rg11unorm":u,"eac-rg11snorm":u,"astc-4x4-unorm":u,"astc-4x4-unorm-srgb":u,"astc-5x4-unorm":u,"astc-5x4-unorm-srgb":u,"astc-5x5-unorm":u,"astc-5x5-unorm-srgb":u,"astc-6x5-unorm":u,"astc-6x5-unorm-srgb":u,"astc-6x6-unorm":u,"astc-6x6-unorm-srgb":u,"astc-8x5-unorm":u,"astc-8x5-unorm-srgb":u,"astc-8x6-unorm":u,"astc-8x6-unorm-srgb":u,"astc-8x8-unorm":u,"astc-8x8-unorm-srgb":u,"astc-10x5-unorm":u,"astc-10x5-unorm-srgb":u,"astc-10x6-unorm":u,"astc-10x6-unorm-srgb":u,"astc-10x8-unorm":u,"astc-10x8-unorm-srgb":u,"astc-10x10-unorm":u,"astc-10x10-unorm-srgb":u,"astc-12x10-unorm":u,"astc-12x10-unorm-srgb":u,"astc-12x12-unorm":u,"astc-12x12-unorm-srgb":u},te={rgba8unorm:y,rgba8snorm:y,rgba8uint:F,rgba8sint:B,rgba16uint:F,rgba16sint:B,rgba16float:y,r32uint:F,r32sint:B,r32float:y,rg32uint:F,rg32sint:B,rg32float:y,rgba32uint:F,rgba32sint:B,rgba32float:y,bgra8unorm:y},ft={f32:"float",u32:"uint",i32:"sint"},Tt={float:u,"unfilterable-float":u,uint:D,sint:v,depth:u};function yt(e,t){return new Pe(e,t)}function I(e){return(e==null?void 0:e.resourceType)==="texture"}function Ge(e){return(e==null?void 0:e.resourceType)==="texture-storage-view"}function Ie(e){return(e==null?void 0:e.resourceType)==="texture-sampled-view"}var ct={mutable:"read_write",readonly:"read",writeonly:"write"},Pe=class{constructor(t,r){this.props=t;this._branch=r;s(this,"resourceType","texture");s(this,"usableAsSampled",!1);s(this,"usableAsStorage",!1);s(this,"usableAsRender",!1);s(this,"_destroyed",!1);s(this,"_label");s(this,"_flags",GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC);s(this,"_texture",null)}get label(){return this._label}$name(t){return this._label=t,this}unwrap(){var t,r,n,a,o;if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:(t=this._label)!=null?t:"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:(r=this.props.dimension)!=null?r:"2d",viewFormats:(n=this.props.viewFormats)!=null?n:[],mipLevelCount:(a=this.props.mipLevelCount)!=null?a:1,sampleCount:(o=this.props.sampleCount)!=null?o:1})),this._texture}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||(this.usableAsStorage=r),this.usableAsSampled||(this.usableAsSampled=n),this.usableAsRender||(this.usableAsRender=a),this}_asStorage(t,r){var o;if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=(o=t==null?void 0:t.format)!=null?o:this.props.format,a=te[n];return Z(!!a,`Unsupported storage texture format: ${n}`),new Re(t!=null?t:{},r,this)}asReadonly(t){return this._asStorage(t,"readonly")}asWriteonly(t){return this._asStorage(t,"writeonly")}asMutable(t){return this._asStorage(t,"mutable")}asSampled(t){var a;if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=(a=t==null?void 0:t.format)!=null?a:this.props.format;if(!te[r])throw new Error(`Unsupported storage texture format: ${r}`);return new Le(t,this)}destroy(){var t;this._destroyed||(this._destroyed=!0,(t=this._texture)==null||t.destroy())}},de={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},Re=class{constructor(t,r,n){this.access=r;this._texture=n;s(this,"resourceType","texture-storage-view");s(this,"texelDataType");s(this,"dimension");s(this,"_view");s(this,"_format");var a,o,i;this.dimension=(o=(a=t==null?void 0:t.dimension)!=null?a:n.props.dimension)!=null?o:"2d",this._format=(i=t==null?void 0:t.format)!=null?i:n.props.format,this.texelDataType=te[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view}resolve(t){let r=t.names.makeUnique(this.label),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${de[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${ct[this.access]}>;`),r}},pe=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;s(this,"resourceType","texture-storage-view");s(this,"texelDataType");this.texelDataType=te[this._format]}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${de[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${ct[this.access]}>;`),r}},Le=class{constructor(t,r){this._props=t;this._texture=r;s(this,"resourceType","texture-sampled-view");s(this,"channelDataType");s(this,"dimension");s(this,"_format");s(this,"_view");var n,a,o;this.dimension=(a=(n=t==null?void 0:t.dimension)!=null?n:r.props.dimension)!=null?a:"2d",this._format=(o=t==null?void 0:t.format)!=null?o:r.props.format,this.channelDataType=gt[this._format]}get label(){return this._texture.label}$name(t){return this._texture.$name(t),this}unwrap(){var t;return this._view||(this._view=this._texture.unwrap().createView(E({label:`${(t=this.label)!=null?t:"<unnamed>"} - View`},this._props))),this._view}resolve(t){var p;let r=t.names.makeUnique(this.label),n=((p=this._texture.props.sampleCount)!=null?p:1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:ft[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${de[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}},le=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;s(this,"resourceType","texture-sampled-view");s(this,"channelDataType");this.channelDataType=Tt[t]}get label(){return this._membership.key}resolve(t){let r=t.names.makeUnique(this.label),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${de[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}};function Ce(e){return!!(e!=null&&e.usableAsSampled)}function qt(e){return!!(e!=null&&e.usableAsRender)}var me=class e extends Error{constructor(t){var r;super(`Resource '${(r=t.label)!=null?r:"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function ge(e){return new ke(e)}function fe(e){return!!e&&e.resourceType==="bind-group-layout"}function bt(e){return!!e&&e.resourceType==="bind-group"}var Ve=class e extends Error{constructor(t,r){super(`Bind group '${t!=null?t:"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},xt=["compute"],J=["compute","vertex","fragment"],ke=class{constructor(t){this.entries=t;s(this,"_label");s(this,"_index");s(this,"resourceType","bind-group-layout");s(this,"bound",{});var n,a,o,i,p;let r=0;for(let[g,l]of Object.entries(t)){if(l===null){r++;continue}let d={idx:r,key:g,layout:this};if("uniform"in l&&(this.bound[g]=new ee("uniform",l.uniform,d)),"storage"in l){let f="type"in l.storage?l.storage:l.storage(0);this.bound[g]=new ee((n=l.access)!=null?n:"readonly",f,d)}"texture"in l&&(this.bound[g]=new le(l.texture,(a=l.viewDimension)!=null?a:"2d",(o=l.multisampled)!=null?o:!1,d)),"storageTexture"in l&&(this.bound[g]=new pe(l.storageTexture,(i=l.viewDimension)!=null?i:"2d",(p=l.access)!=null?p:"writeonly",d)),"externalTexture"in l&&(this.bound[g]=new ue(d)),"sampler"in l&&(l.sampler==="comparison"?this.bound[g]=new se(d):this.bound[g]=new ie(d)),r++}}get label(){return this._label}get index(){return this._index}$name(t){return this._label=t,this}$idx(t){return this._index=t,this}unwrap(t){var n;return t.device.createBindGroupLayout({label:(n=this.label)!=null?n:"<unnamed>",entries:Object.values(this.entries).map((a,o)=>{var g,l,d,f;if(a===null)return null;let i=a.visibility,p={binding:o,visibility:0};if("uniform"in a)i=i!=null?i:J,p.buffer={type:"uniform"};else if("storage"in a)i=i!=null?i:a.access==="mutable"?xt:J,p.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)i=i!=null?i:J,p.sampler={type:a.sampler};else if("texture"in a)i=i!=null?i:J,p.texture={sampleType:a.texture,viewDimension:(g=a.viewDimension)!=null?g:"2d",multisampled:(l=a.multisampled)!=null?l:!1};else if("storageTexture"in a){let m=(d=a.access)!=null?d:"writeonly";i=i!=null?i:m==="readonly"?J:xt,p.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[m],viewDimension:(f=a.viewDimension)!=null?f:"2d"}}else"externalTexture"in a&&(i=i!=null?i:J,p.externalTexture={});return i!=null&&i.includes("compute")&&(p.visibility|=GPUShaderStage.COMPUTE),i!=null&&i.includes("vertex")&&(p.visibility|=GPUShaderStage.VERTEX),i!=null&&i.includes("fragment")&&(p.visibility|=GPUShaderStage.FRAGMENT),p}).filter(a=>a!==null)})}populate(t){return new Me(this,t)}},Me=class{constructor(t,r){this.layout=t;this.entries=r;s(this,"resourceType","bind-group");for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new Ve(t.label,n)}unwrap(t){var n;return t.device.createBindGroup({label:(n=this.layout.label)!=null?n:"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([a,o],i)=>{var g;if(o===null)return null;let p=this.entries[a];if(p===void 0)throw new Error(`'${a}' is a resource required to populate bind group layout '${(g=this.layout.label)!=null?g:"<unnamed>"}'.`);if("uniform"in o){let l;if(G(p)){if(!Ee(p))throw new W(p);l={buffer:t.unwrap(p)}}else l={buffer:p};return{binding:i,resource:l}}if("storage"in o){let l;if(G(p)){if(!oe(p))throw new W(p);l={buffer:t.unwrap(p)}}else l={buffer:p};return{binding:i,resource:l}}if("texture"in o){let l;if(I(p)){if(!Ce(p))throw new me(p);l=t.unwrap(p.asSampled())}else l=p;return{binding:i,resource:l}}if("storageTexture"in o){let l;if(I(p)){if(!oe(p))throw new ae(p);o.access==="readonly"?l=t.unwrap(p.asReadonly()):o.access==="mutable"?l=t.unwrap(p.asMutable()):l=t.unwrap(p.asReadonly())}else l=p;return{binding:i,resource:l}}if("externalTexture"in o||"sampler"in o)return{binding:i,resource:p};throw new Error(`Malformed bind group entry: ${p} (${JSON.stringify(p)})`)}).filter(a=>a!==null)})}};var ht="#CATCHALL#",Oe=class{constructor(){s(this,"_stack",[]);s(this,"_itemDepth",0)}get itemDepth(){return this._itemDepth}get topItem(){let t=this._stack[this._stack.length-1];if(!t||t.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return t}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}pushSlotBindings(t){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(t)})}pushFunctionScope(t,r,n){this._stack.push({type:"functionScope",args:t,returnType:r,externalMap:n})}pop(){let t=this._stack.pop();(t==null?void 0:t.type)==="item"&&this._itemDepth--}readSlot(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="item")n.usedSlots.add(t);else if((n==null?void 0:n.type)==="slotBinding"){let a=n.bindingMap.get(t);if(a!==void 0)return a}else if(!((n==null?void 0:n.type)==="functionScope"||(n==null?void 0:n.type)==="blockScope"))throw new Error("Unknown layer type.")}return t.defaultValue}getResourceById(t){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="functionScope"){let a=n.args.find(i=>i.value===t);if(a!==void 0)return a;let o=n.externalMap[t];return o!==void 0?{value:o,dataType:S}:void 0}if((n==null?void 0:n.type)==="blockScope"){let a=n.declarations.get(t);if(a!==void 0)return{value:t,dataType:a}}}}},Te=[""," "," "," "," "," "," "," "," "],$e=Te.length-1,We=class{constructor(){s(this,"identLevel",0)}get pre(){var t;return(t=Te[this.identLevel])!=null?t:Te[$e].repeat(this.identLevel/$e)+Te[this.identLevel%$e]}indent(){let t=this.pre;return this.identLevel++,t}dedent(){return this.identLevel--,this.pre}},Ne=class{constructor(t){s(this,"_memoizedResolves",new WeakMap);s(this,"_indentController",new We);s(this,"_jitTranspiler");s(this,"_itemStateStack",new Oe);s(this,"_declarations",[]);s(this,"bindGroupLayoutsToPlaceholderMap",new Map);s(this,"_nextFreeLayoutPlaceholderIdx",0);s(this,"fixedBindings",[]);s(this,"names");this.names=t.names,this._jitTranspiler=t.jitTranspiler}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(t){var r;return(r=this._itemStateStack.getResourceById(t))!=null?r:{value:t,dataType:S}}transpileFn(t){if(!this._jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._jitTranspiler.transpileFn(t)}fnToWgsl(t){this._itemStateStack.pushFunctionScope(t.args,t.returnType,t.externalMap);let r=Be(this,t.body);this._itemStateStack.pop();let n=t.args.map(a=>`${a.value}: ${this.resolve(a.dataType)}`).join(", ");return{head:t.returnType!==void 0?`(${n}) -> ${this.resolve(t.returnType)}`:`(${n})`,body:r}}addDeclaration(t){this._declarations.push(t)}allocateLayoutEntry(t){let r=this.bindGroupLayoutsToPlaceholderMap,n=r.get(t);return n||(n=`#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`,r.set(t,n)),n}allocateFixedEntry(t,r){let n=this.fixedBindings.length;return this.fixedBindings.push({layoutEntry:t,resource:r}),{group:ht,binding:n}}readSlot(t){let r=this._itemStateStack.readSlot(t);if(r===void 0)throw new ne(t);return r}unwrap(t){let r=t;for(;pt(r);)r=this.readSlot(r);return r}_getOrInstantiate(t){var n;let r=(n=this._memoizedResolves.get(t))!=null?n:[];this._itemStateStack.pushItem();try{for(let i of r)if([...i.slotToValueMap.entries()].every(([g,l])=>this._itemStateStack.readSlot(g)===l))return i.result;let a=M(t)?De(this,t):t.resolve(this),o=new Map;for(let i of this._itemStateStack.topItem.usedSlots)o.set(i,this._itemStateStack.readSlot(i));return r.push({slotToValueMap:o,result:a}),this._memoizedResolves.set(t,r),a}catch(a){throw a instanceof O?a.appendToTrace(t):new O(a,[t])}finally{this._itemStateStack.pop()}}resolve(t,r=[]){if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return String(t);let n=!1;r.length>0&&(n=!0,this._itemStateStack.pushSlotBindings(r));try{if(this._itemStateStack.itemDepth===0){let a=Qe(()=>this._getOrInstantiate(t));return`${[...this._declarations].join(`
|
9
15
|
|
10
|
-
`)}${a}`}return this._getOrInstantiate(
|
11
|
-
@builtin(${N(p.builtinSymbol)}) ${h}: ${X(p.builtinSymbol)},
|
12
|
-
`}),...a.map(({name:p,varInfo:h,index:E})=>g`
|
13
|
-
@location(${E}) ${p}: ${h},
|
14
|
-
`)],u=new _({names:(ke=e.nameRegistry)!=null?ke:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});u.resolve(this.vertexRoot);let l=Array.from(u.usedBindables).filter(p=>p.usage==="vertex").map((p,h)=>({idx:h,entry:{bindable:p,underlyingType:p.allocatable.dataType}})),d=l.map(p=>g`
|
15
|
-
@location(${p.idx}) ${p.entry.bindable} : ${"expressionCode"in p.entry.underlyingType?p.entry.underlyingType.expressionCode:p.entry.underlyingType.elementType},
|
16
|
-
`),c=[...Array.from(u.usedBuiltins).map(p=>g`
|
17
|
-
@builtin(${N(p)}) ${te(p)}: ${X(p)},
|
18
|
-
`),...d],w=g`
|
19
|
-
struct VertexOutput {
|
20
|
-
${i}
|
21
|
-
};
|
16
|
+
`)}${a}`}return this._getOrInstantiate(t)}finally{n&&this._itemStateStack.pop()}}};function Y(e,t){var f;let r=new Ne(t),n=r.resolve(e),a=r.bindGroupLayoutsToPlaceholderMap,o=[],i=new Set([...a.keys()].map(m=>m.index).filter(m=>m!==void 0)),p=it(i),g=r.fixedBindings.map((m,c)=>[String(c),m.layoutEntry]),l=()=>{let m=p.next().value,c=ge(Object.fromEntries(g));return o[m]=c,n=n.replaceAll(ht,String(m)),[m,c.populate(Object.fromEntries(r.fixedBindings.map((b,A)=>[String(A),b.resource])))]},d=g.length>0?l():null;for(let[m,c]of a.entries()){let b=(f=m.index)!=null?f:p.next().value;o[b]=m,n=n.replaceAll(c,String(b))}return{code:n,bindGroupLayouts:o,catchall:d}}function wt(e){return!!e&&(typeof e=="object"||typeof e=="function")&&"$name"in e}function Dt(e,t){for(let[r,n]of Object.entries(t))e[r]=n,wt(n)&&(!("label"in n)||n.label===void 0)&&n.$name(r)}function St(e,t,r){return Object.entries(t).reduce((n,[a,o])=>{let i=j(o)||M(o)?e.resolve(o):String(o);return n.replaceAll(new RegExp(`(?<![\\w_])${a}(?![\\w_])`,"g"),i)},r)}function Ut(e){let{input:t,extraDependencies:r,names:n,jitTranspiler:a}=e,o={};Dt(o,r!=null?r:{});let i=(Array.isArray(t)?t:[t]).filter(d=>typeof d=="string"),p=(Array.isArray(t)?t:[t]).filter(d=>typeof d!="string"),g={resolve(d){let f=i.join(`
|
22
17
|
|
23
|
-
|
24
|
-
fn main(${c}) -> VertexOutput {
|
25
|
-
${this.vertexRoot}
|
26
|
-
var output: VertexOutput;
|
27
|
-
${n.map(p=>g`
|
28
|
-
output.${p.name} = ${p.name};
|
29
|
-
`)}
|
30
|
-
${a.map(({name:p})=>g`
|
31
|
-
output.${p} = ${p};
|
32
|
-
`)}
|
33
|
-
return output;
|
34
|
-
}
|
35
|
-
`,U=new _({names:(Ie=e.nameRegistry)!=null?Ie:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});U.resolve(this.fragmentRoot);let Q=Array.from(U.usedBuiltins).map(p=>g`
|
36
|
-
@builtin(${N(p)}) ${te(p)}: ${X(p)},
|
37
|
-
`),Z=a.map(({name:p,varInfo:h},E)=>g`
|
38
|
-
@location(${E}) ${p}: ${h},
|
39
|
-
`),lt=[...Q,...Z],dt=g`
|
40
|
-
@fragment
|
41
|
-
fn main(${lt}) -> @location(0) vec4f {
|
42
|
-
${this.fragmentRoot}
|
43
|
-
}
|
44
|
-
`,$e=new $(this.root,w).build({bindingGroup:e.bindingGroup,shaderStage:GPUShaderStage.VERTEX,nameRegistry:(Ce=e.nameRegistry)!=null?Ce:new S}),gt=new $(this.root,dt).build({bindingGroup:e.bindingGroup+1,shaderStage:GPUShaderStage.FRAGMENT,nameRegistry:(Fe=e.nameRegistry)!=null?Fe:new S});return $e.bindGroupResolver.setVertexBuffers(l.map(p=>({index:p.idx,buffer:p.entry.bindable}))),{vertexProgram:$e,fragmentProgram:gt}}},pe=class{constructor(e,r,n){this.root=e;this.computeRoot=r;this.workgroupSize=n}build(e){var l,d,T,m;let r=new _({names:(l=e.nameRegistry)!=null?l:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});r.resolve(this.computeRoot);let a=Array.from(r.usedBuiltins).map(c=>g`
|
45
|
-
@builtin(${N(c)}) ${te(c)}: ${X(c)},
|
46
|
-
`),i=`@workgroup_size(${this.workgroupSize[0]}, ${(d=this.workgroupSize[1])!=null?d:1}, ${(T=this.workgroupSize[2])!=null?T:1})`,u=g`
|
47
|
-
@compute ${i}
|
48
|
-
fn main(${a}) {
|
49
|
-
${this.computeRoot}
|
50
|
-
}
|
51
|
-
`;return new $(this.root,u).build({bindingGroup:e.bindingGroup,shaderStage:GPUShaderStage.COMPUTE,nameRegistry:(m=e.nameRegistry)!=null?m:new S})}};import{BufferReader as Ue,BufferWriter as Ee}from"typed-binary";function le(t,e,r){return new De(t,e,r)}function A(t){return t.resourceType==="buffer"}function de(t){return!!t.usableAsUniform}function ge(t){return!!t.usableAsStorage}function bt(t){return!!t.usableAsVertex}var De=class{constructor(e,r,n){this._group=e;this.dataType=r;this.initialOrBuffer=n;o(this,"resourceType","buffer");o(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);o(this,"_device",null);o(this,"_buffer",null);o(this,"_destroyed",!1);o(this,"_subscription",null);o(this,"_label");o(this,"initial");o(this,"usableAsUniform",!1);o(this,"usableAsStorage",!1);o(this,"usableAsVertex",!1);Je(n)?this._buffer=n:this.initial=n}get label(){return this._label}get buffer(){if(!this._device)throw new Error("Create this buffer using `root.createBuffer` instead of `tgpu.createBuffer`.");if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=this._device.createBuffer({size:this.dataType.size,usage:this.flags,mappedAtCreation:!!this.initial}),this.initial)){let e=new Ee(this._buffer.getMappedRange());if(Xe(this.initial)){let r=this._group;if(!r)throw new Error("Create this buffer using `root.createBuffer` instead of `tgpu.createBuffer`.");let n=this.initial;this.dataType.write(e,r.readPlum(n)),this._subscription=r.onPlumChange(n,()=>{this.write(r.readPlum(n))})}else this.dataType.write(e,this.initial);this._buffer.unmap()}return this._buffer}get device(){if(!this._device)throw new Error("This buffer has not been assigned a device. Use .$device(device) to assign a device");return this._device}get destroyed(){return this._destroyed}$name(e){return this._label=e,this}$usage(...e){for(let r of e)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(e){return this.flags|=e,this}$device(e){return this._device=e,this}write(e){let r=this.buffer,n=this.device;if(r.mapState==="mapped"){let i=r.getMappedRange();if(A(e))throw new Error("Cannot copy to a mapped buffer.");this.dataType.write(new Ee(i),e);return}let a=this.dataType.size;if(A(e)){let i=e.buffer;if(this._group)this._group.commandEncoder.copyBufferToBuffer(i,0,r,0,a);else{let u=n.createCommandEncoder();u.copyBufferToBuffer(i,0,r,0,a),n.queue.submit([u.finish()])}}else{this._group&&this._group.flush();let i=new ArrayBuffer(a);this.dataType.write(new Ee(i),e),n.queue.writeBuffer(r,0,i,0,a)}}async read(){this._group&&this._group.flush();let e=this.buffer,r=this.device;if(e.mapState==="mapped"){let u=e.getMappedRange();return this.dataType.read(new Ue(u))}if(e.usage&GPUBufferUsage.MAP_READ){await e.mapAsync(GPUMapMode.READ);let u=e.getMappedRange(),s=this.dataType.read(new Ue(u));return e.unmap(),s}let n=r.createBuffer({size:this.dataType.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(e,0,n,0,this.dataType.size),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,this.dataType.size);let i=this.dataType.read(new Ue(n.getMappedRange()));return n.unmap(),n.destroy(),i}destroy(){var e;this._destroyed||(this._destroyed=!0,this._subscription&&this._subscription(),(e=this._buffer)==null||e.destroy())}toString(){var e;return`buffer:${(e=this._label)!=null?e:"<unnamed>"}`}};function Re(t){return!!t&&t.resourceType==="buffer-usage"}function rt(t){return new _e(t)}function nt(t){return!!t&&t.resourceType==="bind-group-layout"}function at(t){return!!t&&t.resourceType==="bind-group"}var Ge=class t extends Error{constructor(e,r){super(`Bind group '${e!=null?e:"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,t.prototype)}},tt=["compute"],k=["compute","vertex","fragment"],_e=class{constructor(e){this.entries=e;o(this,"_label");o(this,"resourceType","bind-group-layout");o(this,"bound",{})}get label(){return this._label}$name(e){return this._label=e,this}unwrap(e){var n;return e.device.createBindGroupLayout({label:(n=this.label)!=null?n:"",entries:Object.values(this.entries).map((a,i)=>{var l,d,T,m;if(a===null)return null;let u=a.visibility,s={binding:i,visibility:0};if("uniform"in a)u=u!=null?u:k,s.buffer={type:"uniform"};else if("storage"in a)u=u!=null?u:a.access==="mutable"?tt:k,s.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)u=u!=null?u:k,s.sampler={type:a.sampler};else if("texture"in a)u=u!=null?u:k,s.texture={sampleType:a.texture,viewDimension:(l=a.viewDimension)!=null?l:"2d",multisampled:(d=a.multisampled)!=null?d:!1};else if("storageTexture"in a){let c=(T=a.access)!=null?T:"writeonly";u=u!=null?u:c==="readonly"?k:tt,s.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[c],viewDimension:(m=a.viewDimension)!=null?m:"2d"}}else"externalTexture"in a&&(u=u!=null?u:k,s.externalTexture={});return u!=null&&u.includes("compute")&&(s.visibility|=GPUShaderStage.COMPUTE),u!=null&&u.includes("vertex")&&(s.visibility|=GPUShaderStage.VERTEX),u!=null&&u.includes("fragment")&&(s.visibility|=GPUShaderStage.FRAGMENT),s}).filter(a=>a!==null)})}populate(e){return new Ae(this,e)}},Ae=class{constructor(e,r){this.layout=e;this.entries=r;o(this,"resourceType","bind-group");for(let n of Object.keys(e.entries))if(e.entries[n]!==null&&!(n in r))throw new Ge(e.label,n)}unwrap(e){var n;return e.device.createBindGroup({label:(n=this.layout.label)!=null?n:"",layout:e.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([a,i],u)=>{var l;if(i===null)return null;let s=this.entries[a];if(s===void 0)throw new Error(`'${a}' is a resource required to populate bind group layout '${(l=this.layout.label)!=null?l:"<unnamed>"}'.`);if("uniform"in i){let d;if(A(s)){if(!de(s))throw new z(s);d={buffer:e.unwrap(s)}}else if(Re(s)){if(!de(s.allocatable))throw new z(s.allocatable);d={buffer:e.unwrap(s.allocatable)}}else d={buffer:s};return{binding:u,resource:d}}if("storage"in i){let d;if(A(s)){if(!ge(s))throw new z(s);d={buffer:e.unwrap(s)}}else if(Re(s)){if(!ge(s.allocatable))throw new z(s.allocatable);d={buffer:e.unwrap(s.allocatable)}}else d={buffer:s};return{binding:u,resource:d}}if("texture"in i||"storageTexture"in i||"externalTexture"in i||"sampler"in i)return{binding:u,resource:s};throw new Error(`Malformed bind group entry: ${s} (${JSON.stringify(s)})`)}).filter(a=>a!==null)})}};var ce=class{constructor(e,r){this.device=e;this.jitTranspiler=r;o(this,"_buffers",[]);o(this,"_samplers",new WeakMap);o(this,"_textures",new WeakMap);o(this,"_textureViews",new WeakMap);o(this,"_externalTexturesStatus",new WeakMap);o(this,"_unwrappedBindGroupLayouts",new H(e=>e.unwrap(this)));o(this,"_unwrappedBindGroups",new H(e=>e.unwrap(this)));o(this,"_pipelineExecutors",[]);o(this,"_commandEncoder",null);o(this,"_plumStore",new ne)}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(e,r){let n=le(this,e,r).$device(this.device);return this._buffers.push(n),n}destroy(){for(let e of this._buffers)e.destroy()}unwrap(e){if(A(e))return e.buffer;if(nt(e))return this._unwrappedBindGroupLayouts.getOrMake(e);if(at(e))return this._unwrappedBindGroups.getOrMake(e);throw new Error(`Unknown resource type: ${e}`)}textureFor(e){let r;"texture"in e?r=e.texture:r=e;let n=this._textures.get(r);if(!n){let a=O(M({},r.descriptor),{usage:r.flags});if(n=this.device.createTexture(a),!n)throw new Error(`Failed to create texture for ${e}`);this._textures.set(r,n)}return n}viewFor(e){let r=this._textureViews.get(e);return r||(r=this.textureFor(e.texture).createView(e.descriptor),this._textureViews.set(e,r)),r}externalTextureFor(e){if(this._externalTexturesStatus.set(e,"clean"),e.descriptor.source===void 0)throw new Error("External texture source needs to be defined before use");return this.device.importExternalTexture(e.descriptor)}samplerFor(e){let r=this._samplers.get(e);if(!r){if(r=this.device.createSampler(e.descriptor),!r)throw new Error(`Failed to create sampler for ${e}`);this._samplers.set(e,r)}return r}setSource(e,r){this._externalTexturesStatus.set(e,"dirty"),e.descriptor.source=r}isDirty(e){return this._externalTexturesStatus.get(e)==="dirty"}markClean(e){this._externalTexturesStatus.set(e,"clean")}readPlum(e){return this._plumStore.get(e)}setPlum(e,r){if(typeof r=="function"){let n=r;this._plumStore.set(e,n(this._plumStore.get(e)))}else this._plumStore.set(e,r)}onPlumChange(e,r){return this._plumStore.subscribe(e,r)}makeRenderPipeline(e){var d,T,m,c,w,U,fe,Q,Z;let{vertexProgram:r,fragmentProgram:n}=new se(this,e.vertex.code,e.fragment.code,e.vertex.output).build({bindingGroup:((d=e.externalLayouts)!=null?d:[]).length}),a=this.device.createShaderModule({code:r.code}),i=this.device.createShaderModule({code:n.code}),u=this.device.createPipelineLayout({label:(T=e.label)!=null?T:"",bindGroupLayouts:[...(m=e.externalLayouts)!=null?m:[],r.bindGroupResolver.getBindGroupLayout(),n.bindGroupResolver.getBindGroupLayout()]}),s=this.device.createRenderPipeline({label:(c=e.label)!=null?c:"",layout:u,vertex:{module:a,buffers:(w=r.bindGroupResolver.getVertexBufferDescriptors())!=null?w:[]},fragment:{module:i,targets:(fe=(U=e.fragment)==null?void 0:U.target)!=null?fe:[]},primitive:e.primitive}),l=new Ve(this,s,r,n,(Z=(Q=e.externalLayouts)==null?void 0:Q.length)!=null?Z:0);return this._pipelineExecutors.push(l),l}makeComputePipeline(e){var s,l,d,T,m;let r=ee(()=>{var c,w;return new pe(this,e.code,(c=e.workgroupSize)!=null?c:[1]).build({bindingGroup:((w=e.externalLayouts)!=null?w:[]).length})}),n=this.device.createShaderModule({code:r.code}),a=this.device.createPipelineLayout({label:(s=e.label)!=null?s:"",bindGroupLayouts:[...(l=e.externalLayouts)!=null?l:[],r.bindGroupResolver.getBindGroupLayout()]}),i=this.device.createComputePipeline({label:(d=e.label)!=null?d:"",layout:a,compute:{module:n}}),u=new Le(this,i,[r],(m=(T=e.externalLayouts)==null?void 0:T.length)!=null?m:0);return this._pipelineExecutors.push(u),u}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}},Ve=class{constructor(e,r,n,a,i,u){this.root=e;this.pipeline=r;this.vertexProgram=n;this.fragmentProgram=a;this.externalLayoutCount=i;this.label=u}execute(e){var T,m,c;let d=e,{vertexCount:r,instanceCount:n,firstVertex:a,firstInstance:i,externalBindGroups:u}=d,s=Me(d,["vertexCount","instanceCount","firstVertex","firstInstance","externalBindGroups"]);if(((T=u==null?void 0:u.length)!=null?T:0)!==this.externalLayoutCount)throw new Error(`External bind group count doesn't match the external bind group layout configuration. Expected ${this.externalLayoutCount}, got: ${(m=u==null?void 0:u.length)!=null?m:0}`);let l=this.root.commandEncoder.beginRenderPass(O(M({},s),{label:(c=this.label)!=null?c:""}));l.setPipeline(this.pipeline),(u!=null?u:[]).forEach((w,U)=>l.setBindGroup(U,w)),l.setBindGroup((u!=null?u:[]).length,this.vertexProgram.bindGroupResolver.getBindGroup()),l.setBindGroup((u!=null?u:[]).length+1,this.fragmentProgram.bindGroupResolver.getBindGroup());for(let[w,U]of this.vertexProgram.bindGroupResolver.getVertexBuffers())l.setVertexBuffer(U,w.allocatable.buffer);l.draw(r,n,a,i),l.end()}},Le=class{constructor(e,r,n,a,i){this.root=e;this.pipeline=r;this.programs=n;this.externalLayoutCount=a;this.label=i}execute(e){var i,u,s;let{workgroups:r=[1,1],externalBindGroups:n}=e!=null?e:{};if(((i=n==null?void 0:n.length)!=null?i:0)!==this.externalLayoutCount)throw new Error(`External bind group count doesn't match the external bind group layout configuration. Expected ${this.externalLayoutCount}, got: ${(u=n==null?void 0:n.length)!=null?u:0}`);let a=this.root.commandEncoder.beginComputePass({label:(s=this.label)!=null?s:""});a.setPipeline(this.pipeline),(n!=null?n:[]).forEach((l,d)=>a.setBindGroup(d,l)),this.programs.forEach((l,d)=>a.setBindGroup((n!=null?n:[]).length+d,l.bindGroupResolver.getBindGroup())),a.dispatchWorkgroups(...r),a.end()}};async function ut(t){if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let e=await navigator.gpu.requestAdapter(t==null?void 0:t.adapter);if(!e)throw new Error("Could not find a compatible GPU");return new ce(await e.requestDevice(t==null?void 0:t.device),t==null?void 0:t.unstable_jitTranspiler)}function it(t){return new ce(t.device,t.unstable_jitTranspiler)}function ot(t,e){return le(void 0,t,e)}function st(t,e){t.write(e)}async function pt(t){return t.read()}var I=t=>Math.sqrt(t.x**2+t.y**2),C=t=>Math.sqrt(t.x**2+t.y**2+t.z**2),F=t=>Math.sqrt(t.x**2+t.y**2+t.z**2+t.w**2),R={length:{vec2f:I,vec2i:I,vec2u:I,vec3f:C,vec3i:C,vec3u:C,vec4f:F,vec4i:F,vec4u:F},add:{vec2f:(t,e)=>W(t.x+e.x,t.y+e.y),vec2i:(t,e)=>K(t.x+e.x,t.y+e.y),vec2u:(t,e)=>q(t.x+e.x,t.y+e.y),vec3f:(t,e)=>V(t.x+e.x,t.y+e.y,t.z+e.z),vec3i:(t,e)=>L(t.x+e.x,t.y+e.y,t.z+e.z),vec3u:(t,e)=>P(t.x+e.x,t.y+e.y,t.z+e.z),vec4f:(t,e)=>D(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w),vec4i:(t,e)=>J(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w),vec4u:(t,e)=>Y(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w)},sub:{vec2f:(t,e)=>W(t.x-e.x,t.y-e.y),vec2i:(t,e)=>K(t.x-e.x,t.y-e.y),vec2u:(t,e)=>q(t.x-e.x,t.y-e.y),vec3f:(t,e)=>V(t.x-e.x,t.y-e.y,t.z-e.z),vec3i:(t,e)=>L(t.x-e.x,t.y-e.y,t.z-e.z),vec3u:(t,e)=>P(t.x-e.x,t.y-e.y,t.z-e.z),vec4f:(t,e)=>D(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w),vec4i:(t,e)=>J(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w),vec4u:(t,e)=>Y(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w)},mul:{vec2f:(t,e)=>W(t*e.x,t*e.y),vec2i:(t,e)=>K(t*e.x,t*e.y),vec2u:(t,e)=>q(t*e.x,t*e.y),vec3f:(t,e)=>V(t*e.x,t*e.y,t*e.z),vec3i:(t,e)=>L(t*e.x,t*e.y,t*e.z),vec3u:(t,e)=>P(t*e.x,t*e.y,t*e.z),vec4f:(t,e)=>D(t*e.x,t*e.y,t*e.z,t*e.w),vec4i:(t,e)=>J(t*e.x,t*e.y,t*e.z,t*e.w),vec4u:(t,e)=>Y(t*e.x,t*e.y,t*e.z,t*e.w)},dot:{vec2f:(t,e)=>t.x*e.x+t.y*e.y,vec2i:(t,e)=>t.x*e.x+t.y*e.y,vec2u:(t,e)=>t.x*e.x+t.y*e.y,vec3f:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec3i:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec3u:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec4f:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w,vec4i:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w,vec4u:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w},normalize:{vec2f:t=>{let e=I(t);return W(t.x/e,t.y/e)},vec2i:t=>{let e=I(t);return K(t.x/e,t.y/e)},vec2u:t=>{let e=I(t);return q(t.x/e,t.y/e)},vec3f:t=>{let e=C(t);return V(t.x/e,t.y/e,t.z/e)},vec3i:t=>{let e=C(t);return L(t.x/e,t.y/e,t.z/e)},vec3u:t=>{let e=C(t);return P(t.x/e,t.y/e,t.z/e)},vec4f:t=>{let e=F(t);return D(t.x/e,t.y/e,t.z/e,t.w/e)},vec4i:t=>{let e=F(t);return J(t.x/e,t.y/e,t.z/e,t.w/e)},vec4u:t=>{let e=F(t);return Y(t.x/e,t.y/e,t.z/e,t.w/e)}},cross:{vec3f:(t,e)=>V(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x),vec3i:(t,e)=>L(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x),vec3u:(t,e)=>P(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x)}};var wt={add(t,e){return B()?`(${t} + ${e})`:R.add[t.kind](t,e)},sub(t,e){return B()?`(${t} - ${e})`:R.sub[t.kind](t,e)},mul:(t,e)=>B()?`(${t} * ${e})`:R.mul[e.kind](t,e),dot(t,e){return B()?`dot(${t}, ${e})`:R.dot[t.kind](t,e)},normalize:t=>B()?`normalize(${t})`:R.normalize[t.kind](t),cross(t,e){return B()?`cross(${t}, ${e})`:R.cross[t.kind](t,e)},fract(t){return B()?`fract(${t})`:t-Math.floor(t)},length(t){return B()?`length(${t})`:R.length[t.kind](t)},sin(t){return B()?`sin(${t})`:Math.sin(t)},cos(t){return B()?`cos(${t})`:Math.cos(t)}};var Bt={Uniform:"uniform",Storage:"storage",Vertex:"vertex",bindGroupLayout:rt,init:ut,initFromDevice:it,createBuffer:ot,read:pt,write:st},Yr=Bt;export{ct as RecursiveDataTypeError,Yr as default,ge as isUsableAsStorage,de as isUsableAsUniform,bt as isUsableAsVertex,wt as std,Bt as tgpu};
|
18
|
+
`);for(let m of p)d.resolve(m);return St(d,o,f)}},{code:l}=Y(g,{names:n==="strict"?new k:new V,jitTranspiler:a});return l}var re=class{constructor(t){this._make=t;s(this,"_map",new WeakMap)}getOrMake(t,...r){if(this._map.has(t))return this._map.get(t);let n=this._make(t,...r);return this._map.set(t,n),n}};function vt(e,t,r){return new je(new ze(e,t,r),{})}function Bt(e){return(e==null?void 0:e.resourceType)==="compute-pipeline"}var je=class e{constructor(t,r){this._core=t;this._priors=r;s(this,"resourceType","compute-pipeline")}get label(){return this._core.label}get rawPipeline(){return this._core.unwrap().pipeline}with(t,r){var n;return new e(this._core,{bindGroupLayoutMap:new Map([...(n=this._priors.bindGroupLayoutMap)!=null?n:[],[t,r]])})}dispatchWorkgroups(t,r,n){var i;let a=this._core.unwrap(),o=this._core.branch.commandEncoder.beginComputePass({label:(i=this._core.label)!=null?i:"<unnamed>"});o.setPipeline(a.pipeline),a.bindGroupLayouts.forEach((p,g)=>{var l;if(a.catchall&&g===a.catchall[0])o.setBindGroup(g,this._core.branch.unwrap(a.catchall[1]));else{let d=(l=this._priors.bindGroupLayoutMap)==null?void 0:l.get(p);if(d===void 0)throw new N(p.label);o.setBindGroup(g,this._core.branch.unwrap(d))}}),o.dispatchWorkgroups(t,r,n),o.end()}$name(t){return this._core.label=t,this}},ze=class{constructor(t,r,n){this.branch=t;this._slotBindings=r;this._entryFn=n;s(this,"label");s(this,"_memo")}unwrap(){var t,r,n,a,o;if(this._memo===void 0){let i=this.branch.device,{code:p,bindGroupLayouts:g,catchall:l}=Y({resolve:d=>(d.resolve(this._entryFn,this._slotBindings),"")},{names:this.branch.nameRegistry,jitTranspiler:this.branch.jitTranspiler});l!==null&&((r=g[l[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`)),this._memo={pipeline:i.createComputePipeline({label:(n=this.label)!=null?n:"<unnamed>",layout:i.createPipelineLayout({label:`${(a=this.label)!=null?a:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:g.map(d=>this.branch.unwrap(d))}),compute:{module:i.createShaderModule({label:`${(o=this.label)!=null?o:"<unnamed>"} - Shader`,code:p})}}),bindGroupLayouts:g,catchall:l}}return this._memo}};function Kt(e){return typeof(e==null?void 0:e.format)=="string"}function Ft(e,t){var i,p;let r=[];if($(e)){if(!Kt(t))throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");return r.push(t._layout),{usedVertexLayouts:r,bufferDefinitions:[{arrayStride:t._layout.stride,stepMode:t._layout.stepMode,attributes:[{format:t.format,offset:t.offset,shaderLocation:(i=ce(e))!=null?i:0}]}]}}let n=[],a=new WeakMap,o=0;for(let[g,l]of Object.entries(e)){if(et(l))continue;let d=t[g];if(!d)throw new Error(`An attribute by the name of '${g}' was not provided to the shader.`);let f=d._layout,m=a.get(f);m||(r.push(f),m=[],n.push({arrayStride:f.stride,stepMode:f.stepMode,attributes:m}),a.set(f,m)),o=(p=ce(l))!=null?p:o,m.push({format:d.format,offset:d.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}function _t(e){return(e==null?void 0:e.resourceType)==="vertex-layout"}function Jt(e){return typeof(e==null?void 0:e.loadOp)=="string"}function At(e,t){if($(e)){if(!Jt(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 Yt(e){return typeof(e==null?void 0:e.format)=="string"}function Et(e,t){if($(e)){if(!Yt(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 Pt(e){return new qe(new Ke(e),{})}var qe=class e{constructor(t,r){this._core=t;this._priors=r;s(this,"resourceType","render-pipeline")}get label(){return this._core.label}$name(t){return this._core.label=t,this}with(t,r){var n,a;if(fe(t))return new e(this._core,R(E({},this._priors),{bindGroupLayoutMap:new Map([...(n=this._priors.bindGroupLayoutMap)!=null?n:[],[t,r]])}));if(_t(t))return new e(this._core,R(E({},this._priors),{vertexLayoutMap:new Map([...(a=this._priors.vertexLayoutMap)!=null?a:[],[t,r]])}));throw new Error("Unsupported value passed into .with()")}withColorAttachment(t){return new e(this._core,R(E({},this._priors),{colorAttachment:t}))}draw(t,r,n,a){var d,f;let o=this._core.unwrap(),{branch:i,fragmentFn:p}=this._core.options,g=At(p.shell.returnType,(d=this._priors.colorAttachment)!=null?d:{}).map(m=>I(m.view)?R(E({},m),{view:i.unwrap(m.view).createView()}):m),l=i.commandEncoder.beginRenderPass({label:(f=this._core.label)!=null?f:"<unnamed>",colorAttachments:g});l.setPipeline(o.pipeline),o.bindGroupLayouts.forEach((m,c)=>{var b;if(o.catchall&&c===o.catchall[0])l.setBindGroup(c,i.unwrap(o.catchall[1]));else{let A=(b=this._priors.bindGroupLayoutMap)==null?void 0:b.get(m);if(A===void 0)throw new N(m.label);l.setBindGroup(c,i.unwrap(A))}}),this._core.usedVertexLayouts.forEach((m,c)=>{var A,C;let b=(A=this._priors.vertexLayoutMap)==null?void 0:A.get(m);if(!b)throw new Error(`Missing vertex buffer for layout '${(C=m.label)!=null?C:"<unnamed>"}'. Please provide it using pipeline.with(layout, buffer).(...)`);l.setVertexBuffer(c,i.unwrap(b))}),l.draw(t,r,n,a),l.end()}},Ke=class{constructor(t){this.options=t;s(this,"label");s(this,"usedVertexLayouts");s(this,"_memo");s(this,"_vertexBufferLayouts");s(this,"_targets");let r=Ft(t.vertexFn.shell.argTypes[0],t.vertexAttribs);this._vertexBufferLayouts=r.bufferDefinitions,this.usedVertexLayouts=r.usedVertexLayouts,this._targets=Et(t.fragmentFn.shell.returnType,t.targets)}unwrap(){var t,r,n,a,o;if(this._memo===void 0){let{branch:i,vertexFn:p,fragmentFn:g,slotBindings:l,primitiveState:d}=this.options,{code:f,bindGroupLayouts:m,catchall:c}=Y({resolve:C=>(C.resolve(p,l),C.resolve(g,l),"")},{names:i.nameRegistry,jitTranspiler:i.jitTranspiler});c!==null&&((r=m[c[0]])==null||r.$name(`${(t=this.label)!=null?t:"<unnamed>"} - Automatic Bind Group & Layout`));let b=i.device,A=b.createShaderModule({label:`${(n=this.label)!=null?n:"<unnamed>"} - Shader`,code:f});this._memo={pipeline:b.createRenderPipeline({label:(a=this.label)!=null?a:"<unnamed>",layout:b.createPipelineLayout({label:`${(o=this.label)!=null?o:"<unnamed>"} - Pipeline Layout`,bindGroupLayouts:m.map(C=>i.unwrap(C))}),vertex:{module:A,buffers:this._vertexBufferLayouts},fragment:{module:A,targets:this._targets},primitive:d!=null?d:{}}),bindGroupLayouts:m,catchall:c}}return this._memo}};var Je=class e{constructor(t,r){this._getRoot=t;this._slotBindings=r}with(t,r){return new e(this._getRoot,[...this._slotBindings,[t,r]])}withCompute(t){return new Ye(this._getRoot(),this._slotBindings,t)}withVertex(t,r){return new He({branch:this._getRoot(),primitiveState:void 0,slotBindings:this._slotBindings,vertexFn:t,vertexAttribs:r})}},Ye=class{constructor(t,r,n){this._root=t;this._slotBindings=r;this._entryFn=n}createPipeline(){return vt(this._root,this._slotBindings,this._entryFn)}},He=class{constructor(t){this._options=t}withFragment(t,r,n){return Z(typeof t!="string","Just type mismatch validation"),Z(typeof r!="string","Just type mismatch validation"),new Xe(R(E({},this._options),{fragmentFn:t,targets:r}))}},Xe=class e{constructor(t){this._options=t}withPrimitive(t){return new e(R(E({},this._options),{primitiveState:t}))}createPipeline(){return Pt(this._options)}},ye=class extends Je{constructor(r,n,a,o){super(()=>this,[]);this.device=r;this.nameRegistry=n;this.jitTranspiler=a;this._ownDevice=o;s(this,"_disposables",[]);s(this,"_unwrappedBindGroupLayouts",new re(r=>r.unwrap(this)));s(this,"_unwrappedBindGroups",new re(r=>r.unwrap(this)));s(this,"_commandEncoder",null)}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(r,n){let a=mt(this,r,n).$device(this.device);return this._disposables.push(a),a}createTexture(r){let n=yt(r,this);return this._disposables.push(n),n}destroy(){for(let r of this._disposables)r.destroy();this._ownDevice&&this.device.destroy()}unwrap(r){if(Bt(r))return r.rawPipeline;if(fe(r))return this._unwrappedBindGroupLayouts.getOrMake(r);if(bt(r))return this._unwrappedBindGroups.getOrMake(r);if(G(r))return r.buffer;if(I(r)||Ge(r)||Ie(r))return r.unwrap();throw new Error(`Unknown resource type: ${r}`)}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}};async function Rt(e){let{adapter:t,device:r,unstable_names:n="random",unstable_jitTranspiler:a}=e!=null?e:{};if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let o=await navigator.gpu.requestAdapter(t);if(!o)throw new Error("Could not find a compatible GPU");return new ye(await o.requestDevice(r),n==="random"?new V:new k,a,!0)}function Lt(e){let{device:t,unstable_names:r="random",unstable_jitTranspiler:n}=e!=null?e:{};return new ye(t,r==="random"?new V:new k,n,!1)}var Ht={Uniform:"uniform",Storage:"storage",Vertex:"vertex",bindGroupLayout:ge,init:Rt,initFromDevice:Lt,resolve:Ut},ra=Ht;export{W as NotUniformError,O as ResolutionError,ra as default,G as isBuffer,zt as isComparisonSampler,Ie as isSampledTextureView,jt as isSampler,Ge as isStorageTextureView,I as isTexture,qt as isUsableAsRender,Ce as isUsableAsSampled,oe as isUsableAsStorage,Ee as isUsableAsUniform,Wt as isUsableAsVertex,Ht as tgpu};
|
52
19
|
//# sourceMappingURL=index.js.map
|