typegpu 0.2.0-alpha.0 → 0.2.1

Sign up to get free protection for your applications and to get access to all the features.
package/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { T as TgpuRenderResource, a as TgpuNamable, b as TgpuBuffer, A as AnyTgpuData, O as OmitProps, c as TgpuBufferUsage, U as Uniform, S as Storage, d as TgpuBufferUniform, e as TgpuShaderStage, f as TgpuBufferReadonly, g as TgpuBufferMutable, h as U32, I as I32, F as F32, V as Vec4u, i as Vec4i, j as Vec4f, k as TgpuPlum, E as ExtractPlumValue, l as Unsubscribe, m as TgpuCode, B as BoundTgpuCode, n as Block, v as vecBase, o as vec3f, p as vec3i, q as vec3u } from './types-qmW7FFqN.cjs';
2
- export { r as TgpuData, w as Vertex, s as isUsableAsStorage, t as isUsableAsUniform, u as isUsableAsVertex } from './types-qmW7FFqN.cjs';
1
+ import { T as TgpuRenderResource, a as TgpuNamable, b as TgpuBuffer, A as AnyTgpuData, O as OmitProps, c as TgpuBufferUsage, U as Uniform, S as Storage, d as TgpuBufferUniform, e as TgpuShaderStage, f as TgpuBufferReadonly, g as TgpuBufferMutable, h as U32, I as I32, F as F32, V as Vec4u, i as Vec4i, j as Vec4f, k as TgpuPlum, E as ExtractPlumValue, l as Unsubscribe, m as TgpuCode, B as BoundTgpuCode, n as Block, v as vecBase, o as vec3f, p as vec3i, q as vec3u } from './types-CGmVkuAt.cjs';
2
+ export { r as TgpuData, w as Vertex, s as isUsableAsStorage, t as isUsableAsUniform, u as isUsableAsVertex } from './types-CGmVkuAt.cjs';
3
3
  import { Parsed } from 'typed-binary';
4
4
 
5
5
  declare const TgpuSettableTrait: unique symbol;
@@ -244,25 +244,6 @@ type InitFromDeviceOptions = {
244
244
  device: GPUDevice;
245
245
  unstable_jitTranspiler?: JitTranspiler | undefined;
246
246
  };
247
- /**
248
- * Requests a new GPU device and creates a root around it.
249
- * If a specific device should be used instead, use @see initFromDevice.
250
- *
251
- * @example
252
- * When given no options, the function will ask the browser for a suitable GPU device.
253
- * ```ts
254
- * const root = await tgpu.init();
255
- * ```
256
- *
257
- * @example
258
- * If there are specific options that should be used when requesting a device, you can pass those in.
259
- * ```ts
260
- * const adapterOptions: GPURequestAdapterOptions = ...;
261
- * const deviceDescriptor: GPUDeviceDescriptor = ...;
262
- * const root = await tgpu.init({ adapter: adapterOptions, device: deviceDescriptor });
263
- * ```
264
- */
265
- declare function init(options?: InitOptions): Promise<ExperimentalTgpuRoot>;
266
247
  /**
267
248
  * Creates a root from the given device, instead of requesting it like @see init.
268
249
  *
@@ -324,11 +305,11 @@ declare const tgpu: {
324
305
  /** @deprecated Use `'vertex'` string literal instead. */
325
306
  Vertex: "vertex";
326
307
  bindGroupLayout: typeof bindGroupLayout;
327
- init: typeof init;
308
+ init: (options?: InitOptions) => Promise<TgpuRoot>;
328
309
  initFromDevice: typeof initFromDevice;
329
310
  createBuffer: typeof createBuffer;
330
311
  read: typeof read;
331
312
  write: typeof write;
332
313
  };
333
314
 
334
- export { AnyTgpuData, type BindLayoutEntry, type LayoutEntryToInput, RecursiveDataTypeError, Storage, type TgpuBindGroup, type TgpuBindGroupLayout, TgpuBuffer, type TgpuLayoutEntry, type TgpuLayoutSampler, type TgpuLayoutUniform, Uniform, tgpu as default, std, tgpu };
315
+ export { AnyTgpuData, type BindLayoutEntry, type LayoutEntryToInput, RecursiveDataTypeError, Storage, type TgpuBindGroup, type TgpuBindGroupLayout, TgpuBuffer, type TgpuLayoutEntry, type TgpuLayoutSampler, type TgpuLayoutUniform, type TgpuRoot, Uniform, tgpu as default, std, tgpu };
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { T as TgpuRenderResource, a as TgpuNamable, b as TgpuBuffer, A as AnyTgpuData, O as OmitProps, c as TgpuBufferUsage, U as Uniform, S as Storage, d as TgpuBufferUniform, e as TgpuShaderStage, f as TgpuBufferReadonly, g as TgpuBufferMutable, h as U32, I as I32, F as F32, V as Vec4u, i as Vec4i, j as Vec4f, k as TgpuPlum, E as ExtractPlumValue, l as Unsubscribe, m as TgpuCode, B as BoundTgpuCode, n as Block, v as vecBase, o as vec3f, p as vec3i, q as vec3u } from './types-qmW7FFqN.js';
2
- export { r as TgpuData, w as Vertex, s as isUsableAsStorage, t as isUsableAsUniform, u as isUsableAsVertex } from './types-qmW7FFqN.js';
1
+ import { T as TgpuRenderResource, a as TgpuNamable, b as TgpuBuffer, A as AnyTgpuData, O as OmitProps, c as TgpuBufferUsage, U as Uniform, S as Storage, d as TgpuBufferUniform, e as TgpuShaderStage, f as TgpuBufferReadonly, g as TgpuBufferMutable, h as U32, I as I32, F as F32, V as Vec4u, i as Vec4i, j as Vec4f, k as TgpuPlum, E as ExtractPlumValue, l as Unsubscribe, m as TgpuCode, B as BoundTgpuCode, n as Block, v as vecBase, o as vec3f, p as vec3i, q as vec3u } from './types-CGmVkuAt.js';
2
+ export { r as TgpuData, w as Vertex, s as isUsableAsStorage, t as isUsableAsUniform, u as isUsableAsVertex } from './types-CGmVkuAt.js';
3
3
  import { Parsed } from 'typed-binary';
