typegpu 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/chunk-5EPBCOO4.js +8 -0
- package/chunk-5EPBCOO4.js.map +1 -0
- package/chunk-SBJR5ZQJ.cjs +8 -0
- package/chunk-SBJR5ZQJ.cjs.map +1 -0
- package/data/index.cjs +1 -7
- package/data/index.cjs.map +1 -1
- package/data/index.d.cts +483 -50
- package/data/index.d.ts +483 -50
- package/data/index.js +1 -7
- package/data/index.js.map +1 -1
- package/index.cjs +51 -1
- package/index.cjs.map +1 -1
- package/index.d.cts +288 -6
- package/index.d.ts +288 -6
- package/index.js +51 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/{tgpuBuffer-BVk2wCHR.d.cts → types-CGmVkuAt.d.cts} +448 -109
- package/{tgpuBuffer-BVk2wCHR.d.ts → types-CGmVkuAt.d.ts} +448 -109
- package/chunk-2FWG5LPQ.js +0 -2
- package/chunk-2FWG5LPQ.js.map +0 -1
- package/chunk-7EYKOUWH.cjs +0 -2
- package/chunk-7EYKOUWH.cjs.map +0 -1
package/index.js
CHANGED
@@ -1,2 +1,52 @@
|
|
1
|
-
import{a as
|
1
|
+
import{A as Ye,B as g,H as He,P as W,Q as K,R as q,S as V,T as L,U as P,V as D,W as J,X as Y,a as M,b as O,c as Me,d as o,e as ee,f as B,g as Te,h as Oe,i as ct,j as z,l as me,m as G,o as ye,p as ze,q as Ne,r as N,s as te,t as v,u as j,v as je,w as We,x as Ke,y as qe,z as Je}from"./chunk-5EPBCOO4.js";var H=class{constructor(e){this._make=e;o(this,"_map",new WeakMap)}getOrMake(e,...r){if(this._map.has(e))return this._map.get(e);let n=this._make(e,...r);return this._map.set(e,n),n}};var ft=Symbol("This plum's value is sourced from outside the root.");function re(t){return t[ft]===!0}function Xe(t){return t.__brand==="TgpuPlum"}var ne=class{constructor(){o(this,"_stateMap",new WeakMap)}inspect(e){return this._stateMap.get(e)}_getState(e){let r=this._stateMap.get(e);if(!r){let{value:n,dependencies:a}=this._computeAndGatherDependencies(e);r={value:n,dependencies:a,version:0},this._stateMap.set(e,r)}return r}_notifyListeners(e){let r=this._getState(e);if(!r.active)return;let n=[...r.active.listeners];for(let a of n)a(r.value)}_computeAndGatherDependencies(e){let r=new Map,n=a=>{if(!r.has(a)){let i=this._getState(a);r.set(a,i.version)}return this.get(a)};return{value:e.compute(n),dependencies:r}}_recompute(e){let r=this._getState(e);if(r.active)for(let i of r.active.unsubs)i();let{value:n,dependencies:a}=this._computeAndGatherDependencies(e);if(r.dependencies=a,r.active)for(let[i]of r.dependencies)r.active.unsubs.add(this.subscribe(i,()=>{this._recompute(e)}));return Object.is(r.value,n)||(r.value=n,r.version=re(e)?e.version:r.version+1,this._notifyListeners(e)),r.value}get(e){let r=this._getState(e);if(r.active)return r.value;let n=!1;return re(e)?(e.compute(null),n=r.version!==e.version):r.dependencies.size>0&&(n=[...r.dependencies.entries()].some(([a,i])=>(this.get(a),this._getState(a).version!==i))),n?this._recompute(e):r.value}set(e,r){let n=this._getState(e);Object.is(n.value,r)||(n.value=r,n.version++,this._notifyListeners(e))}subscribe(e,r){let n=this._getState(e),a;if(!n.active){let i=new Set;n.active={listeners:new Set,unsubs:i};for(let[u]of n.dependencies)i.add(this.subscribe(u,()=>{this._recompute(e)}));re(e)&&(a=e.subscribe(()=>{this._recompute(e)}))}return n.active.listeners.add(r),()=>{if(n.active&&(n.active.listeners.delete(r),n.active.listeners.size===0)){for(let i of n.active.unsubs)i();a==null||a(),n.active=void 0}}}};var Tt={f32:"float32",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",u32:"uint32",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",i32:"sint32",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4"};function xe(t){if("expressionCode"in t){let e=t.expressionCode,r=Tt[e];if(!r)throw new Error(`Unsupported vertex format: ${e}`);return r}if("elementType"in t)return xe(t.elementType);throw new Error("Invalid vertex format schema")}function ae(t){return t.type==="sampler"||t.type==="sampler_comparison"}function Qe(t){return!("texture"in t)&&!ae(t)}function ue(t){return"texture"in t}var mt={uniform:"uniform",mutable:"storage",readonly:"read-only-storage"},ie=class{constructor(e,r,n){this.root=e;this.context=r;this.shaderStage=n;o(this,"samplers",[]);o(this,"textureViews",[]);o(this,"externalTextures",[]);o(this,"buffers",[]);o(this,"vertexBuffers",null);o(this,"layout",null);o(this,"bindGroup",null);o(this,"vertexLayout",null);let a=Array.from(r.usedRenderResources);for(let i of a)if(ae(i))this.samplers.push(i);else if(ue(i))this.textureViews.push(i);else if(Qe(i))this.externalTextures.push(i);else throw new Error(`Invalid resource type: ${i}`);this.buffers=Array.from(r.usedBindables)}setVertexBuffers(e){if(this.shaderStage!==GPUShaderStage.VERTEX)throw new Error("Vertex buffers can only be set for vertex shader");this.vertexBuffers=new Map(e.map(({index:r,buffer:n})=>[n,r]))}getBindGroupLayout(){if(this.layout)return this.layout;let e=[];for(let n of this.textureViews)n.access===void 0?e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,texture:{}}):e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,storageTexture:{format:n.texture.descriptor.format}});for(let n of this.externalTextures)e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,externalTexture:{}});for(let n of this.samplers)e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,sampler:{}});for(let n of this.buffers)n.usage!=="vertex"&&e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,buffer:{type:mt[n.usage]}});let r=this.root.device.createBindGroupLayout({entries:e});return this.layout=r,r}getBindGroup(){if(this.checkBindGroupInvalidation(),this.bindGroup)return this.bindGroup;let e=[];for(let n of this.textureViews)e.push({binding:this.context.getIndexFor(n),resource:this.root.viewFor(n)});for(let n of this.externalTextures)e.push({binding:this.context.getIndexFor(n),resource:this.root.externalTextureFor(n)});for(let n of this.samplers)e.push({binding:this.context.getIndexFor(n),resource:this.root.samplerFor(n)});for(let n of this.buffers)n.usage!=="vertex"&&e.push({binding:this.context.getIndexFor(n),resource:{buffer:n.allocatable.buffer}});let r=this.root.device.createBindGroup({layout:this.getBindGroupLayout(),entries:e});return this.bindGroup=r,r}getBindings(){return{bindGroupLayout:this.getBindGroupLayout(),bindGroup:this.getBindGroup()}}getVertexBufferDescriptors(){if(this.vertexBuffers===null)throw new Error("Vertex buffers not set");if(this.vertexLayout)return this.vertexLayout;let e=[];for(let[r,n]of this.vertexBuffers.entries())e.push(O(M({},r.vertexLayout),{attributes:[{shaderLocation:n,offset:0,format:xe(r.allocatable.dataType)}]}));return this.vertexLayout=e,e}getVertexBuffers(){if(this.vertexBuffers===null)throw new Error("Vertex buffers not set");return this.vertexBuffers.entries()}getVertexBufferIndex(e){var n;let r=(n=this.vertexBuffers)==null?void 0:n.get(e);if(this.vertexBuffers===null||r===void 0)throw new Error("Vertex buffers not set");return r}invalidateBindGroup(){this.bindGroup=null}checkBindGroupInvalidation(){for(let e of this.externalTextures){if(this.root.isDirty(e)){this.invalidateBindGroup(),this.root.markClean(e);continue}e.source instanceof HTMLVideoElement&&this.invalidateBindGroup()}}};var f=class{constructor(e){this.name=e;o(this,"s");this.s=Ne.get(e)}get label(){return this.name}resolve(e){return e.resolve(g`${this.s}`)}},y={vertexIndex:new f("vertex_index"),instanceIndex:new f("instance_index"),position:new f("position"),clipDistances:new f("clip_distances"),frontFacing:new f("front_facing"),fragDepth:new f("frag_depth"),sampleIndex:new f("sample_index"),sampleMask:new f("sample_mask"),fragment:new f("fragment"),localInvocationId:new f("local_invocation_id"),localInvocationIndex:new f("local_invocation_index"),globalInvocationId:new f("global_invocation_id"),workgroupId:new f("workgroup_id"),numWorkgroups:new f("num_workgroups")};var yt={[y.vertexIndex.s]:G,[y.instanceIndex.s]:G,[y.position.s]:D,[y.clipDistances.s]:He(G,8),[y.frontFacing.s]:ye,[y.fragDepth.s]:ye,[y.sampleIndex.s]:G,[y.sampleMask.s]:G,[y.fragment.s]:D,[y.localInvocationId.s]:P,[y.localInvocationIndex.s]:G,[y.globalInvocationId.s]:P,[y.workgroupId.s]:P,[y.numWorkgroups.s]:P};function X(t){let e=yt[t];if(!e)throw new Error(`The symbol ${String(t)} in not a valid 'builtin'`);return e}var S=class{constructor(){o(this,"lastUniqueId",0);o(this,"names",new WeakMap)}nameFor(e){let r=this.names.get(e);if(r===void 0){let n;e.label?(n=e.label.replaceAll(/\s/g,"_"),n=n.replaceAll(/[^\w\d]/g,"")):n="item",r=`${n}_${this.lastUniqueId++}`,this.names.set(e,r)}return r}};function x(t,e){return je(e.value)?t.resolve(e.value):String(e.value)}function xt(t){throw new Error(`'${JSON.stringify(t)}' was not handled by the WGSL generator.`)}function Ze(t,e){return e?{value:"true",dataType:me}:{value:"false",dataType:me}}function et(t,e){return`${t.indent()}{
|
2
|
+
${e.block.map(r=>ve(t,r)).join(`
|
3
|
+
`)}
|
4
|
+
${t.dedent()}}`}function he(t,e){return t.getById(e)}function b(t,e){if(typeof e=="string")return he(t,e);if(typeof e=="boolean")return Ze(t,e);if("x2"in e){let[r,n,a]=e.x2,i=x(t,b(t,r)),u=x(t,b(t,a));return{value:`${i} ${n} ${u}`,dataType:v}}if("."in e){let[r,n]=e["."],a=b(t,r),i=x(t,b(t,n));return j(a.value)||typeof a.value=="object"?i==="value"?{value:x(t,a),dataType:v}:{value:a.value[i],dataType:v}:{value:`${x(t,a)}.${i}`,dataType:v}}if("[]"in e){let[r,n]=e["[]"],a=x(t,b(t,r)),i=x(t,b(t,n));return{value:`${a}[${i}]`,dataType:v}}if("num"in e)return{value:e.num,dataType:v};if("call"in e){let n=b(t,e.call).value,i=e.args.map(u=>b(t,u)).map(u=>x(t,u));return j(n)||typeof n=="function"?{value:n(...i),dataType:v}:{value:`${String(n)}(${i.join(", ")})`,dataType:v}}xt(e)}function ve(t,e){if(typeof e=="string")return`${t.pre}${x(t,he(t,e))};`;if(typeof e=="boolean")return`${t.pre}${x(t,Ze(t,e))};`;if("return"in e)return e.return===null?`${t.pre}return;`:`${t.pre}return ${x(t,b(t,e.return))};`;if("if"in e){let r=x(t,b(t,e.if));t.indent();let n=ve(t,e.do);t.dedent(),t.indent();let a=e.else?ve(t,e.else):void 0;return t.dedent(),a?`${t.pre}if (${r})
|
5
|
+
${n}
|
6
|
+
${t.pre}else
|
7
|
+
${a}`:`${t.pre}if (${r})
|
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(`
|
9
|
+
|
10
|
+
`)}${a}`}return this._getOrInstantiate(e)}finally{n&&this._itemStateStack.pop()}}getIndexFor(e){let r=this._shared.getBindingIndex(e);if(r===void 0)throw new Error("No index found for item");return r}};var $=class{constructor(e,r){this.root=e;this.rootNode=r}build(e){var a;let r=new _({names:(a=e.nameRegistry)!=null?a:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler}),n=r.resolve(this.rootNode);return{bindGroupResolver:new ie(this.root,r,e.shaderStage),code:n}}};function vt(t){return Object.getOwnPropertySymbols(t).map(r=>{if(ze.get(r)===void 0)throw new Error("Symbol is not a member of `builtin`");return{name:t[r],builtinSymbol:r}})}var se=class{constructor(e,r,n,a){this.root=e;this.vertexRoot=r;this.fragmentRoot=n;this.vertexOutputFormat=a}build(e){var ke,Ie,Ce,Fe;let r=Object.getOwnPropertySymbols(this.vertexOutputFormat).map(p=>{let h=this.vertexOutputFormat[p];if(typeof h!="string")throw new Error("Output names must be strings.");return{symbol:p,name:h}}),n=vt(Object.fromEntries(r.map(({symbol:p,name:h})=>[p,h]))),a=Object.keys(this.vertexOutputFormat).map((p,h)=>{let E=this.vertexOutputFormat[p];if(!E)throw new Error("Output names must be strings.");return{name:p,varInfo:E,index:h}}),i=[...n.map(p=>{var E;let h=(E=this.vertexOutputFormat[p.builtinSymbol])!=null?E:"";return g`
|
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
|
+
};
|
22
|
+
|
23
|
+
@vertex
|
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};
|
2
52
|
//# sourceMappingURL=index.js.map
|