@margoengine/core 0.1.0 → 1.0.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/dist/camera.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./hypot-Bouwbr1T.js";import{n as t}from"./errors-B6KSysyy.js";import{finite as n}from"./geometry.js";var r=/* @__PURE__ */ new Float64Array(1),i=/* @__PURE__ */ new Float32Array(16),a=/* @__PURE__ */ new Float32Array(24),o=class{fov;near;far;position;target;up=[0,1,0];project;matrix=/* @__PURE__ */ new Float32Array(16);planes=/* @__PURE__ */ new Float32Array(24);e;g=/* @__PURE__ */ new Float64Array(16);f=/* @__PURE__ */ new Float64Array(16);constructor({fov:e=60,position:t=[0,2,5],target:n=[0,0,0],near:r=.1,far:i=1e3}={}){this.fov=e,this.position=t,this.target=n,this.near=r,this.far=i}update(o,s){if(n(this.position,3,`Camera position`),n(this.target,3,`Camera target`),!Number.isFinite(o)||!Number.isFinite(this.fov)||!Number.isFinite(this.near)||!Number.isFinite(this.far)||o<=0||this.fov<=0||this.fov>=180||this.near<=0||this.far<=this.near)throw t(`Invalid projection`,`camera`);let c=this.position[0]-this.target[0],l=this.position[1]-this.target[1],u=this.position[2]-this.target[2],d=e(3,c,l,u);if(!d)throw t(`Camera at target`,`camera`);c/=d,l/=d,u/=d;let f=this.up,p=f[1]*u-f[2]*l,m=f[2]*c-f[0]*u,h=f[0]*l-f[1]*c,g=e(3,p,m,h);if(!g)throw t(`Vertical camera`,`camera`);p/=g,m/=g,h/=g;let _=l*h-u*m,v=u*p-c*h,y=c*m-l*p,b=this.position,x=this.g;x[0]=p,x[1]=_,x[2]=c,x[4]=m,x[5]=v,x[6]=l,x[8]=h,x[9]=y,x[10]=u,x[12]=-p*b[0]-m*b[1]-h*b[2],x[13]=-_*b[0]-v*b[1]-y*b[2],x[14]=-c*b[0]-l*b[1]-u*b[2],x[15]=1;let S=1/Math.tan(this.fov*Math.PI/360),C=this.near-this.far,w=this.f;w.fill(0),this.project?this.project(w,o,s):(w[0]=S/o,w[5]=S,w[10]=s?-this.near/C:(this.far+this.near)/C,w[11]=-1,w[14]=s?-this.far*this.near/C:2*this.far*this.near/C);let T=i;for(let e=0;e<4;e++)for(let t=0;t<4;t++)T[e*4+t]=w[t]*x[e*4]+w[4+t]*x[e*4+1]+w[8+t]*x[e*4+2]+w[12+t]*x[e*4+3];n(T,16,`Camera matrix`);for(let e=0;e<6;e++){let n=e>>1,i=e%2==0?1:-1,o=0;for(let t=0;t<4;t++){let r=e===4&&s?T[t*4+2]:T[t*4+3]+i*T[t*4+n];a[e*4+t]=r,t<3&&(o+=r*r)}r[0]=o;let c=Math.sqrt(r[0]);if(!c)throw t(`Invalid frustum`,`camera`);for(let t=0;t<4;t++)a[e*4+t]/=c}this.matrix.set(T),this.planes.set(a)}fitToBoundingBox(e,r,{aspect:i=1,duration:a=.3,padding:o=1.1}={}){if(n(e,3,`Bounds`),n(r,3,`Bounds`),e.some((e,t)=>e>r[t])||![i,a,o,this.fov,this.near,this.far].every(Number.isFinite)||i<=0||a<0||o<1||this.fov<=0||this.fov>=180||this.near<=0||this.far<=this.near)throw t(`Invalid fit`,`camera`);let s=e.map((e,t)=>(e+r[t])/2),c=Math.hypot(...r.map((t,n)=>(t-e[n])/2)),l=Math.atan(Math.tan(this.fov*Math.PI/360)*Math.min(1,i)),u=Math.max(c/Math.sin(l),c+this.near)*o,d=this.position.map((e,t)=>e-this.target[t]),f=Math.hypot(...d);if(!f||u+c>=this.far)throw t(`Bounds exceed far: raise camera.far`,`camera`);let p=s.map((e,t)=>e+d[t]/f*u);this.e={position:p,target:s,elapsed:0,duration:a,from:this.position,fromTarget:this.target},this.advance(0)}advance(e){if(!this.e)return;let t=this.e,n=t.duration?Math.min(1,(t.elapsed+=e)/t.duration):1,r=n*n*(3-2*n);this.position=t.from.map((e,n)=>e+(t.position[n]-e)*r),this.target=t.fromTarget.map((e,n)=>e+(t.target[n]-e)*r),n===1&&(this.e=void 0)}cancelFit(){this.e=void 0}};export{o as Camera};
1
+ import{t as e}from"./hypot-B7a6-Lk8.js";import{r as t}from"./errors-D0VAEAiW.js";import{finite as n}from"./geometry.js";var r=/* @__PURE__ */ new Float64Array(1),i=/* @__PURE__ */ new Float32Array(16),a=/* @__PURE__ */ new Float32Array(24),o=class{fov;near;far;position;target;up=[0,1,0];project;matrix=/* @__PURE__ */ new Float32Array(16);planes=/* @__PURE__ */ new Float32Array(24);e;g=/* @__PURE__ */ new Float64Array(16);f=/* @__PURE__ */ new Float64Array(16);constructor({fov:e=60,position:t=[0,2,5],target:n=[0,0,0],near:r=.1,far:i=1e3}={}){this.fov=e,this.position=t,this.target=n,this.near=r,this.far=i}update(o,s){if(n(this.position,3,`Camera position`),n(this.target,3,`Camera target`),!Number.isFinite(o)||!Number.isFinite(this.fov)||!Number.isFinite(this.near)||!Number.isFinite(this.far)||o<=0||this.fov<=0||this.fov>=180||this.near<=0||this.far<=this.near)throw t(`Invalid projection`,`camera`);let c=this.position[0]-this.target[0],l=this.position[1]-this.target[1],u=this.position[2]-this.target[2],d=e(3,c,l,u);if(!d)throw t(`Camera at target`,`camera`);c/=d,l/=d,u/=d;let f=this.up,p=f[1]*u-f[2]*l,m=f[2]*c-f[0]*u,h=f[0]*l-f[1]*c,g=e(3,p,m,h);if(!g)throw t(`Vertical camera`,`camera`);p/=g,m/=g,h/=g;let _=l*h-u*m,v=u*p-c*h,y=c*m-l*p,b=this.position,x=this.g;x[0]=p,x[1]=_,x[2]=c,x[4]=m,x[5]=v,x[6]=l,x[8]=h,x[9]=y,x[10]=u,x[12]=-p*b[0]-m*b[1]-h*b[2],x[13]=-_*b[0]-v*b[1]-y*b[2],x[14]=-c*b[0]-l*b[1]-u*b[2],x[15]=1;let S=1/Math.tan(this.fov*Math.PI/360),C=this.near-this.far,w=this.f;w.fill(0),this.project?this.project(w,o,s):(w[0]=S/o,w[5]=S,w[10]=s?-this.near/C:(this.far+this.near)/C,w[11]=-1,w[14]=s?-this.far*this.near/C:2*this.far*this.near/C);let T=i;for(let e=0;e<4;e++)for(let t=0;t<4;t++)T[e*4+t]=w[t]*x[e*4]+w[4+t]*x[e*4+1]+w[8+t]*x[e*4+2]+w[12+t]*x[e*4+3];n(T,16,`Camera matrix`);for(let e=0;e<6;e++){let n=e>>1,i=e%2==0?1:-1,o=0;for(let t=0;t<4;t++){let r=e===4&&s?T[t*4+2]:T[t*4+3]+i*T[t*4+n];a[e*4+t]=r,t<3&&(o+=r*r)}r[0]=o;let c=Math.sqrt(r[0]);if(!c)throw t(`Invalid frustum`,`camera`);for(let t=0;t<4;t++)a[e*4+t]/=c}this.matrix.set(T),this.planes.set(a)}fitToBoundingBox(e,r,{aspect:i=1,duration:a=.3,padding:o=1.1}={}){if(n(e,3,`Bounds`),n(r,3,`Bounds`),e.some((e,t)=>e>r[t])||![i,a,o,this.fov,this.near,this.far].every(Number.isFinite)||i<=0||a<0||o<1||this.fov<=0||this.fov>=180||this.near<=0||this.far<=this.near)throw t(`Invalid fit`,`camera`);let s=e.map((e,t)=>(e+r[t])/2),c=Math.hypot(...r.map((t,n)=>(t-e[n])/2)),l=Math.atan(Math.tan(this.fov*Math.PI/360)*Math.min(1,i)),u=Math.max(c/Math.sin(l),c+this.near)*o,d=this.position.map((e,t)=>e-this.target[t]),f=Math.hypot(...d);if(!f||u+c>=this.far)throw t(`Bounds exceed far: raise camera.far`,`camera`);let p=s.map((e,t)=>e+d[t]/f*u);this.e={position:p,target:s,elapsed:0,duration:a,from:this.position,fromTarget:this.target},this.advance(0)}advance(e){if(!this.e)return;let t=this.e,n=t.duration?Math.min(1,(t.elapsed+=e)/t.duration):1,r=n*n*(3-2*n);this.position=t.from.map((e,n)=>e+(t.position[n]-e)*r),this.target=t.fromTarget.map((e,n)=>e+(t.target[n]-e)*r),n===1&&(this.e=void 0)}cancelFit(){this.e=void 0}};export{o as Camera};
@@ -0,0 +1,4 @@
1
+ var e=[.018,.023,.035,1],t=e=>/^#([\da-f]{3}){1,2}$/i.test(e)?parseInt((e[4]?e:e.replace(/\w/g,`$&$&`)).slice(1),16):-1,n=e=>(e/=255)>.04045?((e+.055)/1.055)**2.4:e/12.92,r=e=>e/255,i=/float$|srgb$/,a=/* @__PURE__ */ e.map(e=>n(e*255));function o(o,s){let c=i.test(s)?n:r;if(o==null||o===!1)return c===r?e:a;let l=t(o);if(l<0)throw RangeError(`Invalid color; use #rrggbb`);return[c(l>>16),c(l>>8&255),c(l&255),1]}var s=/* @__PURE__ */ new WeakMap;function c(e,t){let n=s.get(e);if(!n){let t=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{}}]});n={group:t,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),groups:/* @__PURE__ */ new Map},s.set(e,n)}let r=t.join(),i=n.groups.get(r);if(!i){let a=e.createBuffer({size:16,usage:72});if(e.queue.writeBuffer(a,0,new Float32Array(t)),i=e.createBindGroup({layout:n.group,entries:[{binding:0,resource:{buffer:a}}]}),i.b=a,n.groups.size>63){let[t,r]=n.groups.entries().next().value;n.groups.delete(t),e.queue.onSubmittedWorkDone().then(()=>r.b.destroy())}n.groups.set(r,i)}return[n.layout,i]}function l(t,n,r,{formats:i,values:a=[],depthFormat:o,writeDepth:s,samples:l=1,writeColor:u=!0,tint:d=e}){let f=[i,a,o,+!!s,l,+u].join(`|`),[p,m]=c(t,d),h=n.get(f);if(!h){let e=i.map((e,t)=>`@location(${t}) c${t}:vec4f`).join(`,`),r=t.createShaderModule({code:`@group(0) @binding(0) var<uniform> t:vec4f;
2
+ struct Out{${e}}
3
+ @vertex fn v(@builtin(vertex_index) i:u32)->@builtin(position) vec4f{return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);}
4
+ @fragment fn f()->Out{return Out(t${a.map(e=>`,vec4f(${e})`).join(``)});}`});h=t.createRenderPipeline({layout:p,vertex:{module:r,entryPoint:`v`},fragment:{module:r,entryPoint:`f`,targets:i.map((e,t)=>t?{format:e}:{format:e,writeMask:u?15:0})},...o?{depthStencil:{format:o,depthWriteEnabled:!!s,depthCompare:`always`}}:{},multisample:{count:l}}),n.set(f,h)}r.setPipeline(h),r.setBindGroup(0,m),r.draw(3)}export{n as a,t as i,l as n,e as r,o as t};
package/dist/engine.d.ts CHANGED
@@ -130,7 +130,7 @@ export declare class Scene {
130
130
  readonly name: string;
131
131
  /** `dispose()`, for `using` (set at the end of this file where the runtime has `Symbol.dispose`). */
132
132
  [Symbol.dispose]: () => void;
133
- /** Clear colour (`#rgb` or `#rrggbb`, sRGB) for views of this scene, or null to keep the colour below (overlays). A view's `clear` wins. Shown as given on the canvas; under a post effect it is linear light, tone-mapped with the scene. Default: core's clear colour. */
133
+ /** Clear colour (`#rgb` or `#rrggbb`, sRGB) for views of this scene, or null to keep the colour below (overlays); any other value makes the next render throw a RangeError. A view's `clear` wins. Shown as given on the canvas; under a post effect it is linear light, tone-mapped with the scene. Default: core's clear colour, drawn 5,6,9 on the canvas and treated the same way under an effect. */
134
134
  background?: string | null;
135
135
  readonly frameGraph: FrameGraph;
136
136
  readonly plugins: ReadonlyMap<string, EnginePlugin>;
@@ -288,6 +288,8 @@ export declare class Engine {
288
288
  delta?: number;
289
289
  views?: readonly RenderView[];
290
290
  }): void;
291
+ /** render() ended: a dispose() asked for during its draw runs now. */
292
+ private endDraw;
291
293
  private renderViews;
292
294
  /** A view rectangle in pixels of `size`: fractions of it, or pixels when `pixels` is set. `trusted` skips the bounds check. */
293
295
  private viewPixels;
@@ -318,5 +320,6 @@ export declare class Engine {
318
320
  private readonly call;
319
321
  private readonly frame;
320
322
  stop(): void;
323
+ /** Frees the engine. Asked for while a frame draws (from a pass), it takes effect when that draw ends. */
321
324
  dispose(): void;
322
325
  }