4
4
 
5
5
  declare const TgpuSettableTrait: unique symbol;
@@ -244,25 +244,6 @@ type InitFromDeviceOptions = {
244
244
  device: GPUDevice;
245
245
  unstable_jitTranspiler?: JitTranspiler | undefined;
246
246
  };
247
- /**
248
- * Requests a new GPU device and creates a root around it.
249
- * If a specific device should be used instead, use @see initFromDevice.
250
- *
251
- * @example
252
- * When given no options, the function will ask the browser for a suitable GPU device.
253
- * ```ts
254
- * const root = await tgpu.init();
255
- * ```
256
- *
257
- * @example
258
- * If there are specific options that should be used when requesting a device, you can pass those in.
259
- * ```ts
260
- * const adapterOptions: GPURequestAdapterOptions = ...;
261
- * const deviceDescriptor: GPUDeviceDescriptor = ...;
262
- * const root = await tgpu.init({ adapter: adapterOptions, device: deviceDescriptor });
263
- * ```
264
- */
265
- declare function init(options?: InitOptions): Promise<ExperimentalTgpuRoot>;
266
247
  /**
267
248
  * Creates a root from the given device, instead of requesting it like @see init.
268
249
  *
@@ -324,11 +305,11 @@ declare const tgpu: {
324
305
  /** @deprecated Use `'vertex'` string literal instead. */
325
306
  Vertex: "vertex";
326
307
  bindGroupLayout: typeof bindGroupLayout;
327
- init: typeof init;
308
+ init: (options?: InitOptions) => Promise<TgpuRoot>;
328
309
  initFromDevice: typeof initFromDevice;
329
310
  createBuffer: typeof createBuffer;
330
311
  read: typeof read;
331
312
  write: typeof write;
332
313
  };
333
314
 
334
- export { AnyTgpuData, type BindLayoutEntry, type LayoutEntryToInput, RecursiveDataTypeError, Storage, type TgpuBindGroup, type TgpuBindGroupLayout, TgpuBuffer, type TgpuLayoutEntry, type TgpuLayoutSampler, type TgpuLayoutUniform, Uniform, tgpu as default, std, tgpu };
315
+ export { AnyTgpuData, type BindLayoutEntry, type LayoutEntryToInput, RecursiveDataTypeError, Storage, type TgpuBindGroup, type TgpuBindGroupLayout, TgpuBuffer, type TgpuLayoutEntry, type TgpuLayoutSampler, type TgpuLayoutUniform, type TgpuRoot, Uniform, tgpu as default, std, tgpu };
package/index.js CHANGED
@@ -1,4 +1,4 @@
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()}{
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 R,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]:R,[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]:R,[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
2
  ${e.block.map(r=>ve(t,r)).join(`
3
3
  `)}
4
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})
@@ -48,5 +48,5 @@ ${n}`}if("let"in e||"const"in e){let r=x(t,he(t,"let"in e?e.let:e.const)),n=e.eq
48
48
  fn main(${a}) {
49
49
  ${this.computeRoot}
50
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};
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 Re(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 Re=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 De(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(De(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(De(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),D={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)=>R(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)=>R(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)=>R(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 R(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})`:D.add[t.kind](t,e)},sub(t,e){return B()?`(${t} - ${e})`:D.sub[t.kind](t,e)},mul:(t,e)=>B()?`(${t} * ${e})`:D.mul[e.kind](t,e),dot(t,e){return B()?`dot(${t}, ${e})`:D.dot[t.kind](t,e)},normalize:t=>B()?`normalize(${t})`:D.normalize[t.kind](t),cross(t,e){return B()?`cross(${t}, ${e})`:D.cross[t.kind](t,e)},fract(t){return B()?`fract(${t})`:t-Math.floor(t)},length(t){return B()?`length(${t})`:D.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};
52
52
  //# sourceMappingURL=index.js.map