package/dist/engine.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./hypot-Bouwbr1T.js";import{i as t,n,r,t as i}from"./errors-B6KSysyy.js";import{a,n as o,r as s,t as c}from"./view-rect-DBHPjboz.js";import{F32_OVERFLOW as l,Geometry as u,PbrMaterial as d,finite as f}from"./geometry.js";import{TransformStore as p,syncStoredRotation as m}from"./kernel.js";import{Camera as h}from"./camera.js";import{GPURenderer as g}from"./renderer.js";import{FrameGraph as _}from"./plugin.js";import{assertCore as v,coreRequirement as y}from"./version.js";import{sceneSamples as b}from"./quality.js";var x=`Engine disposed`,S=`WebGPU required`,C=[`x`,`y`,`z`],w=[`sx`,`sy`,`sz`],T=/* @__PURE__ */ new WeakMap,E=(e,t)=>{try{t()}catch(t){e.push(t)}},D=class{e;f;constructor(e,t){this.e=e,this.f=t}h(e){return this.e.check(),this.f===`rotation`?this.e.engine.store.rotations[this.e.id*3+e]:this.e.engine.store.transforms[(this.f===`scale`?w:C)[e]][this.e.id]}g(e){if(typeof e!=`number`||!(e<l&&e>-l))throw n(`Invalid transform`,`transform`)}i(e,t){this.e.check(),this.g(t),this.f===`rotation`?(this.e.engine.store.rotations[this.e.id*3+e]=t,this.e.syncRotation()):this.e.engine.store.transforms[(this.f===`scale`?w:C)[e]][this.e.id]=t}set(e,t,n){this.e.check(),this.g(e),this.g(t),this.g(n);let r=this.f===`scale`?w:C,i=this.e.engine.store.transforms,a=this.e.id;for(let o=0;o<3;o++){let s=o===0?e:o===1?t:n;this.f===`rotation`?this.e.engine.store.rotations[a*3+o]=s:i[r[o]][a]=s}return this.f===`rotation`&&this.e.syncRotation(),this}setAll(e){return this.set(e,e,e)}get x(){return this.h(0)}set x(e){this.i(0,e)}get y(){return this.h(1)}set y(e){this.i(1,e)}get z(){return this.h(2)}set z(e){this.i(2,e)}},O=(t,r,i,a)=>{let o=e(4,i[a],i[a+1],i[a+2],i[a+3]);if(!o)throw n(`Quaternion nonzero`,`transform`);let s=i[a]/o,c=i[a+1]/o,l=i[a+2]/o,u=i[a+3]/o,d=t.transforms,f=t.rotations,p=r*3;d.qx[r]=s,d.qy[r]=c,d.qz[r]=l,d.qw[r]=u;let m=2*(s*l+u*c),h=2*(u*l-s*c),g=1-2*(c*c+l*l);f[p+1]=Math.asin(m>1?1:m<-1?-1:m),h*h+g*g<36e-13?(f[p]=0,f[p+2]=2*Math.atan2(l,u)):(f[p]=Math.atan2(2*(u*s-c*l),1-2*(s*s+c*c)),f[p+2]=Math.atan2(h,g))},k=(e,t)=>+(e[t+22]>.5||e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])<0),A=(e,t)=>{let n=t/24,r=1<<(n&31),i=e.rows;e.dirty>=0&&!(i[n>>5]&r)&&(i[n>>5]|=r,e.dirty++)},j=e=>Object.assign(e,{matrix:e.engine.store.matrices.subarray(e.id*16,e.id*16+16)}),M=class{engine;id;scene;name=``;geometry=null;e=new d;get material(){return this.e}set material(e){if(!(e instanceof d))throw r(`Invalid material`,`arguments`);this.e=e,this.engine.collected=-1}f=!0;get receiveShadow(){return this.f}set receiveShadow(e){if(typeof e!=`boolean`)throw r(`receiveShadow: boolean`,`arguments`);this.f=e,this.engine.collected=-1}constructor(e,n,r=e.scene){this.engine=e,this.id=n,this.scene=r;for(let e of[`position`,`rotation`,`scale`]){let n=new D(this,e);Object.defineProperty(this,e,{get:()=>n,set:t,enumerable:!0})}j(this)}get visible(){return this.check(),this.engine.store.hidden[this.id]===0}set visible(e){if(this.check(),typeof e!=`boolean`)throw r(`Visibility: boolean`,`arguments`);this.engine.store.hidden[this.id]=+!e}check(){if(this.engine.disposed||this.engine.meshes.get(this.id)!==this)throw i(`disposed`,`Mesh disposed`)}setPosition(e){return this.check(),f(e,3,`Position`),this.position.set(e[0],e[1],e[2]),this}setScale(e){return this.check(),f(e,3,`Scale`),this.scale.set(e[0],e[1],e[2]),this}setRotation(e){return this.check(),f(e,3,`Rotation`),this.rotation.set(e[0],e[1],e[2]),this}syncRotation(){m(this.engine.store,this.id)}setQuaternion(e){return this.check(),f(e,4,`Quaternion`),O(this.engine.store,this.id,e,0),this}setParent(e){if(this.check(),e?.check(),e&&(e.engine!==this.engine||e.scene!==this.scene))throw r(`Foreign parent`,`hierarchy`);let t=0;for(let i=e?.id??-1;i!==-1;i=this.engine.store.parents[i]){if(i===this.id)throw r(`Hierarchy cycle`,`hierarchy`);if(++t>=64)throw n(`Parent depth: 64`,`hierarchy`)}let i=e=>{let t=0;for(let n of e?.kids??[])t=Math.max(t,1+i(this.engine.meshes.get(n)));return t};if(e&&t+i(this)>=64)throw n(`Parent depth: 64`,`hierarchy`);let a=this.engine.store.parents;return this.engine.meshes.get(a[this.id])?.kids?.delete(this.id),e&&(e.kids??=/* @__PURE__ */ new Set).add(this.id),a[this.id]=e?.id??-1,this}setGeometry(e){if(this.check(),e!==null&&!(e instanceof u))throw r(`Invalid geometry`,`arguments`);if(e===this.geometry)return this;e&&this.engine.retain(e);let t=this.geometry;this.geometry=e;let n=this.engine.store.bounds;return n.fill(0,this.id*4,this.id*4+4),e&&n.set(e.bounds,this.id*4),t&&this.engine.release(t),this.engine.collected=-1,this}setMaterial(e){return this.check(),this.material=e,this}dispose(){this.engine.meshes.get(this.id)===this&&this.engine.remove(this)}},N=class{engine;name;background;frameGraph=new _;plugins=/* @__PURE__ */ new Map;meshes=/* @__PURE__ */ new Map;stats={visible:0,drawCalls:0};lighting={direction:new Float32Array([3,5,4,3]),radiance:new Float32Array([1,1,1,.15]),ambient:new Float32Array([1,1,1])};constructor(e,t){this.engine=e,this.name=t}createMesh(e=null){return this.engine.createMesh(e,this)}use(e){return this.engine.use(e,this),this}removePlugin(e){this.engine.removePlugin(e,this)}dispose(){let e=this.engine,t=[];if(this===e.scene)throw r(`Default scene: dispose the engine instead`,`scene`);if(e.scenes.delete(this)){for(let n of this.plugins.keys())E(t,()=>e.removePlugin(n,this));for(let t of this.meshes.values())e.remove(t);if(t.length)throw t[0]}}},P=class e{canvas;store;renderer;fallbackReason;coreRequirement=y();scene;scenes=/* @__PURE__ */ new Set;meshes=/* @__PURE__ */ new Map;camera;disposed=!1;onError=e=>{typeof reportError==`function`?reportError(e):console.error(e)};pace;maxDelta=.1;views;i=/* @__PURE__ */ new Map;k=[];I=/* @__PURE__ */ new WeakMap;C=0;Q=[];D=0;r=0;collected=-1;unshadowed=0;L;K=-1;w=[];F;l;t=/* @__PURE__ */ new Set;p=null;o=0;s=!1;n=!1;T=!0;q={delta:null};j=!1;g;A=new AbortController;y=0;B=0;f;e=-1;v;x;J=/* @__PURE__ */ new WeakMap;features;exact;fixed;power;get frameGraph(){return this.f.frameGraph}get lighting(){return this.f.lighting}get stats(){return this.f.stats}get plugins(){return this.f.plugins}static async create(t,a={}){if(!t||typeof t.getContext!=`function`)throw r(`Expected canvas`,`arguments`);let o=a.backend??`auto`;if(![`auto`,`webgpu`,`webgl2`].includes(o))throw r(`Unknown backend`,`arguments`);let s=a.exactSize,c=a.antialias??!s?void 0:1;if(Array.isArray(s)){if(s.length!==2||!s.every(e=>Number.isInteger(e)&&e>0&&e<=8192))throw n(`Invalid exactSize`,`pixel-exact`);[t.width,t.height]=s}let l=await p.create(a.capacity??1024),u,d=null;try{if(a.signal?.throwIfAborted(),o!==`webgl2`)try{u=await g.create(t,a.features,c,a)}catch(e){if(o===`webgpu`||a.signal?.aborted)throw e;d=String(e)}u??=(a.fallback??(()=>{throw i(`unsupported`,o===`webgl2`?`webgl2 needs fallback: webglRenderer`:`WebGPU unavailable`,`webgpu`)}))(t);let n=new e(t,l,u,a.camera,d);return n.features=a.features,n.exact=c,n.fixed=s?1:void 0,n.power=a.powerPreference,n}catch(e){throw u?.dispose(),l.dispose(),e}}constructor(e,t,n,r,i){this.canvas=e,this.store=t,this.renderer=n,this.fallbackReason=i,this.camera=new h(r),this.scenes.add(this.scene=this.f=new N(this,`default`)),this.F=new Uint8Array(t.capacity),this.l=new Int32Array(t.capacity),this.V()}V(){let e=this.renderer,t=(n,r)=>{if(this.disposed||this.j||this.renderer!==e)return;let a=()=>t(n,r);if(this.g)return void this.g.then(a,a);r&&this.onError(n),this.B=0,++this.y<4?this.rebootDevice().catch(e=>this.disposed||this.onError(e)):this.y===4&&this.onError(i(`failed`,`GPU lost 4 times; reload the page`,`gpu-lost`))};e.onLost=t}rebootDevice(){return this.disposed||this.j?Promise.reject(i(`disposed`,x)):this.backend===`webgpu`?(this.g||=(async()=>{let e=this.renderer,t=await g.create(this.canvas,this.features,this.exact,{powerPreference:this.power,signal:this.A.signal},!1);try{this.A.signal.throwIfAborted();for(let e of this.i.values())t.add(e.geometry,e.instances.length/24);t.configure()}catch(e){throw t.dispose(!1),e}this.renderer=t,this.V(),e.dispose(!1);let n=[];for(let e of this.scenes){let t=this.h(e);for(let t of e.plugins.values())E(n,()=>t.onDeviceRestored?.(this));this.h(t)}if(n.length)throw n[0]})().finally(()=>{this.g=void 0}),this.g):Promise.reject(i(`unsupported`,S,`webgpu`))}O(){return this.y&&++this.B>=120&&(this.y=this.B=0),!0}get backend(){return this.renderer.backend}get renderTarget(){return this.renderer.target??null}get gpu(){return this.renderer.gpu??null}geometryBuffers(e){if(this.disposed||this.j||this.g)throw i(`state`,`Geometry unavailable`,`device-restore`);return e.indices.length?this.renderer.geometryBuffers?.(e)??null:null}hasPlugin(e){return this.plugins.has(e)}h(e){let t=this.f;if(t!==e){for(let n of this.i.values()){let r=this.J.get(n);r||this.J.set(n,r=/* @__PURE__ */ new WeakMap),r.set(t,[n.claimed,n.redirect]),[n.claimed,n.redirect]=r.get(e)??[]}this.f=e}return t}m(){if(this.disposed||this.j)throw i(`disposed`,x)}u(e){if(!this.scenes.has(e))throw r(`Unknown scene: use engine.createScene()`,`scene`)}use(e,t=this.f){this.m(),e.coreRequirement&&v(this,e.coreRequirement),this.u(t);let n=e.name,i=t.plugins;if(!n||i.has(n)||T.has(e)||typeof e.setup!=`function`)throw r(`Invalid plugin`,`arguments`);let a=this.h(t);try{t.frameGraph.withOwner(n,()=>{i.set(n,e);for(let[e,t]of[...i])t.late&&(i.delete(e),i.set(e,t));T.set(e,t);try{e.setup(this),e.registerPasses?.(t.frameGraph)}catch(r){t.frameGraph.removeOwner(n),i.delete(n),T.delete(e);try{e.dispose?.()}catch{}throw r}})}finally{this.h(a)}return this}removePlugin(e,t=this.f){let n=t.plugins.get(e);if(!n)return;t.frameGraph.removeOwner(e),t.plugins.delete(e),T.delete(n);let r=this.h(t);try{n.dispose?.()}finally{this.h(r)}}createScene(e=`scene`){this.m();let t=new N(this,e);return this.scenes.add(t),t}sceneOf(e){let t=T.get(e);return t?.engine===this?t:void 0}createMesh(e=null,t=this.f){if(this.m(),this.u(t),e?.check(),e&&(e.engine!==this||e.scene!==t))throw r(`Foreign parent`,`hierarchy`);let n=this.Q.pop()??this.D++;if(n>=this.store.capacity)try{let e=Math.min(n*2,1<<23),t=new Uint8Array(e),r=new Int32Array(e);this.store.grow(e),this.F=t,this.l=r,this.meshes.forEach(j)}catch(e){throw this.D=n,e}let i=this.store.transforms;for(let e of[`x`,`y`,`z`,`qx`,`qy`,`qz`])i[e][n]=0;for(let e of[`qw`,`sx`,`sy`,`sz`])i[e][n]=1;this.store.parents[n]=-1,this.store.constrained[n]=0,this.store.hidden[n]=0,this.store.rotations.fill(0,n*3,n*3+3);let a=new M(this,n,t);this.meshes.set(n,a),t.meshes.set(n,a),a.born=this.r++,this.store.active[n]=1;try{return a.setParent(e)}catch(e){throw a.dispose(),e}}remove(e){let t=this.store.parents;if(e.check(),!this.j){for(let n of e.kids??[])t[n]=-1;e.setParent(null)}e.geometry&&this.release(e.geometry),this.meshes.delete(e.id),e.scene.meshes.delete(e.id),this.r++,this.store.active[e.id]=0,this.store.visible[e.id]=0,this.Q.push(e.id)}writePoses(e,t,r=e.length){this.m();let{transforms:a,active:o}=this.store;if(!(r>=0&&r<=e.length&&t.length>=r*7))throw n(`Invalid poses`,`transform`);for(let a=0,s=0;a<r;a++,s+=7){if(o[e[a]]!==1)throw i(`disposed`,`Mesh disposed`);for(let e=s;e<s+7;e++){let r=t[e];if(typeof r!=`number`||!(r<l&&r>-l))throw n(`Invalid transform: ${a}`,`transform`)}if(!(t[s+3]||t[s+4]||t[s+5]||t[s+6]))throw n(`Quaternion nonzero: ${a}`,`transform`)}for(let n=0,i=0;n<r;n++,i+=7){let r=e[n];a.x[r]=t[i],a.y[r]=t[i+1],a.z[r]=t[i+2],O(this.store,r,t,i+3)}}retain(e){if(!e.indices.length)return;let t=this.i.get(e)??{geometry:e,instances:/* @__PURE__ */ new Float32Array,rows:/* @__PURE__ */ new Uint32Array,count:0,references:0};if(t.references>=t.instances.length/24){let n=(t.references+1)*2,r=new Float32Array(n*24),i=new Uint32Array(n+31>>5);this.renderer.add(e,n),t.instances=r,t.rows=i,this.collected=-1}t.references++||(this.i.set(e,t),this.k.push(t))}release(e){if(!e.indices.length)return;let t=this.i.get(e);--t.references===0&&(this.renderer.remove(e),this.i.delete(e),this.k.splice(this.k.indexOf(t),1))}X=e=>{(this.e===-1||s(e)&this.e)&&(this.unshadowed+=+!e.receiveShadow,e.geometry?.indices.length&&this.store.visible[e.id]&&this.S(e))};S(e){if(this.I.get(e.material)!==this.C){let t=e.material.data;f(t,8,`Material`);for(let e=0;e<8;e++)if(t[e]<0||t[e]>1)throw n(`Invalid material`,`material`);if(t[3]!==1||t[4]<Math.fround(.045)||t[6]!==0&&t[6]!==1)throw n(`Invalid material`,`material`);this.I.set(e.material,this.C),this.w.push([e.material,...t])}let t=this.i.get(e.geometry),r=t.count++*24;this.l[e.id]=r,t.instances.set(e.matrix,r),t.instances.set(e.material.data,r+16),e.receiveShadow||(t.instances[r+22]+=.25),t.instances[r+23]=e.id,t.mask+=k(t.instances,r),A(t,r)}render({camera:e=this.camera,culling:t=!0,delta:n=0,views:a}={}){if(this.n)throw i(`state`,`Render recursion`,`reentrancy`);if(a)return this.Z(a,t,n);if(!(e instanceof h))throw r(`Invalid camera`,`arguments`);this.n=!0,this.v=void 0;let o=!1;try{this.G(t,n,e);let r=this.f.background,{width:i,height:a}=this.canvas;!this.g&&!this.disposed&&this.O()&&this.renderer.render(e,this.lighting,this.k,this.frameGraph,n,r===void 0&&this.e===-1?void 0:{rect:[0,0,i,a],index:0,count:1,id:`0`,clear:r===void 0?void 0:{color:r??!1},layers:this.e===-1?void 0:this.e})}catch(e){throw o=!0,e}finally{try{e!==this.camera&&!this.disposed&&!this.j&&(this.camera.update(this.canvas.width/this.canvas.height,this.backend===`webgpu`),this.store.planes.set(this.camera.planes),this.store.tick(this.T),this.e=this.H(this.camera),this.M())}catch(e){if(!o)throw e}finally{this.n=!1}}}Z(e,t,n){if(!Array.isArray(e)||!e.length)throw r(`Invalid views`,`views`);this.n=!0;let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[],s=e=>e?.target?.color??this.canvas,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map;for(let t of e)c.set(s(t),(c.get(s(t))??0)+1);let u=[...c.keys()],d=e.map((e,t)=>t).sort((t,n)=>u.indexOf(s(e[t]))-u.indexOf(s(e[n])));try{this.E();for(let u of d){let d=e[u];if(!(d?.camera instanceof h)||!d.viewport)throw r(`Invalid view: pass {camera, viewport}`,`views`);let f={...d,viewport:[...d.viewport],scissor:d.scissor&&[...d.scissor]},p=f.scene??this.scene,m=f.target?.color,g=m?[m.width,m.height]:[this.canvas.width,this.canvas.height],_=this.z(f.viewport,f.pixels,g),v=!a.has(p);if(this.u(p),this.h(p),this.G(t,i.has(f.camera)?0:n,f.camera,_,v,n,f.layers),this.disposed)break;i.add(f.camera),a.add(p),!this.g&&(u||this.O())&&this.renderer.render(f.camera,this.lighting,this.k,this.frameGraph,v?n:0,{rect:_,scissor:f.scissor&&this.z(f.scissor,f.pixels,g),layers:this.e===-1?void 0:this.e,index:l.get(s(f))??0,count:c.get(s(f)),id:f.id??String(u),clear:f.clear??(p.background===void 0?void 0:{color:p.background??!1}),target:f.target}),l.set(s(f),(l.get(s(f))??0)+1),m||o.push(f)}}finally{this.n=!1,this.v=o,this.h(this.scene)}}z(e,t,[n,r],i){let o=t?[...e]:[Math.round(e[0]*n),Math.round(e[1]*r),Math.round((e[0]+e[2])*n)-Math.round(e[0]*n),Math.round((e[1]+e[3])*r)-Math.round(e[1]*r)];return i||a(o,n,r),o}G(e,t,r=this.camera,i,a=!0,o=t,s){if(this.m(),!Number.isFinite(o)||o<0||o>1)throw n(`Invalid delta`,`arguments`);if(this.N=o,a&&this.plugins.forEach(this.Y),this.disposed)return;i||this.E(),r.advance(t),r.update(i?i[2]/i[3]:this.canvas.width/this.canvas.height,this.backend===`webgpu`),this.e=this.H(r,s),this.store.planes.set(r.planes),this.store.tick(e);let{direction:c,radiance:l,ambient:u}=this.lighting;f(c,4,`Light`),f(l,4,`Radiance`),f(u,3,`Ambient`);let d=!(c[0]||c[1]||c[2])||c[3]<0;for(let e=0;e<4;e++)d||=l[e]<0||e<3&&u[e]<0;if(d)throw n(`Invalid lighting`,`lighting`);if(this.M(),this.n){let{stats:e}=this,t=this.k;e.visible=e.drawCalls=0;for(let n=0;n<t.length;n++)e.visible+=t[n].count,(t[n].count||t[n].redirect)&&!t[n].claimed&&e.drawCalls++}r===this.camera&&(this.T=e)}H(e,t){return(t===void 0?o()?.cameras.get(e)??-1:c(t,`View layers`))|0}E(){if(this.fixed)return;let e=Math.min(globalThis.devicePixelRatio??1,globalThis.margoLow||2,4/b(this)),t=Math.round(this.canvas.clientWidth*e)||this.canvas.width,n=Math.round(this.canvas.clientHeight*e)||this.canvas.height,r=Math.min(1,(this.gpu?.limits.maxTextureDimension2D??4096)/Math.max(t,n)),i=Math.max(1,Math.round(t*r)),a=Math.max(1,Math.round(n*r));this.canvas.width!==i&&(this.canvas.width=i),this.canvas.height!==a&&(this.canvas.height=a)}M(){let{visible:e,changed:t}=this.store,n=this.F,r=this.f,i=this.e,a=this.collected!==this.r||this.L!==r||this.K!==i||i!==-1&&!!o()?.source;for(let e=0;!a&&e<this.w.length;e++)for(let t=0,n=this.w[e];!a&&t<8;t++)a=n[0].data[t]!==n[t+1];if(a){this.collected=-1;for(let e of this.k)e.count=e.mask=0,e.dirty=-1;this.unshadowed=0,this.C++,this.w.length=0,this.l.fill(-1),r.meshes.forEach(this.X),this.collected=this.r,this.L=r,this.K=i,n.set(e),t.fill(0)}else{for(let a=0;a<this.D;a++)if(e[a]!==n[a]){let o=this.meshes.get(a),c=this.l[a];if(o?.geometry?.indices.length&&o.scene===r&&(i===-1||s(o)&i)&&+(c>=0)!==e[a]){if(c<0)this.S(o),t[a]=0;else{let e=this.i.get(o.geometry),t=--e.count*24,n=e.instances;e.mask-=k(n,c),c!==t&&(n.copyWithin(c,t,t+24),this.l[n[c+23]]=c,A(e,c)),this.l[a]=-1}}n[a]=e[a]}for(let e=t.indexOf(1);e>=0;e=t.indexOf(1,e+1)){t[e]=0;let n=this.l[e];if(n>=0){let t=this.meshes.get(e),r=this.i.get(t.geometry);r.mask-=k(r.instances,n),r.instances.set(t.matrix,n),r.mask+=k(r.instances,n),A(r,n)}}}}pick(e,t,n){let r=n&&{...n},i=this.x??(this.n?Promise.resolve():void 0),a,o=this.x=new Promise(e=>a=e),s=i?i.then(()=>this.disposed||this.j?null:this.R(e,t,r)):this.R(e,t,r),c=()=>{this.x===o&&(this.x=void 0),a()};return s.then(c,c),s}async R(e,t,a){if(![e,t].every(Number.isFinite))throw n(`Invalid pick`,`views`);if(this.m(),this.backend!==`webgpu`)throw i(`unsupported`,S,`webgpu`);let o=this.canvas.clientWidth||this.canvas.width,c=this.canvas.clientHeight||this.canvas.height;if(e<0||t<0||e>=o||t>=c||this.g)return null;this.E();let l=this.renderer,u=this.r,d=[this.canvas.width,this.canvas.height],f=e*d[0]/o,p=t*d[1]/c,m=e=>!e||f>=e[0]&&p>=e[1]&&f<e[0]+e[2]&&p<e[1]+e[3],g=(e,t)=>({...e,viewport:this.z(e.viewport,e.pixels,d,t),scissor:e.scissor&&this.z(e.scissor,e.pixels,d,t),pixels:!0}),_=a&&g(a);if(!a&&this.v){for(let e of this.v){let t=g(e,!0);m(t.viewport)&&m(t.scissor)&&(_=t)}if(!_)return null}if(_&&!(m(_.viewport)&&m(_.scissor)))return null;let v=_?.scene??this.scene,y=_?.camera??this.camera,b=_?.viewport;if(this.u(v),!(y instanceof h))throw r(`Invalid camera`,`arguments`);let x=this.h(v),C;try{this.G(!0,0,y,b,!0,0,_?.layers),_&&(_.layers=this.e===-1?void 0:this.e);let n=[...this.plugins.values()].find(e=>e.onPick);C=n?n.onPick(e,t,_):l.pick(y,this.lighting,this.k,this.frameGraph,f-(b?.[0]??0),p-(b?.[1]??0),b&&[b[2],b[3]]).then(e=>this.meshes.get(e??-1)??null)}finally{this.h(x)}let w=this.e,T=await C;return this.renderer===l&&(!T||this.meshes.get(T.id)===T&&T.born<u&&T.scene===v&&(w===-1||s(T)&w))?T:null}onFrame(e){return this.t.add(e),()=>{this.t.delete(e)}}start({culling:e}={}){this.m(),this.q.culling=e,!this.s&&(this.s=!0,this.o=0,globalThis.document?.addEventListener(`visibilitychange`,this.U),this.p=requestAnimationFrame(this.P))}U=()=>{this.o=0};N=0;Y=e=>e.onPreUpdate?.(this.N);W=e=>e(this,this.q.delta);P=e=>{if(this.p=null,this.s){if(!this.pace||this.pace(e)){let t=(e-this.o)/1e3,n=this.maxDelta,r=this.o?t!==t||t<n?t:n:0;this.o=e;try{this.q.delta=r,this.t.forEach(this.W),this.q.views=this.views?.length?this.views:void 0,this.disposed||this.render(this.q)}catch(e){this.stop(),this.onError(e);return}}this.s&&(this.p??=requestAnimationFrame(this.P))}};stop(){this.s=!1,this.p!==null&&cancelAnimationFrame(this.p),this.p=null,this.o=0,globalThis.document?.removeEventListener(`visibilitychange`,this.U)}dispose(){if(this.disposed||this.j)return;this.j=!0,this.stop(),this.A.abort(i(`disposed`,x));let e=[];for(let t of this.scenes)for(let n of t.plugins.keys())E(e,()=>this.removePlugin(n,t));for(let t of this.meshes.values())E(e,()=>t.dispose());if(this.t.clear(),E(e,()=>this.renderer.dispose()),E(e,()=>this.store.dispose()),this.disposed=!0,e.length)throw e[0]}};if(Symbol.dispose)for(let e of[P,M,N])e.prototype[Symbol.dispose]=e.prototype.dispose;export{P as Engine,M as Mesh,N as Scene,D as VectorRef};
1
+ import{t as e}from"./hypot-B7a6-Lk8.js";import{a as t,i as n,r,t as i}from"./errors-D0VAEAiW.js";import{a,n as o,r as s,t as c}from"./view-rect-DJ1fxok2.js";import{F32_OVERFLOW as l,Geometry as u,PbrMaterial as d,finite as f}from"./geometry.js";import{TransformStore as p,syncStoredRotation as m}from"./kernel.js";import{Camera as h}from"./camera.js";import{GPURenderer as g}from"./renderer.js";import{FrameGraph as _}from"./plugin.js";import{assertCore as v,coreRequirement as y}from"./version.js";import{sceneSamples as b}from"./quality.js";var x=`Engine disposed`,S=`WebGPU required`,C=[`x`,`y`,`z`],w=[`sx`,`sy`,`sz`],T=/* @__PURE__ */ new WeakMap,E=(e,t)=>{try{t()}catch(t){e.push(t)}},D=class{e;f;constructor(e,t){this.e=e,this.f=t}h(e){return this.e.check(),this.f===`rotation`?this.e.engine.store.rotations[this.e.id*3+e]:this.e.engine.store.transforms[(this.f===`scale`?w:C)[e]][this.e.id]}g(e){if(typeof e!=`number`||!(e<l&&e>-l))throw r(`Invalid transform`,`transform`)}i(e,t){this.e.check(),this.g(t),this.f===`rotation`?(this.e.engine.store.rotations[this.e.id*3+e]=t,this.e.syncRotation()):this.e.engine.store.transforms[(this.f===`scale`?w:C)[e]][this.e.id]=t}set(e,t,n){this.e.check(),this.g(e),this.g(t),this.g(n);let r=this.f===`scale`?w:C,i=this.e.engine.store.transforms,a=this.e.id;for(let o=0;o<3;o++){let s=o===0?e:o===1?t:n;this.f===`rotation`?this.e.engine.store.rotations[a*3+o]=s:i[r[o]][a]=s}return this.f===`rotation`&&this.e.syncRotation(),this}setAll(e){return this.set(e,e,e)}get x(){return this.h(0)}set x(e){this.i(0,e)}get y(){return this.h(1)}set y(e){this.i(1,e)}get z(){return this.h(2)}set z(e){this.i(2,e)}},O=(t,n,i,a)=>{let o=e(4,i[a],i[a+1],i[a+2],i[a+3]);if(!o)throw r(`Quaternion nonzero`,`transform`);let s=i[a]/o,c=i[a+1]/o,l=i[a+2]/o,u=i[a+3]/o,d=t.transforms,f=t.rotations,p=n*3;d.qx[n]=s,d.qy[n]=c,d.qz[n]=l,d.qw[n]=u;let m=2*(s*l+u*c),h=2*(u*l-s*c),g=1-2*(c*c+l*l);f[p+1]=Math.asin(m>1?1:m<-1?-1:m),h*h+g*g<36e-13?(f[p]=0,f[p+2]=2*Math.atan2(l,u)):(f[p]=Math.atan2(2*(u*s-c*l),1-2*(s*s+c*c)),f[p+2]=Math.atan2(h,g))},k=(e,t)=>+(e[t+22]>.5||e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])<0),A=(e,t)=>{let n=t/24,r=1<<(n&31),i=e.rows;e.dirty>=0&&!(i[n>>5]&r)&&(i[n>>5]|=r,e.dirty++)},j=e=>Object.assign(e,{matrix:e.engine.store.matrices.subarray(e.id*16,e.id*16+16)}),M=class{engine;id;scene;name=``;geometry=null;e=new d;get material(){return this.e}set material(e){if(!(e instanceof d))throw n(`Invalid material`,`arguments`);this.e=e,this.engine.collected=-1}f=!0;get receiveShadow(){return this.f}set receiveShadow(e){if(typeof e!=`boolean`)throw n(`receiveShadow: boolean`,`arguments`);this.f=e,this.engine.collected=-1}constructor(e,n,r=e.scene){this.engine=e,this.id=n,this.scene=r;for(let e of[`position`,`rotation`,`scale`]){let n=new D(this,e);Object.defineProperty(this,e,{get:()=>n,set:t,enumerable:!0})}j(this)}get visible(){return this.check(),this.engine.store.hidden[this.id]===0}set visible(e){if(this.check(),typeof e!=`boolean`)throw n(`Visibility: boolean`,`arguments`);this.engine.store.hidden[this.id]=+!e}check(){if(this.engine.disposed||this.engine.meshes.get(this.id)!==this)throw i(`disposed`,`Mesh disposed`)}setPosition(e){return this.check(),f(e,3,`Position`),this.position.set(e[0],e[1],e[2]),this}setScale(e){return this.check(),f(e,3,`Scale`),this.scale.set(e[0],e[1],e[2]),this}setRotation(e){return this.check(),f(e,3,`Rotation`),this.rotation.set(e[0],e[1],e[2]),this}syncRotation(){m(this.engine.store,this.id)}setQuaternion(e){return this.check(),f(e,4,`Quaternion`),O(this.engine.store,this.id,e,0),this}setParent(e){if(this.check(),e?.check(),e&&(e.engine!==this.engine||e.scene!==this.scene))throw n(`Foreign parent`,`hierarchy`);let t=0;for(let i=e?.id??-1;i!==-1;i=this.engine.store.parents[i]){if(i===this.id)throw n(`Hierarchy cycle`,`hierarchy`);if(++t>=64)throw r(`Parent depth: 64`,`hierarchy`)}let i=e=>{let t=0;for(let n of e?.kids??[])t=Math.max(t,1+i(this.engine.meshes.get(n)));return t};if(e&&t+i(this)>=64)throw r(`Parent depth: 64`,`hierarchy`);let a=this.engine.store.parents;return this.engine.meshes.get(a[this.id])?.kids?.delete(this.id),e&&(e.kids??=/* @__PURE__ */ new Set).add(this.id),a[this.id]=e?.id??-1,this}setGeometry(e){if(this.check(),e!==null&&!(e instanceof u))throw n(`Invalid geometry`,`arguments`);if(e===this.geometry)return this;e&&this.engine.retain(e);let t=this.geometry;this.geometry=e;let r=this.engine.store.bounds;return r.fill(0,this.id*4,this.id*4+4),e&&r.set(e.bounds,this.id*4),t&&this.engine.release(t),this.engine.collected=-1,this}setMaterial(e){return this.check(),this.material=e,this}dispose(){this.engine.meshes.get(this.id)===this&&this.engine.remove(this)}},N=class{engine;name;background;frameGraph=new _;plugins=/* @__PURE__ */ new Map;meshes=/* @__PURE__ */ new Map;stats={visible:0,drawCalls:0};lighting={direction:new Float32Array([3,5,4,3]),radiance:new Float32Array([1,1,1,.15]),ambient:new Float32Array([1,1,1])};constructor(e,t){this.engine=e,this.name=t}createMesh(e=null){return this.engine.createMesh(e,this)}use(e){return this.engine.use(e,this),this}removePlugin(e){this.engine.removePlugin(e,this)}dispose(){let e=this.engine,t=[];if(this===e.scene)throw n(`Default scene: dispose the engine instead`,`scene`);if(e.scenes.delete(this)){for(let n of this.plugins.keys())E(t,()=>e.removePlugin(n,this));for(let t of this.meshes.values())e.remove(t);if(t.length)throw t[0]}}},P=class e{canvas;store;renderer;fallbackReason;coreRequirement=y();scene;scenes=/* @__PURE__ */ new Set;meshes=/* @__PURE__ */ new Map;camera;disposed=!1;onError=e=>{typeof reportError==`function`?reportError(e):console.error(e)};pace;maxDelta=.1;views;j=/* @__PURE__ */ new Map;l=[];I=/* @__PURE__ */ new WeakMap;C=0;R=[];D=0;r=0;collected=-1;unshadowed=0;L;K=-1;w=[];F;m;t=/* @__PURE__ */ new Set;p=null;o=0;s=!1;f=0;U=!0;q={delta:null};k=!1;h;A=new AbortController;y=0;B=0;g;e=-1;v;x;J=/* @__PURE__ */ new WeakMap;features;exact;fixed;power;get frameGraph(){return this.g.frameGraph}get lighting(){return this.g.lighting}get stats(){return this.g.stats}get plugins(){return this.g.plugins}static async create(t,a={}){if(!t||typeof t.getContext!=`function`)throw n(`Expected canvas`,`arguments`);let o=a.backend??`auto`;if(![`auto`,`webgpu`,`webgl2`].includes(o))throw n(`Unknown backend`,`arguments`);let s=a.exactSize,c=a.antialias??!s?void 0:1;if(Array.isArray(s)){if(s.length!==2||!s.every(e=>Number.isInteger(e)&&e>0&&e<=8192))throw r(`Invalid exactSize`,`pixel-exact`);[t.width,t.height]=s}let l=await p.create(a.capacity??1024),u,d=null;try{if(a.signal?.throwIfAborted(),o!==`webgl2`)try{u=await g.create(t,a.features,c,a)}catch(e){if(o===`webgpu`||a.signal?.aborted)throw e;d=String(e)}u??=(a.fallback??(()=>{throw i(`unsupported`,o===`webgl2`?`webgl2 needs fallback: webglRenderer`:`WebGPU unavailable`,`webgpu`)}))(t);let n=new e(t,l,u,a.camera,d);return n.features=a.features,n.exact=c,n.fixed=s?1:void 0,n.power=a.powerPreference,n}catch(e){throw u?.dispose(),l.dispose(),e}}constructor(e,t,n,r,i){this.canvas=e,this.store=t,this.renderer=n,this.fallbackReason=i,this.camera=new h(r),this.scenes.add(this.scene=this.g=new N(this,`default`)),this.F=new Uint8Array(t.capacity),this.m=new Int32Array(t.capacity),this.W()}W(){let e=this.renderer,t=(n,r)=>{if(this.disposed||this.k||this.renderer!==e)return;let a=()=>t(n,r);if(this.h)return void this.h.then(a,a);r&&this.onError(n),this.B=0,++this.y<4?this.rebootDevice().catch(e=>this.disposed||this.onError(e)):this.y===4&&this.onError(i(`failed`,`GPU lost 4 times; reload the page`,`gpu-lost`))};e.onLost=t}rebootDevice(){return this.disposed||this.k?Promise.reject(i(`disposed`,x)):this.backend===`webgpu`?(this.h||=(async()=>{let e=this.renderer,t=await g.create(this.canvas,this.features,this.exact,{powerPreference:this.power,signal:this.A.signal},!1);try{this.A.signal.throwIfAborted();for(let e of this.j.values())t.add(e.geometry,e.instances.length/24);t.configure()}catch(e){throw t.dispose(!1),e}this.renderer=t,this.W(),e.dispose(!1);let n=[];for(let e of this.scenes){let t=this.i(e);for(let t of e.plugins.values())E(n,()=>t.onDeviceRestored?.(this));this.i(t)}if(n.length)throw n[0]})().finally(()=>{this.h=void 0}),this.h):Promise.reject(i(`unsupported`,S,`webgpu`))}O(){return this.y&&++this.B>=120&&(this.y=this.B=0),!0}get backend(){return this.renderer.backend}get renderTarget(){return this.renderer.target??null}get gpu(){return this.renderer.gpu??null}geometryBuffers(e){if(this.disposed||this.k||this.h)throw i(`state`,`Geometry unavailable`,`device-restore`);return e.indices.length?this.renderer.geometryBuffers?.(e)??null:null}hasPlugin(e){return this.plugins.has(e)}i(e){let t=this.g;if(t!==e){for(let n of this.j.values()){let r=this.J.get(n);r||this.J.set(n,r=/* @__PURE__ */ new WeakMap),r.set(t,[n.claimed,n.redirect]),[n.claimed,n.redirect]=r.get(e)??[]}this.g=e}return t}n(){if(this.disposed||this.k)throw i(`disposed`,x)}u(e){if(!this.scenes.has(e))throw n(`Unknown scene: use engine.createScene()`,`scene`)}use(e,t=this.g){this.n(),e.coreRequirement&&v(this,e.coreRequirement),this.u(t);let r=e.name,i=t.plugins;if(!r||i.has(r)||T.has(e)||typeof e.setup!=`function`)throw n(`Invalid plugin`,`arguments`);let a=this.i(t);try{t.frameGraph.withOwner(r,()=>{i.set(r,e);for(let[e,t]of[...i])t.late&&(i.delete(e),i.set(e,t));T.set(e,t);try{e.setup(this),e.registerPasses?.(t.frameGraph)}catch(n){t.frameGraph.removeOwner(r),i.delete(r),T.delete(e);try{e.dispose?.()}catch{}throw n}})}finally{this.i(a)}return this}removePlugin(e,t=this.g){let n=t.plugins.get(e);if(!n)return;t.frameGraph.removeOwner(e),t.plugins.delete(e),T.delete(n);let r=this.i(t);try{n.dispose?.()}finally{this.i(r)}}createScene(e=`scene`){this.n();let t=new N(this,e);return this.scenes.add(t),t}sceneOf(e){let t=T.get(e);return t?.engine===this?t:void 0}createMesh(e=null,t=this.g){if(this.n(),this.u(t),e?.check(),e&&(e.engine!==this||e.scene!==t))throw n(`Foreign parent`,`hierarchy`);let r=this.R.pop()??this.D++;if(r>=this.store.capacity)try{let e=Math.min(r*2,1<<23),t=new Uint8Array(e),n=new Int32Array(e);this.store.grow(e),this.F=t,this.m=n,this.meshes.forEach(j)}catch(e){throw this.D=r,e}let i=this.store.transforms;for(let e of[`x`,`y`,`z`,`qx`,`qy`,`qz`])i[e][r]=0;for(let e of[`qw`,`sx`,`sy`,`sz`])i[e][r]=1;this.store.parents[r]=-1,this.store.constrained[r]=0,this.store.hidden[r]=0,this.store.rotations.fill(0,r*3,r*3+3);let a=new M(this,r,t);this.meshes.set(r,a),t.meshes.set(r,a),a.born=this.r++,this.store.active[r]=1;try{return a.setParent(e)}catch(e){throw a.dispose(),e}}remove(e){let t=this.store.parents;if(e.check(),!this.k){for(let n of e.kids??[])t[n]=-1;e.setParent(null)}e.geometry&&this.release(e.geometry),this.meshes.delete(e.id),e.scene.meshes.delete(e.id),this.r++,this.store.active[e.id]=0,this.store.visible[e.id]=0,this.R.push(e.id)}writePoses(e,t,n=e.length){this.n();let{transforms:a,active:o}=this.store;if(!(n>=0&&n<=e.length&&t.length>=n*7))throw r(`Invalid poses`,`transform`);for(let a=0,s=0;a<n;a++,s+=7){if(o[e[a]]!==1)throw i(`disposed`,`Mesh disposed`);for(let e=s;e<s+7;e++){let n=t[e];if(typeof n!=`number`||!(n<l&&n>-l))throw r(`Invalid transform: ${a}`,`transform`)}if(!(t[s+3]||t[s+4]||t[s+5]||t[s+6]))throw r(`Quaternion nonzero: ${a}`,`transform`)}for(let r=0,i=0;r<n;r++,i+=7){let n=e[r];a.x[n]=t[i],a.y[n]=t[i+1],a.z[n]=t[i+2],O(this.store,n,t,i+3)}}retain(e){if(!e.indices.length)return;let t=this.j.get(e)??{geometry:e,instances:/* @__PURE__ */ new Float32Array,rows:/* @__PURE__ */ new Uint32Array,count:0,references:0};if(t.references>=t.instances.length/24){let n=(t.references+1)*2,r=new Float32Array(n*24),i=new Uint32Array(n+31>>5);this.renderer.add(e,n),t.instances=r,t.rows=i,this.collected=-1}t.references++||(this.j.set(e,t),this.l.push(t))}release(e){if(!e.indices.length)return;let t=this.j.get(e);--t.references===0&&(this.renderer.remove(e),this.j.delete(e),this.l.splice(this.l.indexOf(t),1))}Y=e=>{(this.e===-1||s(e)&this.e)&&(this.unshadowed+=+!e.receiveShadow,e.geometry?.indices.length&&this.store.visible[e.id]&&this.T(e))};T(e){if(this.I.get(e.material)!==this.C){let t=e.material.data;f(t,8,`Material`);for(let e=0;e<8;e++)if(t[e]<0||t[e]>1)throw r(`Invalid material`,`material`);if(t[3]!==1||t[4]<Math.fround(.045)||t[6]!==0&&t[6]!==1)throw r(`Invalid material`,`material`);this.I.set(e.material,this.C),this.w.push([e.material,...t])}let t=this.j.get(e.geometry),n=t.count++*24;this.m[e.id]=n,t.instances.set(e.matrix,n),t.instances.set(e.material.data,n+16),e.receiveShadow||(t.instances[n+22]+=.25),t.instances[n+23]=e.id,t.mask+=k(t.instances,n),A(t,n)}render({camera:e=this.camera,culling:t=!0,delta:r=0,views:a}={}){if(this.f)throw i(`state`,`Render recursion`,`reentrancy`);if(a)return this.a(a,t,r);if(!(e instanceof h))throw n(`Invalid camera`,`arguments`);this.f=1,this.v=void 0;let o=!1;try{this.G(t,r,e);let n=this.g.background,{width:i,height:a}=this.canvas;!this.h&&!this.disposed&&this.O()&&(this.f=2)&&this.renderer.render(e,this.lighting,this.l,this.frameGraph,r,n===void 0&&this.e===-1?void 0:{rect:[0,0,i,a],index:0,count:1,id:`0`,clear:n===void 0?void 0:{color:n??!1},layers:this.e===-1?void 0:this.e})}catch(e){throw o=!0,e}finally{try{e!==this.camera&&!this.disposed&&!this.k&&(this.camera.update(this.canvas.width/this.canvas.height,this.backend===`webgpu`),this.store.planes.set(this.camera.planes),this.store.tick(this.U),this.e=this.H(this.camera),this.M())}catch(e){if(!o)throw e}finally{this.P()}}}P(){let e=this.f>2;this.f=0,e&&this.dispose()}a(e,t,r){if(!Array.isArray(e)||!e.length)throw n(`Invalid views`,`views`);this.f=1;let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[],s=e=>e?.target?.color??this.canvas,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map;for(let t of e)c.set(s(t),(c.get(s(t))??0)+1);let u=[...c.keys()],d=e.map((e,t)=>t).sort((t,n)=>u.indexOf(s(e[t]))-u.indexOf(s(e[n])));try{this.E();for(let u of d){let d=e[u];if(!(d?.camera instanceof h)||!d.viewport)throw n(`Invalid view: pass {camera, viewport}`,`views`);let f={...d,viewport:[...d.viewport],scissor:d.scissor&&[...d.scissor]},p=f.scene??this.scene,m=f.target?.color,g=m?[m.width,m.height]:[this.canvas.width,this.canvas.height],_=this.z(f.viewport,f.pixels,g),v=!a.has(p);if(this.u(p),this.i(p),this.G(t,i.has(f.camera)?0:r,f.camera,_,v,r,f.layers),this.disposed||(i.add(f.camera),a.add(p),!this.h&&(u||this.O())&&(this.f=2)&&this.renderer.render(f.camera,this.lighting,this.l,this.frameGraph,v?r:0,{rect:_,scissor:f.scissor&&this.z(f.scissor,f.pixels,g),layers:this.e===-1?void 0:this.e,index:l.get(s(f))??0,count:c.get(s(f)),id:f.id??String(u),clear:f.clear??(p.background===void 0?void 0:{color:p.background??!1}),target:f.target}),l.set(s(f),(l.get(s(f))??0)+1),m||o.push(f),this.f>2))break;this.f=1}}finally{this.P(),this.v=o,this.i(this.scene)}}z(e,t,[n,r],i){let o=t?[...e]:[Math.round(e[0]*n),Math.round(e[1]*r),Math.round((e[0]+e[2])*n)-Math.round(e[0]*n),Math.round((e[1]+e[3])*r)-Math.round(e[1]*r)];return i||a(o,n,r),o}G(e,t,n=this.camera,i,a=!0,o=t,s){if(this.n(),!Number.isFinite(o)||o<0||o>1)throw r(`Invalid delta`,`arguments`);if(this.N=o,a&&this.plugins.forEach(this.Z),this.disposed)return;i||this.E(),n.advance(t),n.update(i?i[2]/i[3]:this.canvas.width/this.canvas.height,this.backend===`webgpu`),this.e=this.H(n,s),this.store.planes.set(n.planes),this.store.tick(e);let{direction:c,radiance:l,ambient:u}=this.lighting;f(c,4,`Light`),f(l,4,`Radiance`),f(u,3,`Ambient`);let d=!(c[0]||c[1]||c[2])||c[3]<0;for(let e=0;e<4;e++)d||=l[e]<0||e<3&&u[e]<0;if(d)throw r(`Invalid lighting`,`lighting`);if(this.M(),this.f){let{stats:e}=this,t=this.l;e.visible=e.drawCalls=0;for(let n=0;n<t.length;n++)e.visible+=t[n].count,(t[n].count||t[n].redirect)&&!t[n].claimed&&e.drawCalls++}n===this.camera&&(this.U=e)}H(e,t){return(t===void 0?o()?.cameras.get(e)??-1:c(t,`View layers`))|0}E(){if(this.fixed)return;let e=Math.min(globalThis.devicePixelRatio??1,globalThis.margoLow||2,4/b(this)),t=Math.round(this.canvas.clientWidth*e)||this.canvas.width,n=Math.round(this.canvas.clientHeight*e)||this.canvas.height,r=Math.min(1,(this.gpu?.limits.maxTextureDimension2D??4096)/Math.max(t,n)),i=Math.max(1,Math.round(t*r)),a=Math.max(1,Math.round(n*r));this.canvas.width!==i&&(this.canvas.width=i),this.canvas.height!==a&&(this.canvas.height=a)}M(){let{visible:e,changed:t}=this.store,n=this.F,r=this.g,i=this.e,a=this.collected!==this.r||this.L!==r||this.K!==i||i!==-1&&!!o()?.source;for(let e=0;!a&&e<this.w.length;e++)for(let t=0,n=this.w[e];!a&&t<8;t++)a=n[0].data[t]!==n[t+1];if(a){this.collected=-1;for(let e of this.l)e.count=e.mask=0,e.dirty=-1;this.unshadowed=0,this.C++,this.w.length=0,this.m.fill(-1),r.meshes.forEach(this.Y),this.collected=this.r,this.L=r,this.K=i,n.set(e),t.fill(0)}else{for(let a=0;a<this.D;a++)if(e[a]!==n[a]){let o=this.meshes.get(a),c=this.m[a];if(o?.geometry?.indices.length&&o.scene===r&&(i===-1||s(o)&i)&&+(c>=0)!==e[a]){if(c<0)this.T(o),t[a]=0;else{let e=this.j.get(o.geometry),t=--e.count*24,n=e.instances;e.mask-=k(n,c),c!==t&&(n.copyWithin(c,t,t+24),this.m[n[c+23]]=c,A(e,c)),this.m[a]=-1}}n[a]=e[a]}for(let e=t.indexOf(1);e>=0;e=t.indexOf(1,e+1)){t[e]=0;let n=this.m[e];if(n>=0){let t=this.meshes.get(e),r=this.j.get(t.geometry);r.mask-=k(r.instances,n),r.instances.set(t.matrix,n),r.mask+=k(r.instances,n),A(r,n)}}}}pick(e,t,n){let r=n&&{...n},i=this.x??(this.f?Promise.resolve():void 0),a,o=this.x=new Promise(e=>a=e),s=i?i.then(()=>this.disposed||this.k?null:this.S(e,t,r)):this.S(e,t,r),c=()=>{this.x===o&&(this.x=void 0),a()};return s.then(c,c),s}async S(e,t,a){if(![e,t].every(Number.isFinite))throw r(`Invalid pick`,`views`);if(this.n(),this.backend!==`webgpu`)throw i(`unsupported`,S,`webgpu`);let o=this.canvas.clientWidth||this.canvas.width,c=this.canvas.clientHeight||this.canvas.height;if(e<0||t<0||e>=o||t>=c||this.h)return null;this.E();let l=this.renderer,u=this.r,d=[this.canvas.width,this.canvas.height],f=e*d[0]/o,p=t*d[1]/c,m=e=>!e||f>=e[0]&&p>=e[1]&&f<e[0]+e[2]&&p<e[1]+e[3],g=(e,t)=>({...e,viewport:this.z(e.viewport,e.pixels,d,t),scissor:e.scissor&&this.z(e.scissor,e.pixels,d,t),pixels:!0}),_=a&&g(a);if(!a&&this.v){for(let e of this.v){let t=g(e,!0);m(t.viewport)&&m(t.scissor)&&(_=t)}if(!_)return null}if(_&&!(m(_.viewport)&&m(_.scissor)))return null;let v=_?.scene??this.scene,y=_?.camera??this.camera,b=_?.viewport;if(this.u(v),!(y instanceof h))throw n(`Invalid camera`,`arguments`);let x=this.i(v),C;try{this.G(!0,0,y,b,!0,0,_?.layers),_&&(_.layers=this.e===-1?void 0:this.e);let n=[...this.plugins.values()].find(e=>e.onPick);C=n?n.onPick(e,t,_):l.pick(y,this.lighting,this.l,this.frameGraph,f-(b?.[0]??0),p-(b?.[1]??0),b&&[b[2],b[3]]).then(e=>this.meshes.get(e??-1)??null)}finally{this.i(x)}let w=this.e,T=await C;return this.renderer===l&&(!T||this.meshes.get(T.id)===T&&T.born<u&&T.scene===v&&(w===-1||s(T)&w))?T:null}onFrame(e){return this.t.add(e),()=>{this.t.delete(e)}}start({culling:e}={}){this.n(),this.q.culling=e,!this.s&&(this.s=!0,this.o=0,globalThis.document?.addEventListener(`visibilitychange`,this.V),this.p=requestAnimationFrame(this.Q))}V=()=>{this.o=0};N=0;Z=e=>e.onPreUpdate?.(this.N);X=e=>e(this,this.q.delta);Q=e=>{if(this.p=null,this.s){if(!this.pace||this.pace(e)){let t=(e-this.o)/1e3,n=this.maxDelta,r=this.o?t!==t||t<n?t:n:0;this.o=e;try{this.q.delta=r,this.t.forEach(this.X),this.q.views=this.views?.length?this.views:void 0,this.disposed||this.render(this.q)}catch(e){this.stop(),this.onError(e);return}}this.s&&(this.p??=requestAnimationFrame(this.Q))}};stop(){this.s=!1,this.p!==null&&cancelAnimationFrame(this.p),this.p=null,this.o=0,globalThis.document?.removeEventListener(`visibilitychange`,this.V)}dispose(){if(this.disposed||this.k||this.f>1&&(this.f=3))return;this.k=!0,this.stop(),this.A.abort(i(`disposed`,x));let e=[];for(let t of this.scenes)for(let n of t.plugins.keys())E(e,()=>this.removePlugin(n,t));for(let t of this.meshes.values())E(e,()=>t.dispose());if(this.t.clear(),E(e,()=>this.renderer.dispose()),E(e,()=>this.store.dispose()),this.disposed=!0,e.length)throw e[0]}};if(Symbol.dispose)for(let e of[P,M,N])e.prototype[Symbol.dispose]=e.prototype.dispose;export{P as Engine,M as Mesh,N as Scene,D as VectorRef};
@@ -1 +1 @@
1
- var e=(e,t)=>Object.assign(Error(t),{name:`MargoError`,code:e}),t=(e,t)=>`${e}; see https://margoengine.com/errors#${t}`,n=(n,r,i=n)=>e(n,t(r,i)),r=(e,n)=>TypeError(t(e,n)),i=(e,n)=>RangeError(t(e,n)),a=()=>{throw Object.assign(r(`Retained vector: use a transform setter`,`transform`),{code:`transform`})};function o(t){return!/^(Compile|Eval|Runtime)Error$/.test(t?.name)||!/wasm-unsafe-eval|content security policy|\bCSP\b|disallowed by embedder/i.test(t.message)?t:Object.assign(e(`failed`,`Wasm compilation blocked by CSP; add 'wasm-unsafe-eval' to script-src; see https://margoengine.com/llms/docs/csp.md`),{cause:t})}export{o as a,a as i,i as n,r,n as t};
1
+ var e=(e,t)=>Object.assign(Error(t),{name:`MargoError`,code:e}),t=(e,t)=>`${e}; see https://margoengine.com/errors#${t}`,n=(n,r,i=n)=>e(n,t(r,i)),r=(e,n)=>TypeError(t(e,n)),i=(e,n)=>RangeError(t(e,n)),a=()=>{throw Object.assign(r(`Retained vector: use a transform setter`,`transform`),{code:`transform`})};function o(t){return!/^(Compile|Eval|Runtime)Error$/.test(t?.name)||!/wasm-unsafe-eval|content security policy|\bCSP\b|disallowed by embedder/i.test(t.message)?t:Object.assign(e(`failed`,`Wasm compilation blocked by CSP; add 'wasm-unsafe-eval' to script-src; see https://margoengine.com/llms/docs/csp.md`),{cause:t})}export{a,r as i,e as n,o,i as r,n as t};
@@ -2,7 +2,7 @@ export { Engine, Mesh, VectorRef } from './engine.js';
2
2
  export type { FrameCallback, EngineOptions, Scene } from './engine.js';
3
3
  export { TransformStore } from './kernel.js';
4
4
  export { FrameGraph } from './plugin.js';
5
- export type { EnginePlugin, FramePass, PassContext, DrawOptions } from './plugin.js';
5
+ export type { EnginePlugin, FramePass, PassContext, DrawOptions, Snapshot } from './plugin.js';
6
6
  export { Geometry, PbrMaterial, box } from './geometry.js';
7
7
  export { Camera } from './camera.js';
8
8
  export type { Vec3, CameraOptions } from './camera.js';
@@ -16,3 +16,6 @@ export type { CoreRequirement } from './version.js';
16
16
  export declare const engineRuntime: (engine: EngineKernel, version?: string, source?: string) => Engine;
17
17
  /** Type-only view of a public mesh handle as its runtime `Mesh` (no check or copy; same object). */
18
18
  export declare const meshRuntime: (mesh: MeshHandle) => Mesh;
19
+ export { fault, margoError, rangeError, typeError } from './shared/errors.js';
20
+ export type { MargoErrorCode } from './shared/errors.js';
21
+ export { hypot, hypotOf, hypotTerms } from './shared/hypot.js';
package/dist/extension.js CHANGED
@@ -1 +1 @@
1
- import{Engine as e,Mesh as t,VectorRef as n}from"./engine.js";import{Geometry as r,PbrMaterial as i,box as a}from"./geometry.js";import{TransformStore as o}from"./kernel.js";import{Camera as s}from"./camera.js";import{uploadRows as c}from"./renderer.js";import{FrameGraph as l}from"./plugin.js";import{CORE_VERSION as u,CORE_VERSION as d,assertCore as f,assertCore as p,coreRequirement as m,coreRequirement as h}from"./version.js";var g=(e,t=d,n=import.meta.url)=>(p(e,h(t,n)),e),_=e=>e;export{u as CORE_VERSION,s as Camera,e as Engine,l as FrameGraph,r as Geometry,t as Mesh,i as PbrMaterial,o as TransformStore,n as VectorRef,f as assertCore,a as box,m as coreRequirement,g as engineRuntime,_ as meshRuntime,c as uploadRows};
1
+ import{n as e,r as t,t as n}from"./hypot-B7a6-Lk8.js";import{i as r,n as i,r as a,t as o}from"./errors-D0VAEAiW.js";import{Engine as s,Mesh as c,VectorRef as l}from"./engine.js";import{Geometry as u,PbrMaterial as d,box as f}from"./geometry.js";import{TransformStore as p}from"./kernel.js";import{Camera as m}from"./camera.js";import{uploadRows as h}from"./renderer.js";import{FrameGraph as g}from"./plugin.js";import{CORE_VERSION as _,CORE_VERSION as v,assertCore as y,assertCore as b,coreRequirement as x,coreRequirement as S}from"./version.js";var C=(e,t=v,n=import.meta.url)=>(b(e,S(t,n)),e),w=e=>e;export{_ as CORE_VERSION,m as Camera,s as Engine,g as FrameGraph,u as Geometry,c as Mesh,d as PbrMaterial,p as TransformStore,l as VectorRef,y as assertCore,f as box,x as coreRequirement,C as engineRuntime,o as fault,n as hypot,e as hypotOf,t as hypotTerms,i as margoError,w as meshRuntime,a as rangeError,r as typeError,h as uploadRows};
package/dist/geometry.js CHANGED
@@ -1 +1 @@
1
- import{n as e,r as t}from"./errors-B6KSysyy.js";import{a as n,i as r}from"./clear-color-jWdkJ0Fa.js";var i=34028235677973366e22;function a(n,r,i){if(n.length!==r)throw t(`${i}: ${r} values`,`transform`);for(let t=0;t<r;t++){let r=n[t];if(typeof r!=`number`||!(Math.abs(r)<34028235677973366e22))throw e(`${i}: finite values`,`transform`)}}var o=class{vertices;indices;bounds;constructor(t,n,r){let i=t.length/3;if(!Number.isInteger(i)||i>11184810||(i===0?r.length!==0:i<3||!r.length)||r.length%3)throw e(`Invalid geometry`,`geometry`);a(t,i*3,`Positions`),a(n,i*3,`Normals`);for(let t=0;t<r.length;t++)if(!Number.isInteger(r[t])||r[t]<0||r[t]>=i)throw e(`Invalid geometry`,`geometry`);this.vertices=new Float32Array(i*6);let o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];for(let e=0;e<i;e++)for(let r=0;r<3;r++)this.vertices[e*6+r]=t[e*3+r],this.vertices[e*6+3+r]=n[e*3+r],o[r]=Math.min(o[r],t[e*3+r]),s[r]=Math.max(s[r],t[e*3+r]);this.indices=Uint32Array.from(r);let c=this.bounds=/* @__PURE__ */ new Float32Array(4),l=this.vertices;if(i)for(let e=0;e<3;e++)c[e]=(o[e]+s[e])/2;let u=0;for(let e=0;e<i;e++)u=Math.max(u,Math.hypot(l[e*6]-c[0],l[e*6+1]-c[1],l[e*6+2]-c[2]));c[3]=u,c[3]<u&&new Uint32Array(c.buffer)[3]++,a(c,4,`Bounds`)}};function s(t=1,n=1,r=1){let i=[t,n,r];if(a(i,3,`Box size`),Math.min(t,n,r)<=0)throw e(`Box size: positive`,`geometry`);let s=[],c=[],l=[];for(let e=0;e<3;e++)for(let t of[-1,1]){let n=s.length/3,r=(e+1)%3;for(let[n,a]of[[-1,-1],[1,-1],[1,1],[-1,1]])for(let o=0;o<3;o++)s.push((o===e?t:o===r?n:a)*i[o]/2),c.push(o===e?t:0);for(let e of t>0?[0,1,2,0,2,3]:[0,2,1,0,3,2])l.push(n+e)}return new o(s,c,l)}var c=class{data=new Float32Array([0,0,0,1,.5,0,1,0]);constructor(e={}){this.set({...e,color:e.color??`#4f46e5`})}set({color:i=this.data.slice(0,3),roughness:o=this.data[4],metalness:s=this.data[5],doubleSided:c=!!this.data[6]}){let l=typeof i==`string`?r(i):0,u=typeof i==`string`?l<0?null:[16,8,0].map(e=>n(l>>e&255)):i;if(!u)throw t(`Invalid Color`,`material`);if(a(u,3,`Color`),[...u,o,s].some(e=>!Number.isFinite(e)||e<0||e>1))throw e(`Invalid material`,`material`);if(typeof c!=`boolean`)throw t(`Invalid material`,`material`);this.data.set([...u,1,Math.max(.045,o),s,+c])}};export{i as F32_OVERFLOW,o as Geometry,c as PbrMaterial,s as box,a as finite};
1
+ import{i as e,r as t}from"./errors-D0VAEAiW.js";import{a as n,i as r}from"./clear-color-ziMPCpSz.js";var i=34028235677973366e22;function a(n,r,i){if(n.length!==r)throw e(`${i}: ${r} values`,`transform`);for(let e=0;e<r;e++){let r=n[e];if(typeof r!=`number`||!(Math.abs(r)<34028235677973366e22))throw t(`${i}: finite values`,`transform`)}}var o=class{vertices;indices;bounds;constructor(e,n,r){let i=e.length/3;if(!Number.isInteger(i)||i>11184810||(i===0?r.length!==0:i<3||!r.length)||r.length%3)throw t(`Invalid geometry`,`geometry`);a(e,i*3,`Positions`),a(n,i*3,`Normals`);for(let e=0;e<r.length;e++)if(!Number.isInteger(r[e])||r[e]<0||r[e]>=i)throw t(`Invalid geometry`,`geometry`);this.vertices=new Float32Array(i*6);let o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];for(let t=0;t<i;t++)for(let r=0;r<3;r++)this.vertices[t*6+r]=e[t*3+r],this.vertices[t*6+3+r]=n[t*3+r],o[r]=Math.min(o[r],e[t*3+r]),s[r]=Math.max(s[r],e[t*3+r]);this.indices=Uint32Array.from(r);let c=this.bounds=/* @__PURE__ */ new Float32Array(4),l=this.vertices;if(i)for(let e=0;e<3;e++)c[e]=(o[e]+s[e])/2;let u=0;for(let e=0;e<i;e++)u=Math.max(u,Math.hypot(l[e*6]-c[0],l[e*6+1]-c[1],l[e*6+2]-c[2]));c[3]=u,c[3]<u&&new Uint32Array(c.buffer)[3]++,a(c,4,`Bounds`)}};function s(e=1,n=1,r=1){let i=[e,n,r];if(a(i,3,`Box size`),Math.min(e,n,r)<=0)throw t(`Box size: positive`,`geometry`);let s=[],c=[],l=[];for(let e=0;e<3;e++)for(let t of[-1,1]){let n=s.length/3,r=(e+1)%3;for(let[n,a]of[[-1,-1],[1,-1],[1,1],[-1,1]])for(let o=0;o<3;o++)s.push((o===e?t:o===r?n:a)*i[o]/2),c.push(o===e?t:0);for(let e of t>0?[0,1,2,0,2,3]:[0,2,1,0,3,2])l.push(n+e)}return new o(s,c,l)}var c=class{data=new Float32Array([0,0,0,1,.5,0,1,0]);constructor(e={}){this.set({...e,color:e.color??`#4f46e5`})}set({color:i=this.data.slice(0,3),roughness:o=this.data[4],metalness:s=this.data[5],doubleSided:c=!!this.data[6]}){let l=typeof i==`string`?r(i):0,u=typeof i==`string`?l<0?null:[16,8,0].map(e=>n(l>>e&255)):i;if(!u)throw e(`Invalid Color`,`material`);if(a(u,3,`Color`),[...u,o,s].some(e=>!Number.isFinite(e)||e<0||e>1))throw t(`Invalid material`,`material`);if(typeof c!=`boolean`)throw e(`Invalid material`,`material`);this.data.set([...u,1,Math.max(.045,o),s,+c])}};export{i as F32_OVERFLOW,o as Geometry,c as PbrMaterial,s as box,a as finite};
@@ -1 +1 @@
1
- var e=/* @__PURE__ */ new Float64Array(5);function t(t){let n=e,r=0,i=0,a=0,o=!1;for(let e=0;e<t;e++){let t=n[e]=Math.abs(n[e]);t>r?r=t:t!==t&&(o=!0)}if(r===1/0||o||!r)n[4]=r===1/0||!o?r:NaN;else{for(let e=0;e<t;e++){let t=n[e]/r,o=t*t-a,s=i+o;a=s-i-o,i=s}n[4]=i,n[4]=Math.sqrt(n[4])*r}}function n(n,r,i,a=0,o=0){let s=e;return s[0]=r,s[1]=i,s[2]=a,s[3]=o,t(n),s[4]}export{n as t};
1
+ var e=/* @__PURE__ */ new Float64Array(5);function t(t){let n=e,r=0,i=0,a=0,o=!1;for(let e=0;e<t;e++){let t=n[e]=Math.abs(n[e]);t>r?r=t:t!==t&&(o=!0)}if(r===1/0||o||!r)n[4]=r===1/0||!o?r:NaN;else{for(let e=0;e<t;e++){let t=n[e]/r,o=t*t-a,s=i+o;a=s-i-o,i=s}n[4]=i,n[4]=Math.sqrt(n[4])*r}}function n(n,r,i,a=0,o=0){let s=e;return s[0]=r,s[1]=i,s[2]=a,s[3]=o,t(n),s[4]}export{t as n,e as r,n as t};
package/dist/kernel.js CHANGED
@@ -1 +1 @@
1
- import{a as e,n as t,t as n}from"./errors-B6KSysyy.js";import{wasmBase64 as r}from"./wasm.js";var i=/* @__PURE__ */ new WeakMap;function a(e,t){let r=i.get(e);if(!r?.handle)throw n(`disposed`,`Transforms disposed`);r.api.kernel_sync_rotation(r.handle,t)}var o,s=0,c=1,l=2,u=3,d=4,f=5,p=6,m=7,h=8,g=9,_=10,v=11,y=27,b=35,x=38,S=24,C=0,w=1,T=2,E=3,D=6,O=class a{f;static async create(t=1024){o??=(async()=>{let e=Uint8Array.from(atob(r),e=>e.charCodeAt(0));return WebAssembly.compile(await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate-raw`))).arrayBuffer())})().catch(e=>{throw o=void 0,e});try{let e=await WebAssembly.instantiate(await o);return new a(e.exports,t)}catch(t){throw e(t)}}constructor(e,t){this.f=e,i.set(this,{handle:0,api:e}),this.g(t)}g(e){if(!Number.isSafeInteger(e)||e<1||e>1<<23)throw t(`Capacity: 1..8388608`,`limits`);let r=this.f,a=r.kernel_new(e);if(!a)throw n(`failed`,`Transform allocation`,`limits`);let o=r.kernel_data(a),O=r.kernel_flags(a),k=r.memory.buffer,A=(t,n=e)=>new Float32Array(k,o+t*4,n),j=t=>new Uint8Array(k,O+t*e,e);this.e=a;let M=i.get(this);M&&(M.handle=a),Object.assign(this,{capacity:e,transforms:{x:A(s*e),y:A(c*e),z:A(l*e),qx:A(u*e),qy:A(d*e),qz:A(f*e),qw:A(p*e),sx:A(m*e),sy:A(h*e),sz:A(g*e)},parents:A(_*e),matrices:A(v*e,16*e),bounds:A(y*e,4*e),planes:A(b*e,S),rotations:A(b*e+S,3*e),limits:A(x*e+S,12*e),active:j(C),visible:j(w),constrained:j(T),hidden:j(E),changed:j(D)})}grow(e){if(!(e>this.capacity))throw t(`Capacity`,`limits`);let n=()=>Object.values({...this.transforms,...this}).filter(ArrayBuffer.isView),r=n().map(e=>e.slice()),i=this.capacity;this.f.kernel_drop(this.e);try{this.g(e)}catch(e){throw this.g(i),e}finally{n().forEach((e,t)=>e.set(r[t]))}}tick(e=!0){if(!this.e)throw n(`disposed`,`Transforms disposed`);let r=this.f.kernel_tick(this.e,+e);if(r)throw r>this.capacity?t(`Invalid frustum`,`camera`):t(`Invalid transform/bounds: ${r-1}`,`transform`)}dispose(){let e=i.get(this);e&&(e.handle=0),this.e&&=(this.f.kernel_drop(this.e),0)}};export{O as TransformStore,a as syncStoredRotation};
1
+ import{o as e,r as t,t as n}from"./errors-D0VAEAiW.js";import{wasmBase64 as r}from"./wasm.js";var i=/* @__PURE__ */ new WeakMap;function a(e,t){let r=i.get(e);if(!r?.handle)throw n(`disposed`,`Transforms disposed`);r.api.kernel_sync_rotation(r.handle,t)}var o,s=0,c=1,l=2,u=3,d=4,f=5,p=6,m=7,h=8,g=9,_=10,v=11,y=27,b=35,x=38,S=24,C=0,w=1,T=2,E=3,D=6,O=class a{f;static async create(t=1024){o??=(async()=>{let e=Uint8Array.from(atob(r),e=>e.charCodeAt(0));return WebAssembly.compile(await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate-raw`))).arrayBuffer())})().catch(e=>{throw o=void 0,e});try{let e=await WebAssembly.instantiate(await o);return new a(e.exports,t)}catch(t){throw e(t)}}constructor(e,t){this.f=e,i.set(this,{handle:0,api:e}),this.g(t)}g(e){if(!Number.isSafeInteger(e)||e<1||e>1<<23)throw t(`Capacity: 1..8388608`,`limits`);let r=this.f,a=r.kernel_new(e);if(!a)throw n(`failed`,`Transform allocation`,`limits`);let o=r.kernel_data(a),O=r.kernel_flags(a),k=r.memory.buffer,A=(t,n=e)=>new Float32Array(k,o+t*4,n),j=t=>new Uint8Array(k,O+t*e,e);this.e=a;let M=i.get(this);M&&(M.handle=a),Object.assign(this,{capacity:e,transforms:{x:A(s*e),y:A(c*e),z:A(l*e),qx:A(u*e),qy:A(d*e),qz:A(f*e),qw:A(p*e),sx:A(m*e),sy:A(h*e),sz:A(g*e)},parents:A(_*e),matrices:A(v*e,16*e),bounds:A(y*e,4*e),planes:A(b*e,S),rotations:A(b*e+S,3*e),limits:A(x*e+S,12*e),active:j(C),visible:j(w),constrained:j(T),hidden:j(E),changed:j(D)})}grow(e){if(!(e>this.capacity))throw t(`Capacity`,`limits`);let n=()=>Object.values({...this.transforms,...this}).filter(ArrayBuffer.isView),r=n().map(e=>e.slice()),i=this.capacity;this.f.kernel_drop(this.e);try{this.g(e)}catch(e){throw this.g(i),e}finally{n().forEach((e,t)=>e.set(r[t]))}}tick(e=!0){if(!this.e)throw n(`disposed`,`Transforms disposed`);let r=this.f.kernel_tick(this.e,+e);if(r)throw r>this.capacity?t(`Invalid frustum`,`camera`):t(`Invalid transform/bounds: ${r-1}`,`transform`)}dispose(){let e=i.get(this);e&&(e.handle=0),this.e&&=(this.f.kernel_drop(this.e),0)}};export{O as TransformStore,a as syncStoredRotation};
package/dist/plugin.d.ts CHANGED
@@ -21,6 +21,15 @@ export interface DrawOptions {
21
21
  scissor?: readonly [number, number, number, number];
22
22
  /** Stencil clear value when the depth format has stencil; setting it clears stencil even with `clear: false`. Default 0. */
23
23
  stencilClear?: number;
24
+ /**
25
+ * Record this draw's batches into a WebGPU render bundle the first time and replay it after that (WebGPU
26
+ * "Bundles", GPURenderBundleEncoder and executeBundles): the CPU no longer encodes each batch, only their changed
27
+ * rows are uploaded. Core records again when the draw's pipeline or bind group differs from the recording; any other
28
+ * change to what is drawn (batches, their counts, buffers, `mask` or `redirect`) is the caller's to see, by clearing
29
+ * `bundle`. Ignored with `colorAttachments`. Default the context's `snapshot`. `@margoengine/culling/snapshot` does this
30
+ * for the main pass.
31
+ */
32
+ snapshot?: Snapshot;
24
33
  /** Draw with drawIndexedIndirect. Default the context's `indirect`. */
25
34
  indirect?: boolean;
26
35
  /** Extra color attachments after the main color target. */
@@ -28,6 +37,12 @@ export interface DrawOptions {
28
37
  /** Marks a draw that writes per-mesh ids (factors.w) into an extra attachment. Core ignores it; a package drawing claimed batches' meshes from its own buffers draws them one mesh at a time so each writes its own id. Default false. */
29
38
  partIds?: boolean;
30
39
  }
40
+ /** A recorded core draw ({@link DrawOptions.snapshot}): core sets every field; clear `bundle` to record again. */
41
+ export interface Snapshot {
42
+ bundle?: GPURenderBundle;
43
+ /** The draw's bind group 0, which names its pipeline too. */
44
+ group?: GPUBindGroup;
45
+ }
31
46
  /**
32
47
  * What a {@link FramePass} receives each frame: `delta` in seconds, the drawing-buffer `width`/`height` in pixels,
33
48
  * the camera, `draw`, and the backend-specific device handles.
@@ -81,6 +96,8 @@ export type PassContext = {
81
96
  shader: string;
82
97
  bindings: GPUBindGroupEntry[];
83
98
  indirect: boolean;
99
+ /** The next core draw's {@link DrawOptions.snapshot}; that draw clears it, so a pass sets it for one draw. */
100
+ snapshot?: Snapshot;
84
101
  descriptor: GPURenderPipelineDescriptor;
85
102
  /**
86
103
  * For a {@link FramePass} that `joins`: call it just before each `beginRenderPass` on `color` and `depth`, on
package/dist/plugin.js CHANGED
@@ -1 +1 @@
1
- import{r as e,t}from"./errors-B6KSysyy.js";var n=class{revision=0;e=[{name:`main`,order:0,joins:!0,execute:e=>{e.only=!0,e.draw(),e.only=!1}}];g;f=!1;idle(){if(this.f)throw t(`state`,`Graph executing`,`reentrancy`)}add(t){if(this.idle(),!t.name||!Number.isFinite(t.order)||typeof t.execute!=`function`||this.e.some(e=>e.name===t.name))throw e(`Invalid pass`,`arguments`);let n={...t,owner:this.g,execute:e=>t.execute(e),prepare:e=>t.prepare?.(e)};return this.e.push(n),this.e.sort((e,t)=>e.order-t.order),this.revision++,()=>{this.idle(),this.e=this.e.filter(e=>e!==n),this.revision++}}withOwner(e,t){this.idle();let n=this.g;this.g=e;try{t()}finally{this.g=n}}removeOwner(e){this.idle(),this.e=this.e.filter(t=>t.owner!==e),this.revision++}execute(e){if(this.f)throw t(`state`,`Graph recursion`,`reentrancy`);this.f=!0;try{for(let t=0;t<this.e.length;t++)e.last=t+1===this.e.length&&this.e[t].joins,e.joins=this.e[t+1]?.joins,this.e[t].execute(e),e.backend===`webgpu`&&!e.joins&&e.settle?.()}finally{this.f=!1}}prepare(e){if(this.f)throw t(`state`,`Graph recursion`,`reentrancy`);this.f=!0;try{for(let t of this.e)t.prepare?.(e)}finally{this.f=!1}}};export{n as FrameGraph};
1
+ import{i as e,t}from"./errors-D0VAEAiW.js";var n=class{revision=0;e=[{name:`main`,order:0,joins:!0,execute:e=>{e.only=!0,e.draw(),e.only=!1}}];g;f=!1;idle(){if(this.f)throw t(`state`,`Graph executing`,`reentrancy`)}add(t){if(this.idle(),!t.name||!Number.isFinite(t.order)||typeof t.execute!=`function`||this.e.some(e=>e.name===t.name))throw e(`Invalid pass`,`arguments`);let n={...t,owner:this.g,execute:e=>t.execute(e),prepare:e=>t.prepare?.(e)};return this.e.push(n),this.e.sort((e,t)=>e.order-t.order),this.revision++,()=>{this.idle(),this.e=this.e.filter(e=>e!==n),this.revision++}}withOwner(e,t){this.idle();let n=this.g;this.g=e;try{t()}finally{this.g=n}}removeOwner(e){this.idle(),this.e=this.e.filter(t=>t.owner!==e),this.revision++}execute(e){if(this.f)throw t(`state`,`Graph recursion`,`reentrancy`);this.f=!0;try{for(let t=0;t<this.e.length;t++)e.last=t+1===this.e.length&&this.e[t].joins,e.joins=this.e[t+1]?.joins,this.e[t].execute(e),e.backend===`webgpu`&&!e.joins&&e.settle?.()}finally{this.f=!1}}prepare(e){if(this.f)throw t(`state`,`Graph recursion`,`reentrancy`);this.f=!0;try{for(let t of this.e)t.prepare?.(e)}finally{this.f=!1}}};export{n as FrameGraph};
@@ -17,6 +17,10 @@ export declare function rectangleClear(rect: readonly number[] | undefined, widt
17
17
  * `count`; core still uploads the batch into its own buffer, which stays the source the package reads. A batch with a
18
18
  * redirect is drawn even when core collected no instances for it, so a package can supply all of a batch's instances
19
19
  * and their visibility on the GPU (`DynamicInstances` in @margoengine/culling).
20
+ * `draws`, with a redirect only (default 1): the number of 20-byte argument sets in its `args`, drawn in order, for
21
+ * sub-ranges of one merged geometry (`MultiDraw` in @margoengine/culling/multidraw). `multi` draws them in one
22
+ * `multiDrawIndexedIndirect` call (the WebGPU multi-draw-indirect proposal; set it only when the device has that
23
+ * feature), which core uses in a render pass and not in a bundle.
20
24
  * `claimed`: set by a package that draws these instances itself (core never sets it, and it persists until the package
21
25
  * clears it): core's draws neither bind nor encode the batch and `engine.stats.drawCalls` leaves it out. Pick passes
22
26
  * still draw it. */
@@ -31,6 +35,8 @@ export interface Batch {
31
35
  instances: GPUBuffer;
32
36
  args: GPUBuffer;
33
37
  };
38
+ draws?: number;
39
+ multi?: boolean;
34
40
  claimed?: boolean;
35
41
  }
36
42
  /**
@@ -83,7 +89,10 @@ export interface RenderView {
83
89
  /**
84
90
  * Draw into these textures instead of the canvas; the caller owns them and recreates them after device loss.
85
91
  * `color`: 1 sample, any renderable colour format, RENDER_ATTACHMENT usage; with 4x MSAA core draws into its own 4x
86
- * texture of that format (kept per target size and format) and resolves into it, so edges are antialiased.
92
+ * texture of that format (kept per target size and format) and resolves into it, so edges are antialiased. The
93
+ * texture holds display colour, as the canvas does. An `-srgb` format must name its non-srgb twin in `viewFormats`
94
+ * (`rgba8unorm` for `rgba8unorm-srgb`): core draws through a view in that format, so the colour is encoded once,
95
+ * the texture stores the same bytes as its twin would, and sampling it returns linear light.
87
96
  * `depth` (optional): the size of `color`, in the scene's depth format and sample count (`depth32float-stencil8`
88
97
  * when the device has that feature, else `depth32float`; 4 samples with 4x MSAA, else 1); core draws into it. Without
89
98
  * it core draws into its own depth. Other shapes throw TypeError. Several views may draw into one target: they stack
package/dist/renderer.js CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,r as t,t as n}from"./errors-B6KSysyy.js";import{a as r,i}from"./view-rect-DBHPjboz.js";import{n as a,r as o,t as s}from"./clear-color-jWdkJ0Fa.js";import{sceneSamples as c}from"./quality.js";import{wgsl as l}from"./shaders.js";var u={},d=e=>(e.count||e.redirect)&&!e.claimed;function f(e,n,r,a,o,s){if(!a&&!o)return`none`;if(!i(e,n,r))return`attachment`;if(s)throw t(`Partial-view clear: draw extra attachments with clear: false`,`views`);return`draw`}var p=(e,t,n,r,i,a)=>{r*=24,i=i*24>a?a:i*24,i>r&&e.writeBuffer(t,r*4,n,r,i-r)};function m(e,t,n,r){let{rows:i,instances:a}=n,o=n.count*24;if(r||!i||!(n.dirty>=0))p(e,t,a,0,o,o),i?.fill(0);else if(n.dirty){let n=i.h??=new Uint16Array(i.buffer,i.byteOffset,i.length*2);for(let r=0,i=0,s=0;r<=n.length;r++){let c=n[r];if(r===n.length)p(e,t,a,i,s,o);else if(c)for(n[r]=0;c;){let n=31-Math.clz32(c&-c),l=~(c>>n),u=n+31-Math.clz32(l&-l),d=r*16+n;d!==s&&(p(e,t,a,i,s,o),i=d),s=r*16+u,c=c>>u<<u}}}n.dirty=0}var h=(e,t,{signal:r,startupWarning:i=8e3,startupTimeout:a},o)=>new Promise((s,c)=>{let l=1,u=()=>{clearTimeout(p),clearTimeout(m),r?.removeEventListener(`abort`,f)},d=e=>{l=0,u(),c(e)},f=()=>d(r.reason),p=setTimeout(console.warn,i,`Margo: still waiting for ${t} after ${i/1e3} s; see https://margoengine.com/errors#timeout`),m=setTimeout(d,a??3e4,n(`timeout`,`WebGPU ${t} never settled`));r?.aborted?f():r?.addEventListener(`abort`,f),e.then(e=>{u(),l?s(e):o?.(e)},d)}),g=class i{o;e;x;p;z;f;H;set onLost(e){this.e.lost.then(t=>{this.h||e(this.memory??n(`failed`,`GPU lost: ${t.message}`,`gpu-lost`),!!this.memory)})}get target(){return{format:this.p,depthFormat:this.f.depthStencil.format,samples:this.f.multisample.count}}get gpu(){return this.e}backend=`webgpu`;g=/* @__PURE__ */ new Float32Array(32);v=[];k;l;r=!1;cleared=!1;depthView;keepDepth=!1;u;resolvePass;I=[];B=[];q;D;y=!1;G=/* @__PURE__ */ new Map;w=[];t=0;s;memory;i=!1;j=/* @__PURE__ */ new Map;n=[];E=/* @__PURE__ */ new WeakMap;m;A;C;h=!1;static async create(e,t=[],r=c(),a={},o=!0){let s=navigator.gpu,u=a.powerPreference,d=s&&await h(s.requestAdapter(u?{powerPreference:u}:/Win/.test(navigator.userAgent)?{}:{powerPreference:`high-performance`}),`requestAdapter`,a);if(!d)throw n(`unsupported`,`WebGPU adapter unavailable`,`webgpu`);let f=d.limits,p=await h(d.requestDevice({requiredLimits:{maxTextureArrayLayers:f?.maxTextureArrayLayers,maxBufferSize:f?.maxBufferSize,maxStorageBufferBindingSize:f?.maxStorageBufferBindingSize},requiredFeatures:[`depth32float-stencil8`,...t].filter(e=>d.features.has(e))}),`requestDevice`,a,e=>e.destroy());try{let t=navigator.gpu.getPreferredCanvasFormat(),s=p.createShaderModule({code:l}),c={layout:`auto`,vertex:{module:s,entryPoint:`vertex`,buffers:[{arrayStride:24,attributes:[{shaderLocation:0,offset:0,format:`float32x3`},{shaderLocation:1,offset:12,format:`float32x3`}]},{arrayStride:96,stepMode:`instance`,attributes:Array.from({length:6},(e,t)=>({shaderLocation:t+2,offset:t*16,format:`float32x4`}))}]},fragment:{module:s,entryPoint:`fragment`,targets:[{format:t}]},depthStencil:{format:p.features.has(`depth32float-stencil8`)?`depth32float-stencil8`:`depth32float`,depthWriteEnabled:!0,depthCompare:`greater-equal`},multisample:{count:r}},u=`createRenderPipelineAsync`,d=await h(p.createRenderPipelineAsync(c),u,a),f=await h(p.createRenderPipelineAsync({...c,primitive:{cullMode:`back`},fragment:{...c.fragment,constants:{C:1}}}),u,a),m=e.getContext(`webgpu`);if(!m)throw n(`unsupported`,`No WebGPU canvas`,`webgpu`);let g=new i(e,p,m,t,d,c,f);return o&&g.configure(),g}catch(e){throw p.destroy(),e}}constructor(e,t,r,i,a,o,s){this.o=e,this.e=t,this.x=r,this.p=i,this.z=a,this.f=o,this.H=s,this.m=t.createBuffer({size:128,usage:72}),this.A=t.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}}]}),this.C=t.createBindGroup({layout:s.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}}]}),t.lost.then(()=>this.i=!0),t.addEventListener(`uncapturederror`,({error:e})=>{this.memory||(e instanceof GPUOutOfMemoryError?(this.memory=n(`failed`,`GPU out of memory: ${e.message}`,`gpu-lost`),this.i=!0,t.destroy()):this.s=n(`failed`,e.message,`gpu-lost`))})}configure(){this.x.configure({device:this.e,format:this.p})}add(t,n){let r=[];try{let i=(t,n)=>{if(t.byteLength>this.e.limits.maxBufferSize)throw e(`GPU buffer limit`,`limits`);let i=this.e.createBuffer({size:t.byteLength,usage:n|8});return r.push(i),this.e.queue.writeBuffer(i,0,t),i},a=i(t.vertices,160),o=i(t.indices,144);if(n*96>this.e.limits.maxBufferSize)throw e(`GPU buffer limit`,`limits`);let s=this.e.createBuffer({size:n*96,usage:168});r.push(s),this.remove(t),this.j.set(t,{vertex:a,index:o,instance:s,frame:-1})}catch(e){for(let e of r)e.destroy();throw e}}remove(e){let t=this.j.get(e);t&&(t.vertex.destroy(),t.index.destroy(),t.instance.destroy(),t.indirect?.destroy(),this.j.delete(e))}geometryBuffers(e){let t=this.j.get(e);if(this.h||this.i||!t)throw n(`state`,`Geometry unavailable`,`device-restore`);return t}render(e,t,n,r,i,a){if(!(this.i||this.h))try{this.J(e,t,n,r,i,a)}catch(e){throw this.s=void 0,e}}J(e,n,i,c,p,m){if(this.s)throw this.s;let h=m?.target,{width:g,height:_}=h?.color??this.o,v=h?.color.format??this.p,y=this.F(+!!h,g,_,v),b=this.f.multisample.count,x=h?.depth;if(h&&(h.color.sampleCount>1||x&&(x.width!==g||x.height!==_)))throw t(`Invalid view target: use 1-sample colour`,`views`);if(x&&(x.sampleCount!==b||x.format!==this.f.depthStencil.format))throw t(`Invalid view depth: use the scene depth format and samples, or omit depth`,`views`);this.g.set(e.matrix),this.g.set(e.position,16),this.g.set(n.direction,20);let S=Math.hypot(this.g[20],this.g[21],this.g[22]);for(let e=20;e<23;e++)this.g[e]/=S;this.g.set(n.radiance,24),this.g.fill(1,28,31),n.ambient&&this.g.set(n.ambient,28),this.e.queue.writeBuffer(this.m,0,this.g),this.q?.settle();let C=!!m&&m.index+1!==m.count;this.y=C;let w=this.e.createCommandEncoder();this.t++;let T=this.I;for(let e=0;e<i.length;e++)T[e]=i[e];T.length=i.length,this.l=h?.color.createView()??this.x.getCurrentTexture().createView(),this.k=y.length>1?y[0]:void 0;let E=this.k??this.l,D=x?x.createView():y.at(-1);this.r=(c.revision>0||C)&&!!this.k,this.keepDepth=!!x,this.depthView=D;let O=this.q??={backend:`webgpu`,draw:(e=u)=>{let t=this.q,n=t.view?.viewport,i=e.viewport===void 0?n:e.viewport,c=e.scissor===void 0?e.viewport===void 0?t.view?.scissor??n:void 0:e.scissor;r(i,t.width,t.height),r(c,t.width,t.height);let p=e.pipeline??this.z,m=e.bindings??t.bindings;if(!e.pipeline&&(t.shader!==l||t.format!==this.p||t.descriptor!==this.f)){let e=t.descriptor.multisample?.count+t.format+t.descriptor.depthStencil?.format;p=this.variant(t.shader,e,e=>({...t.descriptor,vertex:{...this.f.vertex,module:e},fragment:{...this.f.fragment,module:e,targets:[{format:t.format}]}}))}let h=this.A;if(p!==this.z||m.length){let e=this.E.get(p),t=!e||e.bindings.length!==m.length;for(let n=0;!t&&n<m.length;n++){let r=m[n],i=e.bindings[n],a=r.resource,o=i.resource;t=r.binding!==i.binding||(a.buffer?a.buffer!==o.buffer||a.offset!==o.offset||a.size!==o.size:a!==o)}if(t||!e){let t=this.e.createBindGroup({layout:p.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}},...m]});e={bindings:m.map(({binding:e,resource:t})=>({binding:e,resource:t.buffer?{...t}:t})),group:t},this.E.set(p,e)}h=e.group}let g=t.view?.clear?.color,_=typeof g==`string`,v=e.clear??(g===!1?!1:_||!t.view?.index),y=e.clearDepth??t.view?.clear?.depth??e.clear??!0,b=s(_?g:void 0,t.color!==this.k&&t.color!==this.l&&t.format),x=f(t.view?i??c:void 0,t.width,t.height,!!v,!!y,e.colorAttachments?.length??0),S=this.u??={colorAttachments:[{view:t.color,clearValue:o,loadOp:`clear`,storeOp:`store`}],depthStencilAttachment:{view:t.depth,depthClearValue:0,depthLoadOp:`clear`,depthStoreOp:`store`}},C=S.colorAttachments,w=C[0],E=S.depthStencilAttachment;w.view=t.color,w.loadOp=x===`attachment`&&v?`clear`:`load`,x===`attachment`&&v&&(w.clearValue=b),E.view=t.depth,E.depthLoadOp=x===`attachment`&&y?`clear`:`load`,w.resolveTarget=t.color===this.k&&!this.r?this.l:void 0,w.storeOp=w.resolveTarget?`discard`:`store`,E.depthStoreOp=this.keepDepth?`store`:w.storeOp,C.length=1,e.colorAttachments&&C.push(...e.colorAttachments);let D=t.descriptor.depthStencil.format.includes(`stencil`);if(E.stencilClearValue=D?e.stencilClear??0:void 0,E.stencilLoadOp=D?x===`draw`?`load`:v||e.stencilClear!==void 0?`clear`:`load`:void 0,E.stencilStoreOp=D?E.depthStoreOp:void 0,t.only&&t.draw===this.D){if(t.joins&&x===`attachment`&&!T.some(d)){this.cleared=!0;return}t.attach(w,E,!0)}let O=t.encoder.beginRenderPass(S);i&&O.setViewport(...i,0,1),c&&O.setScissorRect(...c),x===`draw`&&a(this.e,this.G,O,{formats:[t.format],depthFormat:t.descriptor.depthStencil.format,writeDepth:!!y,samples:t.descriptor.multisample?.count,writeColor:!!v,tint:b});let k;for(let n=0;n<T.length;n++){let r=T[n];if(d(r)){let n=p===this.z&&!m.length&&!r.mask?this.H:p;n!==k&&(k=n,O.setPipeline(n),O.setBindGroup(0,n===p?h:this.C));let i=this.j.get(r.geometry);i.frame!==this.t&&this.upload(r,i,this.t);let a=r.redirect;O.setVertexBuffer(0,i.vertex),O.setVertexBuffer(1,a?.instances??i.instance),O.setIndexBuffer(i.index,`uint32`),a?O.drawIndexedIndirect(a.args,0):e.indirect??t.indirect?(i.indirect??=this.e.createBuffer({size:20,usage:264}),i.command??=new Uint32Array([r.geometry.indices.length,0,0,0,0]),i.command[1]!==r.count&&(i.command[1]=r.count,this.e.queue.writeBuffer(i.indirect,0,i.command)),O.drawIndexedIndirect(i.indirect,0)):O.drawIndexed(r.geometry.indices.length,r.count)}}O.end()},attach:(e,t,n)=>{if(this.cleared){let n=this.u.colorAttachments[0],r=this.u.depthStencilAttachment;this.cleared=!1,e.loadOp=n.loadOp,e.clearValue=n.clearValue,t.depthLoadOp=r.depthLoadOp,t.depthClearValue=r.depthClearValue,r.stencilLoadOp&&(t.stencilReadOnly=void 0,t.stencilLoadOp=r.stencilLoadOp,t.stencilClearValue=r.stencilClearValue,t.stencilStoreOp=`store`)}n&&this.q.last&&this.r&&!this.y&&e.view===this.k&&t.view===this.depthView&&(e.resolveTarget=this.l,e.storeOp=`discard`,t.depthStoreOp=this.keepDepth?`store`:`discard`,t.stencilStoreOp&&=t.depthStoreOp,this.r=!1)},settle:()=>{this.cleared&&(this.cleared=!1,this.q.encoder.beginRenderPass(this.u).end())}};for(O.batches=T,O.draw=this.D??=O.draw,O.descriptor=this.f,O.device=this.e,O.encoder=w,O.color=E,O.depth=D,O.camera=e,O.view=m&&{id:m.id,camera:e,viewport:m.rect,scissor:m.scissor,index:m.index,count:m.count,clear:m.clear,layers:m.layers,target:m.target},O.width=g,O.height=_,O.delta=p,O.format=v,O.shader=l,O.bindings=this.w,O.indirect=!1;this.w.length;)this.w.pop();if(c.execute(O),!this.i&&!this.h){if(this.r&&!this.y){let e=this.resolvePass??={colorAttachments:[{view:E,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:D,depthLoadOp:`load`,stencilReadOnly:!0}},t=e.colorAttachments[0];t.view=E,t.resolveTarget=this.l,t.storeOp=C?`store`:`discard`,e.depthStencilAttachment.view=D,e.depthStencilAttachment.depthStoreOp=C||x?`store`:`discard`,w.beginRenderPass(e).end()}this.B[0]=w.finish(),this.e.queue.submit(this.B)}}F(e,t,n,r){let i=this.v[e];if(!i||i.width!==t||i.height!==n||i.format!==r){for(let e of i?.textures??[])e.destroy();i=this.v[e]={width:t,height:n,format:r,textures:[],views:[]};for(let e of[r,this.f.depthStencil.format].slice(this.f.multisample.count===4?0:1)){let r=this.e.createTexture({size:[t,n],sampleCount:this.f.multisample.count,format:e,usage:16});i.textures.push(r),i.views.push(r.createView())}}return i.views}upload(e,t,n){m(this.e.queue,t.instance,e,t.frame<0),t.frame=n}variant(t,n,r){for(let e=0;e<this.n.length;e++)if(this.n[e][0]===t&&this.n[e][1]===n)return this.n[e][2];if(this.n.length>=64)throw e(`Shader limit: 64`,`limits`);let i=this.e.createRenderPipeline(r(this.e.createShaderModule({code:t})));return this.n.push([t,n,i]),i}async pick(e,t,n,r,i,a,o){if(this.i||this.h)return null;let s,c,u,d;try{let f=this.e;s=f.createTexture({size:[1,1],format:`r32uint`,usage:17}),c=f.createTexture({size:[1,1],format:`depth32float`,usage:16}),u=f.createBuffer({size:4,usage:9});let p=e.matrix.slice(),m=o?.[0]??this.o.width,h=o?.[1]??this.o.height,g=2*(Math.floor(i)+.5)/m-1,_=1-2*(Math.floor(a)+.5)/h;for(let t=0;t<4;t++)p[t*4]=(e.matrix[t*4]-g*e.matrix[t*4+3])*m,p[t*4+1]=(e.matrix[t*4+1]-_*e.matrix[t*4+3])*h;let v=/* @__PURE__ */ new Float32Array(32);v.set(p),v.set(e.position,16),v.set(t.direction,20),v.set(t.radiance,24),v.fill(1,28,31),t.ambient&&v.set(t.ambient,28),d=f.createBuffer({size:128,usage:72}),f.queue.writeBuffer(d,0,v);let y=f.createCommandEncoder(),b={backend:`webgpu`,device:f,encoder:y,color:s.createView(),depth:c.createView(),camera:e,width:this.o.width,height:this.o.height,delta:0,format:this.p,shader:l,bindings:[],indirect:!1,descriptor:this.f,draw:()=>{}};r.prepare(b);let x=b.shader.replace(`@location(3) material:vec4f`,`@location(3) material:vec4f,@location(4) @interpolate(flat) id:u32`).replace(`o.color=i.color.rgb`,`o.id=u32(i.factors.w)+1u;o.color=i.color.rgb`).replace(`->@location(0) vec4f {`,`->@location(0) u32 {`).replace(/let n=normalize\(i.normal\)[\s\S]*$/,`return i.id;
2
- }`),S=this.variant(x,``,e=>({...this.f,multisample:{count:1},vertex:{...this.f.vertex,module:e},fragment:{module:e,entryPoint:`fragment`,targets:[{format:`r32uint`}]},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`greater-equal`}})),C=f.createBindGroup({layout:S.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:d}},...b.bindings]}),w=y.beginRenderPass({colorAttachments:[{view:s.createView(),clearValue:[0,0,0,0],loadOp:`clear`,storeOp:`store`}],depthStencilAttachment:{view:c.createView(),depthClearValue:0,depthLoadOp:`clear`,depthStoreOp:`store`}});w.setPipeline(S),w.setBindGroup(0,C);for(let e of n)if(e.count){let t=this.j.get(e.geometry);this.upload(e,t,this.t-1),w.setVertexBuffer(0,t.vertex),w.setVertexBuffer(1,t.instance),w.setIndexBuffer(t.index,`uint32`),w.drawIndexed(e.geometry.indices.length,e.count)}if(w.end(),this.i||this.h||(y.copyTextureToBuffer({texture:s},{buffer:u},[1,1]),f.queue.submit([y.finish()]),!await u.mapAsync(1).then(()=>1,e=>{if(this.i||this.h)return 0;throw e})))return null;let T=new Uint32Array(u.getMappedRange())[0];return u.unmap(),T===0?null:T-1}finally{d?.destroy(),s?.destroy(),c?.destroy(),u?.destroy()}}dispose(e=!0){if(!this.h){this.h=!0;for(let e of this.j.keys())this.remove(e);for(let e of this.v)for(let t of e?.textures??[])t.destroy();this.m.destroy(),e&&this.x.unconfigure(),this.e.destroy()}}};export{g as GPURenderer,f as rectangleClear,m as uploadRows};
1
+ import{i as e,r as t,t as n}from"./errors-D0VAEAiW.js";import{a as r,i}from"./view-rect-DJ1fxok2.js";import{n as a,r as o,t as s}from"./clear-color-ziMPCpSz.js";import{sceneSamples as c}from"./quality.js";import{wgsl as l}from"./shaders.js";var u={},d=e=>(e.count||e.redirect)&&!e.claimed;function f(t,n,r,a,o,s){if(!a&&!o)return`none`;if(!i(t,n,r))return`attachment`;if(s)throw e(`Partial-view clear: draw extra attachments with clear: false`,`views`);return`draw`}var p=(e,t,n,r,i,a)=>{r*=24,i=i*24>a?a:i*24,i>r&&e.writeBuffer(t,r*4,n,r,i-r)};function m(e,t,n,r){let{rows:i,instances:a}=n,o=n.count*24;if(r||!i||!(n.dirty>=0))p(e,t,a,0,o,o),i?.fill(0);else if(n.dirty){let n=i.h??=new Uint16Array(i.buffer,i.byteOffset,i.length*2);for(let r=0,i=0,s=0;r<=n.length;r++){let c=n[r];if(r===n.length)p(e,t,a,i,s,o);else if(c)for(n[r]=0;c;){let n=31-Math.clz32(c&-c),l=~(c>>n),u=n+31-Math.clz32(l&-l),d=r*16+n;d!==s&&(p(e,t,a,i,s,o),i=d),s=r*16+u,c=c>>u<<u}}}n.dirty=0}var h=(e,t,{signal:r,startupWarning:i=8e3,startupTimeout:a},o)=>new Promise((s,c)=>{let l=1,u=()=>{clearTimeout(p),clearTimeout(m),r?.removeEventListener(`abort`,f)},d=e=>{l=0,u(),c(e)},f=()=>d(r.reason),p=setTimeout(console.warn,i,`Margo: still waiting for ${t} after ${i/1e3} s; see https://margoengine.com/errors#timeout`),m=setTimeout(d,a??3e4,n(`timeout`,`WebGPU ${t} never settled`));r?.aborted?f():r?.addEventListener(`abort`,f),e.then(e=>{u(),l?s(e):o?.(e)},d)}),g=class i{o;e;x;q;z;f;H;set onLost(e){this.e.lost.then(t=>{this.i||e(this.memory??n(`failed`,`GPU lost: ${t.message}`,`gpu-lost`),!!this.memory)})}get target(){return{format:this.q,depthFormat:this.f.depthStencil.format,samples:this.f.multisample.count}}get gpu(){return this.e}backend=`webgpu`;g=/* @__PURE__ */ new Float32Array(32);v=[];k;l;s=!1;cleared=!1;depthView;keepDepth=!1;u;resolvePass;I=[];B=[];r;D;y=!1;G=/* @__PURE__ */ new Map;w=[];t=0;p;memory;h=!1;j=/* @__PURE__ */ new Map;n=[];E=/* @__PURE__ */ new WeakMap;m;A;C;i=!1;static async create(e,t=[],r=c(),a={},o=!0){let s=navigator.gpu,u=a.powerPreference,d=s&&await h(s.requestAdapter(u?{powerPreference:u}:/Win/.test(navigator.userAgent)?{}:{powerPreference:`high-performance`}),`requestAdapter`,a);if(!d)throw n(`unsupported`,`WebGPU adapter unavailable`,`webgpu`);let f=d.limits,p=await h(d.requestDevice({requiredLimits:{maxTextureArrayLayers:f?.maxTextureArrayLayers,maxBufferSize:f?.maxBufferSize,maxStorageBufferBindingSize:f?.maxStorageBufferBindingSize},requiredFeatures:[`depth32float-stencil8`,...t].filter(e=>d.features.has(e))}),`requestDevice`,a,e=>e.destroy());try{let t=navigator.gpu.getPreferredCanvasFormat(),s=p.createShaderModule({code:l}),c={layout:`auto`,vertex:{module:s,entryPoint:`vertex`,buffers:[{arrayStride:24,attributes:[{shaderLocation:0,offset:0,format:`float32x3`},{shaderLocation:1,offset:12,format:`float32x3`}]},{arrayStride:96,stepMode:`instance`,attributes:Array.from({length:6},(e,t)=>({shaderLocation:t+2,offset:t*16,format:`float32x4`}))}]},fragment:{module:s,entryPoint:`fragment`,targets:[{format:t}]},depthStencil:{format:p.features.has(`depth32float-stencil8`)?`depth32float-stencil8`:`depth32float`,depthWriteEnabled:!0,depthCompare:`greater-equal`},multisample:{count:r}},u=`createRenderPipelineAsync`,d=await h(p.createRenderPipelineAsync(c),u,a),f=await h(p.createRenderPipelineAsync({...c,primitive:{cullMode:`back`},fragment:{...c.fragment,constants:{C:1}}}),u,a),m=e.getContext(`webgpu`);if(!m)throw n(`unsupported`,`No WebGPU canvas`,`webgpu`);let g=new i(e,p,m,t,d,c,f);return o&&g.configure(),g}catch(e){throw p.destroy(),e}}constructor(e,t,r,i,a,o,s){this.o=e,this.e=t,this.x=r,this.q=i,this.z=a,this.f=o,this.H=s,this.m=t.createBuffer({size:128,usage:72}),this.A=t.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}}]}),this.C=t.createBindGroup({layout:s.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}}]}),t.lost.then(()=>this.h=!0);let c=t.destroy.bind(t);t.destroy=()=>{this.h=!0,c()},t.addEventListener(`uncapturederror`,({error:e})=>{this.memory||(e instanceof GPUOutOfMemoryError?(this.memory=n(`failed`,`GPU out of memory: ${e.message}`,`gpu-lost`),this.h=!0,t.destroy()):this.p??=n(`failed`,e.message,`gpu-lost`))})}configure(){this.x.configure({device:this.e,format:this.q})}add(e,n){let r=[];try{let i=(e,n)=>{if(e.byteLength>this.e.limits.maxBufferSize)throw t(`GPU buffer limit`,`limits`);let i=this.e.createBuffer({size:e.byteLength,usage:n|8});return r.push(i),this.e.queue.writeBuffer(i,0,e),i},a=i(e.vertices,160),o=i(e.indices,144);if(n*96>this.e.limits.maxBufferSize)throw t(`GPU buffer limit`,`limits`);let s=this.e.createBuffer({size:n*96,usage:168});r.push(s),this.remove(e),this.j.set(e,{vertex:a,index:o,instance:s,frame:-1})}catch(e){for(let e of r)e.destroy();throw e}}remove(e){let t=this.j.get(e);t&&(t.vertex.destroy(),t.index.destroy(),t.instance.destroy(),t.indirect?.destroy(),this.j.delete(e))}geometryBuffers(e){let t=this.j.get(e);if(this.i||this.h||!t)throw n(`state`,`Geometry unavailable`,`device-restore`);return t}render(e,t,n,r,i,a){if(!(this.h||this.i))try{this.J(e,t,n,r,i,a)}catch(e){throw this.p=void 0,e}}J(t,n,i,c,p,m){if(this.p)throw this.p;let h=m?.target,{width:g,height:_}=h?.color??this.o,v=h?.color.format.replace(`-srgb`,``)??this.q,y=this.F(+!!h,g,_,v),b=this.f.multisample.count,x=h?.depth;if(h&&(h.color.sampleCount>1||x&&(x.width!==g||x.height!==_)))throw e(`Invalid view target: use 1-sample colour`,`views`);if(x&&(x.sampleCount!==b||x.format!==this.f.depthStencil.format))throw e(`Invalid view depth: use the scene depth format and samples, or omit depth`,`views`);this.g.set(t.matrix),this.g.set(t.position,16),this.g.set(n.direction,20);let S=Math.hypot(this.g[20],this.g[21],this.g[22]);for(let e=20;e<23;e++)this.g[e]/=S;this.g.set(n.radiance,24),this.g.fill(1,28,31),n.ambient&&this.g.set(n.ambient,28),this.e.queue.writeBuffer(this.m,0,this.g),this.r?.settle();let C=!!m&&m.index+1!==m.count;this.y=C;let w=this.e.createCommandEncoder();this.t++;let T=this.I;for(let e=0;e<i.length;e++)T[e]=i[e];T.length=i.length;let E=h&&h.color.format!==v;E&&this.e.pushErrorScope(`validation`),this.l=h?.color.createView({format:v})??this.x.getCurrentTexture().createView(),E&&this.e.popErrorScope().then(t=>{t&&(this.p=e(`Invalid view target: add viewFormats ['${v}']`,`views`))}),this.k=y.length>1?y[0]:void 0;let D=this.k??this.l,O=x?x.createView():y.at(-1);this.s=(c.revision>0||C)&&!!this.k,this.keepDepth=!!x,this.depthView=O;let k=this.r??={backend:`webgpu`,draw:(e=u)=>{let t=this.r,n=e.colorAttachments?void 0:e.snapshot??t.snapshot;t.snapshot=void 0;let i=t.view?.viewport,c=e.viewport===void 0?i:e.viewport,p=e.scissor===void 0?e.viewport===void 0?t.view?.scissor??i:void 0:e.scissor;r(c,t.width,t.height),r(p,t.width,t.height);let m=e.pipeline??this.z,h=e.bindings??t.bindings;if(!e.pipeline&&(t.shader!==l||t.format!==this.q||t.descriptor!==this.f)){let e=t.descriptor.multisample?.count+t.format+t.descriptor.depthStencil?.format;m=this.variant(t.shader,e,e=>({...t.descriptor,vertex:{...this.f.vertex,module:e},fragment:{...this.f.fragment,module:e,targets:[{format:t.format}]}}))}let g=this.A;if(m!==this.z||h.length){let e=this.E.get(m),t=!e||e.bindings.length!==h.length;for(let n=0;!t&&n<h.length;n++){let r=h[n],i=e.bindings[n],a=r.resource,o=i.resource;t=r.binding!==i.binding||(a.buffer?a.buffer!==o.buffer||a.offset!==o.offset||a.size!==o.size:a!==o)}if(t||!e){let t=this.e.createBindGroup({layout:m.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.m}},...h]});e={bindings:h.map(({binding:e,resource:t})=>({binding:e,resource:t.buffer?{...t}:t})),group:t},this.E.set(m,e)}g=e.group}let _=t.view?.clear?.color,v=e.clear??(_===!1?!1:typeof _==`string`||!t.view?.index),y=e.clearDepth??t.view?.clear?.depth??e.clear??!0,b=s(_,t.color!==this.k&&t.color!==this.l&&t.format),x=f(t.view?c??p:void 0,t.width,t.height,!!v,!!y,e.colorAttachments?.length??0),S=this.u??={colorAttachments:[{view:t.color,clearValue:o,loadOp:`clear`,storeOp:`store`}],depthStencilAttachment:{view:t.depth,depthClearValue:0,depthLoadOp:`clear`,depthStoreOp:`store`}},C=S.colorAttachments,w=C[0],E=S.depthStencilAttachment;w.view=t.color,w.loadOp=x===`attachment`&&v?`clear`:`load`,x===`attachment`&&v&&(w.clearValue=b),E.view=t.depth,E.depthLoadOp=x===`attachment`&&y?`clear`:`load`,w.resolveTarget=t.color===this.k&&!this.s?this.l:void 0,w.storeOp=w.resolveTarget?`discard`:`store`,E.depthStoreOp=this.keepDepth?`store`:w.storeOp,C.length=1,e.colorAttachments&&C.push(...e.colorAttachments);let D=t.descriptor.depthStencil.format.includes(`stencil`);if(E.stencilClearValue=D?e.stencilClear??0:void 0,E.stencilLoadOp=D?x===`draw`?`load`:v||e.stencilClear!==void 0?`clear`:`load`:void 0,E.stencilStoreOp=D?E.depthStoreOp:void 0,t.only&&t.draw===this.D){if(t.joins&&x===`attachment`&&!T.some(d)){this.cleared=!0;return}t.attach(w,E,!0)}let O=t.encoder.beginRenderPass(S);c&&O.setViewport(...c,0,1),p&&O.setScissorRect(...p),x===`draw`&&a(this.e,this.G,O,{formats:[t.format],depthFormat:t.descriptor.depthStencil.format,writeDepth:!!y,samples:t.descriptor.multisample?.count,writeColor:!!v,tint:b});let k,A=n?.bundle&&n.group===g,j=n&&!A?this.e.createRenderBundleEncoder({colorFormats:[t.format],depthStencilFormat:t.descriptor.depthStencil.format,sampleCount:t.descriptor.multisample?.count}):O;for(let n=0;n<T.length;n++){let r=T[n];if(d(r)){let n=m===this.z&&!h.length&&!r.mask?this.H:m,i=this.j.get(r.geometry);i.frame!==this.t&&this.upload(r,i,this.t);let a=r.redirect?.args;if(!a&&(e.indirect??t.indirect)&&(a=i.indirect??=this.e.createBuffer({size:20,usage:264}),i.command??=new Uint32Array([r.geometry.indices.length,0,0,0,0]),i.command[1]!==r.count&&(i.command[1]=r.count,this.e.queue.writeBuffer(a,0,i.command))),!A){n!==k&&(k=n,j.setPipeline(n),j.setBindGroup(0,n===m?g:this.C)),j.setVertexBuffer(0,i.vertex),j.setVertexBuffer(1,r.redirect?.instances??i.instance),j.setIndexBuffer(i.index,`uint32`);let e=r.redirect&&r.draws||1;if(!a)j.drawIndexed(r.geometry.indices.length,r.count);else if(r.redirect&&r.multi&&j===O)O.multiDrawIndexedIndirect(a,0,e);else for(let t=0;t<e;t++)j.drawIndexedIndirect(a,t*20)}}}n&&(A||(n.bundle=j.finish(),n.group=g),O.executeBundles([n.bundle])),O.end()},attach:(e,t,n)=>{if(this.cleared){let n=this.u.colorAttachments[0],r=this.u.depthStencilAttachment;this.cleared=!1,e.loadOp=n.loadOp,e.clearValue=n.clearValue,t.depthLoadOp=r.depthLoadOp,t.depthClearValue=r.depthClearValue,r.stencilLoadOp&&(t.stencilReadOnly=void 0,t.stencilLoadOp=r.stencilLoadOp,t.stencilClearValue=r.stencilClearValue,t.stencilStoreOp=`store`)}n&&this.r.last&&this.s&&!this.y&&e.view===this.k&&t.view===this.depthView&&(e.resolveTarget=this.l,e.storeOp=`discard`,t.depthStoreOp=this.keepDepth?`store`:`discard`,t.stencilStoreOp&&=t.depthStoreOp,this.s=!1)},settle:()=>{this.cleared&&(this.cleared=!1,this.r.encoder.beginRenderPass(this.u).end())}};for(k.batches=T,k.draw=this.D??=k.draw,k.descriptor=this.f,k.device=this.e,k.encoder=w,k.color=D,k.depth=O,k.camera=t,k.view=m&&{id:m.id,camera:t,viewport:m.rect,scissor:m.scissor,index:m.index,count:m.count,clear:m.clear,layers:m.layers,target:m.target},k.width=g,k.height=_,k.delta=p,k.format=v,k.shader=l,k.bindings=this.w,k.indirect=!1;this.w.length;)this.w.pop();if(c.execute(k),!this.h&&!this.i){if(this.s&&!this.y){let e=this.resolvePass??={colorAttachments:[{view:D,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:O,depthLoadOp:`load`,stencilReadOnly:!0}},t=e.colorAttachments[0];t.view=D,t.resolveTarget=this.l,t.storeOp=C?`store`:`discard`,e.depthStencilAttachment.view=O,e.depthStencilAttachment.depthStoreOp=C||x?`store`:`discard`,w.beginRenderPass(e).end()}this.B[0]=w.finish(),this.e.queue.submit(this.B)}}F(e,t,n,r){let i=this.v[e];if(!i||i.width!==t||i.height!==n||i.format!==r){for(let e of i?.textures??[])e.destroy();i=this.v[e]={width:t,height:n,format:r,textures:[],views:[]};for(let e of[r,this.f.depthStencil.format].slice(this.f.multisample.count===4?0:1)){let r=this.e.createTexture({size:[t,n],sampleCount:this.f.multisample.count,format:e,usage:16});i.textures.push(r),i.views.push(r.createView())}}return i.views}upload(e,t,n){m(this.e.queue,t.instance,e,t.frame<0),t.frame=n}variant(e,n,r){for(let t=0;t<this.n.length;t++)if(this.n[t][0]===e&&this.n[t][1]===n)return this.n[t][2];if(this.n.length>=64)throw t(`Shader limit: 64`,`limits`);let i=this.e.createRenderPipeline(r(this.e.createShaderModule({code:e})));return this.n.push([e,n,i]),i}async pick(e,t,n,r,i,a,o){if(this.h||this.i)return null;let s,c,u,d;try{let f=this.e;s=f.createTexture({size:[1,1],format:`r32uint`,usage:17}),c=f.createTexture({size:[1,1],format:`depth32float`,usage:16}),u=f.createBuffer({size:4,usage:9});let p=e.matrix.slice(),m=o?.[0]??this.o.width,h=o?.[1]??this.o.height,g=2*(Math.floor(i)+.5)/m-1,_=1-2*(Math.floor(a)+.5)/h;for(let t=0;t<4;t++)p[t*4]=(e.matrix[t*4]-g*e.matrix[t*4+3])*m,p[t*4+1]=(e.matrix[t*4+1]-_*e.matrix[t*4+3])*h;let v=/* @__PURE__ */ new Float32Array(32);v.set(p),v.set(e.position,16),v.set(t.direction,20),v.set(t.radiance,24),v.fill(1,28,31),t.ambient&&v.set(t.ambient,28),d=f.createBuffer({size:128,usage:72}),f.queue.writeBuffer(d,0,v);let y=f.createCommandEncoder(),b={backend:`webgpu`,device:f,encoder:y,color:s.createView(),depth:c.createView(),camera:e,width:this.o.width,height:this.o.height,delta:0,format:this.q,shader:l,bindings:[],indirect:!1,descriptor:this.f,draw:()=>{}};r.prepare(b);let x=b.shader.replace(`@location(3) material:vec4f`,`@location(3) material:vec4f,@location(4) @interpolate(flat) id:u32`).replace(`o.color=i.color.rgb`,`o.id=u32(i.factors.w)+1u;o.color=i.color.rgb`).replace(`->@location(0) vec4f {`,`->@location(0) u32 {`).replace(/let n=normalize\(i.normal\)[\s\S]*$/,`return i.id;
2
+ }`),S=this.variant(x,``,e=>({...this.f,multisample:{count:1},vertex:{...this.f.vertex,module:e},fragment:{module:e,entryPoint:`fragment`,targets:[{format:`r32uint`}]},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`greater-equal`}})),C=f.createBindGroup({layout:S.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:d}},...b.bindings]}),w=y.beginRenderPass({colorAttachments:[{view:s.createView(),clearValue:[0,0,0,0],loadOp:`clear`,storeOp:`store`}],depthStencilAttachment:{view:c.createView(),depthClearValue:0,depthLoadOp:`clear`,depthStoreOp:`store`}});w.setPipeline(S),w.setBindGroup(0,C);for(let e of n)if(e.count){let t=this.j.get(e.geometry);this.upload(e,t,this.t-1),w.setVertexBuffer(0,t.vertex),w.setVertexBuffer(1,t.instance),w.setIndexBuffer(t.index,`uint32`),w.drawIndexed(e.geometry.indices.length,e.count)}if(w.end(),this.h||this.i||(y.copyTextureToBuffer({texture:s},{buffer:u},[1,1]),f.queue.submit([y.finish()]),!await u.mapAsync(1).then(()=>1,e=>{if(this.h||this.i)return 0;throw e})))return null;let T=new Uint32Array(u.getMappedRange())[0];return u.unmap(),T===0?null:T-1}finally{d?.destroy(),s?.destroy(),c?.destroy(),u?.destroy()}}dispose(e=!0){if(!this.i){this.i=!0;for(let e of this.j.keys())this.remove(e);for(let e of this.v)for(let t of e?.textures??[])t.destroy();this.m.destroy(),e&&this.x.unconfigure(),this.e.destroy()}}};export{g as GPURenderer,f as rectangleClear,m as uploadRows};
@@ -0,0 +1,16 @@
1
+ /** `@margoengine/math`'s MargoErrorCode, repeated here because shared code cannot import the package. */
2
+ export type MargoErrorCode = 'disposed' | 'attached' | 'state' | 'unsupported' | 'failed' | 'timeout' | 'version';
3
+ /** An Error named `MargoError` with `code`: what `new MargoError(code, message)` builds, without the class. */
4
+ export function margoError(code: MargoErrorCode, message: string): Error & { code: MargoErrorCode };
5
+ /** `margoError` whose message links to `anchor` (default the code) on margoengine.com/errors. */
6
+ export function fault(code: MargoErrorCode, message: string, anchor?: string): Error & { code: MargoErrorCode };
7
+ /** TypeError whose message links to `anchor` on margoengine.com/errors. */
8
+ export function typeError(message: string, anchor: string): TypeError;
9
+ /** RangeError whose message links to `anchor` on margoengine.com/errors. */
10
+ export function rangeError(message: string, anchor: string): RangeError;
11
+
12
+ /** Throws a TypeError with code `transform` and the retained-vector help message. */
13
+ export function vectorAssignment(): never;
14
+
15
+ /** Coded error with CSP help for policy-blocked Wasm initialization; other errors pass through. */
16
+ export function wasmError(error: unknown): unknown;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `Math.hypot` of the first `count` (2 to 4) of a, b, c, d, by V8's own steps, so V8 gets the same bits, without
3
+ * allocating. The values must not be NaN.
4
+ */
5
+ export function hypot(count: number, a: number, b: number, c?: number, d?: number): number;
6
+ /** Terms (0 to 3) and result (4) of {@link hypotOf}. */
7
+ export const hypotTerms: Float64Array;
8
+ /**
9
+ * {@link hypot} of `hypotTerms[0]` to `hypotTerms[count - 1]` into `hypotTerms[4]` (the terms become their magnitudes).
10
+ * For hot paths where V8 would box hypot's arguments and result into heap numbers.
11
+ */
12
+ export function hypotOf(count: number): void;
package/dist/version.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Exact core version. The build checks this against the package manifest. */
2
- export declare const CORE_VERSION = "0.1.0";
2
+ export declare const CORE_VERSION = "1.0.0";
3
3
  /** A package's build requirement and the core module it actually resolved. */
4
4
  export interface CoreRequirement {
5
5
  readonly version: string;
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./errors-B6KSysyy.js";var t=`0.1.0`,n={version:t,source:import.meta.url};function r(e=t,r=import.meta.url){return{version:e,source:r,runtime:n}}function i(t,n=r()){let i=t?.coreRequirement?.runtime;if(i&&(i.version!==n.version||i.version!==n.runtime.version||i!==n.runtime))throw e(`version`,`core ${i.version} ${i.source}; ${n.source} needs ${n.version}, got ${n.runtime.version} ${n.runtime.source}`);return t}export{t as CORE_VERSION,i as assertCore,r as coreRequirement};
1
+ import{t as e}from"./errors-D0VAEAiW.js";var t=`1.0.0`,n={version:t,source:import.meta.url};function r(e=t,r=import.meta.url){return{version:e,source:r,runtime:n}}function i(t,n=r()){let i=t?.coreRequirement?.runtime;if(i&&(i.version!==n.version||i.version!==n.runtime.version||i!==n.runtime))throw e(`version`,`core ${i.version} ${i.source}; ${n.source} needs ${n.version}, got ${n.runtime.version} ${n.runtime.source}`);return t}export{t as CORE_VERSION,i as assertCore,r as coreRequirement};
@@ -1 +1 @@
1
- import{n as e}from"./errors-B6KSysyy.js";function t(){return globalThis[Symbol.for(`margoengine.layers`)]}function n(e){return t()?.maskOf(e)??1}var r=(e,t,n)=>!!e&&(e[0]!==0||e[1]!==0||e[2]!==t||e[3]!==n);function i(t,n,r){if(t!==void 0){if(!Array.isArray(t)||t.length!==4)throw e(`Invalid draw rectangle`,`views`);for(let n=0;n<4;n++)if(!Number.isSafeInteger(t[n])||t[n]<(n<2?0:1))throw e(`Invalid draw rectangle`,`views`);if(t[0]+t[2]>n||t[1]+t[3]>r)throw e(`Draw rectangle exceeds target`,`views`)}}function a(e,t){if(!Number.isInteger(e)||e<0||e>4294967295)throw RangeError(`${t} ${e} is not a 32-bit layer mask; pass an integer from 0 to 0xffffffff`);return e>>>0}export{i as a,r as i,t as n,n as r,a as t};
1
+ import{r as e}from"./errors-D0VAEAiW.js";function t(){return globalThis[Symbol.for(`margoengine.layers`)]}function n(e){return t()?.maskOf(e)??1}var r=(e,t,n)=>!!e&&(e[0]!==0||e[1]!==0||e[2]!==t||e[3]!==n);function i(t,n,r){if(t!==void 0){if(!Array.isArray(t)||t.length!==4)throw e(`Invalid draw rectangle`,`views`);for(let n=0;n<4;n++)if(!Number.isSafeInteger(t[n])||t[n]<(n<2?0:1))throw e(`Invalid draw rectangle`,`views`);if(t[0]+t[2]>n||t[1]+t[3]>r)throw e(`Draw rectangle exceeds target`,`views`)}}function a(e,t){if(!Number.isInteger(e)||e<0||e>4294967295)throw RangeError(`${t} ${e} is not a 32-bit layer mask; pass an integer from 0 to 0xffffffff`);return e>>>0}export{i as a,r as i,t as n,n as r,a as t};
package/package.json CHANGED
@@ -1,48 +1,48 @@
1
- {
2
- "name": "@margoengine/core",
3
- "version": "0.1.0",
4
- "description": "WebGPU rendering and a Wasm transform kernel. WebGL2 is the optional @margoengine/webgl2-compat package.",
5
- "keywords": [
6
- "margoengine",
7
- "webgpu",
8
- "3d",
9
- "wasm",
10
- "rust",
11
- "renderer"
12
- ],
13
- "homepage": "https://margoengine.com",
14
- "bugs": {
15
- "url": "https://github.com/scottcampbelldata/margoengine/issues"
16
- },
17
- "repository": {
18
- "type": "git",
19
- "url": "git+https://github.com/scottcampbelldata/margoengine.git",
20
- "directory": "packages/core"
21
- },
22
- "license": "Apache-2.0",
23
- "author": "Scott Campbell",
24
- "type": "module",
25
- "publishConfig": {
26
- "access": "public"
27
- },
28
- "scripts": {
29
- "test": "node --test tests/*.test.js ../../tests/modern.test.js ../../tests/deep-core*.test.js ../../tests/modern-frame-timing.test.js ../../tests/modern-msaa.test.js ../../tests/modern-quaternion.test.js ../../tests/modern-resolution.test.js",
30
- "test:gpu": "node tests/empty.browser.mjs && node tests/scale.browser.mjs && node tests/zero-scale.browser.mjs && node tests/ggx-precision.browser.mjs && node tests/depth-equal.browser.mjs && node tests/exact-antialias.browser.mjs && cd ../.. && node packages/core/tests/pick-clear.browser.mjs",
31
- "prepack": "npm --prefix ../.. run build:packages"
32
- },
33
- "sideEffects": false,
34
- "exports": {
35
- ".": {
36
- "types": "./dist/index.d.ts",
37
- "import": "./dist/index.js"
38
- },
39
- "./extension": {
40
- "types": "./dist/extension.d.ts",
41
- "import": "./dist/extension.js"
42
- }
43
- },
44
- "files": [
45
- "dist",
46
- "NOTICE"
47
- ]
48
- }
1
+ {
2
+ "name": "@margoengine/core",
3
+ "version": "1.0.0",
4
+ "description": "WebGPU rendering and a Wasm transform kernel. WebGL2 is the optional @margoengine/webgl2-compat package.",
5
+ "keywords": [
6
+ "margoengine",
7
+ "webgpu",
8
+ "3d",
9
+ "wasm",
10
+ "rust",
11
+ "renderer"
12
+ ],
13
+ "homepage": "https://margoengine.com",
14
+ "bugs": {
15
+ "url": "https://github.com/scottcampbelldata/margoengine/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/scottcampbelldata/margoengine.git",
20
+ "directory": "packages/core"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "author": "Scott Campbell",
24
+ "type": "module",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "scripts": {
29
+ "test": "node --test tests/*.test.js ../../tests/modern.test.js ../../tests/deep-core*.test.js ../../tests/modern-frame-timing.test.js ../../tests/modern-msaa.test.js ../../tests/modern-quaternion.test.js ../../tests/modern-resolution.test.js",
30
+ "test:gpu": "node tests/empty.browser.mjs && node tests/scale.browser.mjs && node tests/zero-scale.browser.mjs && node tests/ggx-precision.browser.mjs && node tests/depth-equal.browser.mjs && node tests/exact-antialias.browser.mjs && node tests/view-srgb.browser.mjs && cd ../.. && node packages/core/tests/pick-clear.browser.mjs",
31
+ "prepack": "npm --prefix ../.. run build:packages"
32
+ },
33
+ "sideEffects": false,
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.js"
38
+ },
39
+ "./extension": {
40
+ "types": "./dist/extension.d.ts",
41
+ "import": "./dist/extension.js"
42
+ }
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "NOTICE"
47
+ ]
48
+ }
@@ -1,4 +0,0 @@
1
- var e=[.018,.023,.035,1],t=e=>/^#([\da-f]{3}){1,2}$/i.test(e)?parseInt((e[4]?e:e.replace(/\w/g,`$&$&`)).slice(1),16):-1,n=e=>(e/=255)>.04045?((e+.055)/1.055)**2.4:e/12.92,r=e=>e/255,i=/float$|srgb$/;function a(a,o){if(typeof a!=`string`)return e;let s=t(a),c=i.test(o)?n:r;if(s<0)throw RangeError(`Invalid color; use #rrggbb`);return[c(s>>16),c(s>>8&255),c(s&255),1]}var o=/* @__PURE__ */ new WeakMap;function s(e,t){let n=o.get(e);if(!n){let t=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{}}]});n={group:t,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),groups:/* @__PURE__ */ new Map},o.set(e,n)}let r=t.join(),i=n.groups.get(r);if(!i){let a=e.createBuffer({size:16,usage:72});if(e.queue.writeBuffer(a,0,new Float32Array(t)),i=e.createBindGroup({layout:n.group,entries:[{binding:0,resource:{buffer:a}}]}),i.b=a,n.groups.size>63){let[t,r]=n.groups.entries().next().value;n.groups.delete(t),e.queue.onSubmittedWorkDone().then(()=>r.b.destroy())}n.groups.set(r,i)}return[n.layout,i]}function c(t,n,r,{formats:i,values:a=[],depthFormat:o,writeDepth:c,samples:l=1,writeColor:u=!0,tint:d=e}){let f=[i,a,o,+!!c,l,+u].join(`|`),[p,m]=s(t,d),h=n.get(f);if(!h){let e=i.map((e,t)=>`@location(${t}) c${t}:vec4f`).join(`,`),r=t.createShaderModule({code:`@group(0) @binding(0) var<uniform> t:vec4f;
2
- struct Out{${e}}
3
- @vertex fn v(@builtin(vertex_index) i:u32)->@builtin(position) vec4f{return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);}
4
- @fragment fn f()->Out{return Out(t${a.map(e=>`,vec4f(${e})`).join(``)});}`});h=t.createRenderPipeline({layout:p,vertex:{module:r,entryPoint:`v`},fragment:{module:r,entryPoint:`f`,targets:i.map((e,t)=>t?{format:e}:{format:e,writeMask:u?15:0})},...o?{depthStencil:{format:o,depthWriteEnabled:!!c,depthCompare:`always`}}:{},multisample:{count:l}}),n.set(f,h)}r.setPipeline(h),r.setBindGroup(0,m),r.draw(3)}export{n as a,t as i,c as n,e as r,a as t};