@margoengine/animation 0.0.0-stage → 0.1.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.
Files changed (67) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1054 -3
  4. package/dist/batch.d.ts +155 -0
  5. package/dist/clip-utils.d.ts +50 -0
  6. package/dist/clip-utils.js +1 -0
  7. package/dist/clone.d.ts +15 -0
  8. package/dist/deform-readers-DmYAkvBK.js +1 -0
  9. package/dist/deform-readers.d.ts +5 -0
  10. package/dist/deformed-points.d.ts +87 -0
  11. package/dist/deformed-points.js +17 -0
  12. package/dist/discrete-tracks.d.ts +102 -0
  13. package/dist/discrete-tracks.js +1 -0
  14. package/dist/dqs.d.ts +41 -0
  15. package/dist/dqs.js +29 -0
  16. package/dist/errors-t1ewumJS.js +1 -0
  17. package/dist/geometry-cache.d.ts +208 -0
  18. package/dist/geometry-cache.js +4 -0
  19. package/dist/gltf-C2HVNxzB.js +1 -0
  20. package/dist/gltf.d.ts +63 -0
  21. package/dist/group.d.ts +97 -0
  22. package/dist/hdr-format-cmvLFubB.js +1 -0
  23. package/dist/index.d.ts +201 -0
  24. package/dist/index.js +1 -0
  25. package/dist/instanced-morph.d.ts +82 -0
  26. package/dist/instanced-morph.js +13 -0
  27. package/dist/instanced-skin.d.ts +82 -0
  28. package/dist/instanced-skin.js +43 -0
  29. package/dist/interactivity.d.ts +71 -0
  30. package/dist/interactivity.js +4 -0
  31. package/dist/key-cursor.d.ts +23 -0
  32. package/dist/keyframes-BO50xipp.js +4 -0
  33. package/dist/keyframes.d.ts +204 -0
  34. package/dist/lod.d.ts +87 -0
  35. package/dist/lod.js +4 -0
  36. package/dist/material-animation.d.ts +29 -0
  37. package/dist/mixer.d.ts +226 -0
  38. package/dist/mixer.js +4 -0
  39. package/dist/morph-gpu.d.ts +76 -0
  40. package/dist/morph-gpu.js +48 -0
  41. package/dist/playback.d.ts +94 -0
  42. package/dist/playback.js +4 -0
  43. package/dist/point-cache.d.ts +28 -0
  44. package/dist/point-cache.js +1 -0
  45. package/dist/pointer-BOFnz0gk.js +1 -0
  46. package/dist/pointer.d.ts +43 -0
  47. package/dist/pointer.js +1 -0
  48. package/dist/pose-source-MuCl8VDd.js +1 -0
  49. package/dist/pose.d.ts +7 -0
  50. package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
  51. package/dist/retarget.d.ts +107 -0
  52. package/dist/rigid.d.ts +42 -0
  53. package/dist/sampling-DjDWYqt2.js +1 -0
  54. package/dist/sampling.d.ts +112 -0
  55. package/dist/sampling.js +1 -0
  56. package/dist/shader-CgAVFeOl.js +66 -0
  57. package/dist/shader.d.ts +30 -0
  58. package/dist/skeleton-utils.d.ts +2 -0
  59. package/dist/skeleton-utils.js +4 -0
  60. package/dist/skin.d.ts +163 -0
  61. package/dist/src-WGCsukxV.js +4 -0
  62. package/dist/vat-mWaj5B5R.js +50 -0
  63. package/dist/vat.d.ts +178 -0
  64. package/dist/vat.js +1 -0
  65. package/dist/vertex-map-BC_WH7ER.js +1 -0
  66. package/dist/weight-buffer.d.ts +1 -0
  67. package/package.json +133 -6
package/dist/skin.d.ts ADDED
@@ -0,0 +1,163 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { PBRModel } from '@margoengine/gltf/pbr';
3
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
4
+ import type { Mat4, MutableVec3, Quat, Vec3 } from '@margoengine/math';
5
+ /** A bone's transform local to its parent bone; omitted parts keep their value (or the default, for a new bone). */
6
+ export interface BonePose {
7
+ /** Default [0, 0, 0]. */
8
+ translation?: Vec3;
9
+ /** Unit quaternion [x, y, z, w], normalised on input. Default [0, 0, 0, 1]. */
10
+ rotation?: Quat;
11
+ /** Default [1, 1, 1]. */
12
+ scale?: Vec3;
13
+ }
14
+ /** One bone of a {@link Skeleton}. Its translation, rotation and scale are the base (bind) pose. */
15
+ export interface BoneData extends BonePose {
16
+ /** Stable id that keyframe tracks target; unique in the skeleton. */
17
+ name: string;
18
+ /** Index of the parent bone, or -1 for the one root bone. */
19
+ parent: number;
20
+ }
21
+ /** @internal Checks `width` finite numbers (TypeError for the shape, RangeError for the values). */
22
+ export declare function finite(value: unknown, width: number, label: string): ArrayLike<number>;
23
+ /**
24
+ * A bone hierarchy authored from raw data: a base (bind) pose, a current pose set bone by bone, and the matrices a
25
+ * {@link Skin} deforms with. Matrices are in skeleton space, the local space of the skinned mesh the bones live under;
26
+ * they are recomputed lazily after a pose change. Bone length and thickness are display concerns and not stored.
27
+ */
28
+ export declare class Skeleton {
29
+ /** Bone names in input order; a bone's index is its position here. */
30
+ readonly names: readonly string[];
31
+ /** Parent bone index per bone, -1 for the root. */
32
+ readonly parents: readonly number[];
33
+ /** Index of the root bone; vertices whose weights sum to zero follow it. */
34
+ readonly root: number;
35
+ /** Increments on every pose or bind-pose change, so consumers can skip unchanged uploads. */
36
+ revision: number;
37
+ private readonly pose;
38
+ private readonly base;
39
+ private readonly inverse;
40
+ private readonly world;
41
+ private readonly skin;
42
+ private readonly order;
43
+ private readonly byName;
44
+ private readonly local;
45
+ private readonly workspace;
46
+ private dirty;
47
+ /**
48
+ * @param bones The hierarchy and base pose; exactly one bone has parent -1.
49
+ * @param inverseBindMatrices Optional 16 column-major numbers per bone; computed from the base pose when omitted.
50
+ */
51
+ constructor(bones: readonly BoneData[], inverseBindMatrices?: ArrayLike<number>);
52
+ /** Number of bones. */
53
+ get count(): number;
54
+ /** Index of the bone with this name, or -1. */
55
+ index(name: string): number;
56
+ private bone;
57
+ /** Sets any of a bone's local translation, rotation and scale in the current pose. */
58
+ setPose(bone: number, pose: BonePose): this;
59
+ /** A copy of a bone's current local transform. */
60
+ getPose(bone: number): {
61
+ translation: MutableVec3;
62
+ rotation: [number, number, number, number];
63
+ scale: MutableVec3;
64
+ };
65
+ /**
66
+ * Returns bones to the base pose: every bone when `bone` is omitted, else that bone alone (Restore Pose) or, with
67
+ * `nested`, that bone and all bones under it (Restore Pose All).
68
+ */
69
+ restorePose(bone?: number, nested?: boolean): this;
70
+ /** Makes the current pose the base pose and recomputes every inverse bind matrix from it (the mesh stays put). */
71
+ setBindPose(): this;
72
+ private bind;
73
+ private changed;
74
+ private update;
75
+ /** Each bone's current skeleton-space matrix, 16 column-major numbers per bone. Read-only; refreshed on access. */
76
+ get matrices(): Float64Array;
77
+ /** Inverse bind matrices, 16 column-major numbers per bone (for export). Read-only. */
78
+ get inverseBindMatrices(): Float64Array;
79
+ /** `matrices` times `inverseBindMatrices` per bone: what moves a bind-pose vertex. Read-only; refreshed on access. */
80
+ get skinMatrices(): Float64Array;
81
+ /** `parent` (e.g. the skinned mesh's `primitives[0].node.matrix`) times the bone's matrix: its world matrix. */
82
+ worldMatrix(bone: number, parent?: Mat4, out?: Float32Array<ArrayBuffer>): Float32Array;
83
+ }
84
+ interface PosedSnapshot {
85
+ readonly node: PBRModel['root'];
86
+ readonly vertices: Float32Array;
87
+ readonly indices: Uint32Array;
88
+ readonly doubleSided: boolean;
89
+ readonly side: 'front' | 'back' | 'double';
90
+ readonly matrix: Float32Array;
91
+ readonly primitiveIndex: number;
92
+ }
93
+ /**
94
+ * Up to four bone influences per vertex over a {@link Skeleton}, deforming a `createMesh` mesh (or any gltf/pbr model
95
+ * whose primitives share one vertex array) on the GPU once attached. Weights are normalised to sum 1 as they are set;
96
+ * a vertex whose weights sum to zero follows the root bone.
97
+ */
98
+ export declare class Skin implements EnginePlugin {
99
+ readonly skeleton: Skeleton;
100
+ readonly name: string;
101
+ /** Vertex count. */
102
+ readonly count: number;
103
+ /** The mesh it deforms, when made by `Skin.attach`. */
104
+ mesh?: PBRModel;
105
+ private readonly ids;
106
+ private readonly weights;
107
+ private edits;
108
+ private pickingSource?;
109
+ private posed?;
110
+ private dirtyFrom;
111
+ private dirtyTo;
112
+ private uploaded;
113
+ private disposed;
114
+ private gpu?;
115
+ private unsubscribe?;
116
+ private readonly prepare;
117
+ /** @param joints Four bone indices per vertex. @param weights Four weights per vertex, each finite and >= 0. */
118
+ constructor(skeleton: Skeleton, joints: ArrayLike<number>, weights: ArrayLike<number>);
119
+ /**
120
+ * Replaces the influences of vertices `first` onward (four joints and four weights each), for weight painting. Costs
121
+ * O(changed vertices) here; the next frame uploads 32 bytes per vertex from the lowest to the highest changed one.
122
+ */
123
+ setInfluences(first: number, joints: ArrayLike<number>, weights: ArrayLike<number>): this;
124
+ /**
125
+ * CPU skinning at the skeleton's current pose, with the GPU pass's maths: bind-pose `positions` (and `normals`), xyz
126
+ * per vertex in skeleton space, to posed copies. For picking a posed mesh and for exporting a static pose.
127
+ */
128
+ pose(positions: ArrayLike<number>, normals?: ArrayLike<number>): {
129
+ positions: Float32Array;
130
+ normals?: Float32Array;
131
+ };
132
+ /**
133
+ * A synchronous picking source for `Raycaster.intersectPosed` (`@margoengine/bvh`): hits on the mesh at the skeleton's
134
+ * current pose, skinned on the CPU with {@link Skin.pose}. The posed vertices are cached per skeleton `revision` and
135
+ * influence edit, so many rays in one frame skin once. Needs a skin made by `Skin.attach`.
136
+ */
137
+ get picking(): {
138
+ readonly root: PBRModel['root'];
139
+ readonly disposed: boolean;
140
+ posePickingGeometry(): readonly PosedSnapshot[];
141
+ };
142
+ private requireMesh;
143
+ /**
144
+ * A skin that deforms `mesh` on the GPU from now on, as a plugin of the mesh's engine. `mesh` is a `createMesh` mesh
145
+ * (or any gltf/pbr model whose primitives share one vertex array) with one vertex per four influences.
146
+ */
147
+ static attach(mesh: PBRModel, skeleton: Skeleton, joints: ArrayLike<number>, weights: ArrayLike<number>): Skin;
148
+ setup(engine: Engine): void;
149
+ private scenePosed?;
150
+ /**
151
+ * The CPU pose synchronous scene queries test while the GPU pass deforms the mesh (shared/pose-source.js): the
152
+ * vertices `picking` caches per pose, copied into one array so a tree over it is refitted, not rebuilt.
153
+ */
154
+ private readonly scenePose;
155
+ registerPasses(graph: FrameGraph): void;
156
+ private deform;
157
+ private release;
158
+ onDeviceRestored(engine: Engine): void;
159
+ /** Stops deforming the mesh and frees the GPU buffers. CPU posing keeps working. */
160
+ dispose(): void;
161
+ [Symbol.dispose]: () => void;
162
+ }
163
+ export {};
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{n as e}from"./errors-t1ewumJS.js";import{t}from"./vertex-map-BC_WH7ER.js";import{n,t as r}from"./pose-source-MuCl8VDd.js";import{t as i}from"./deform-readers-DmYAkvBK.js";import{c as a,o}from"./sampling-DjDWYqt2.js";import{t as s}from"./shader-CgAVFeOl.js";import{a as c,i as l,s as u,t as d}from"./keyframes-BO50xipp.js";import{a as f,c as p,d as m,i as h,l as g,n as _,o as v,r as y,s as b,t as x,u as S}from"./gltf-C2HVNxzB.js";import{MargoError as C}from"@margoengine/math/errors";import{invertMatrixStable as w,multiplyMatrices as T}from"@margoengine/math/mat4";import{conjugateQuaternion as E,multiplyQuaternions as D,normalizeQuaternion as O}from"@margoengine/math/quat";import{PBRModel as ee,textureCoordinates as k,textureTransform as te}from"@margoengine/gltf/pbr-model";import{MargoError as A}from"@margoengine/math";function ne(e,t){for(let n=t;n>=0;n=e.parents?.[n]??-1)if(e.hidden[n])return!0;return!1}function re(e,t,n,r,i,a,o){let s=e.length/20,c=s?n.length/(s*12):0,l=new Float32Array(i.buffer,i.byteOffset,i.length),u=/* @__PURE__ */ new Float64Array(16);t.set(e);for(let d=0,f=0;d<s;d++,f+=20){let p=e[f],m=e[f+1],h=e[f+2],g=e[f+4],_=e[f+5],v=e[f+6];for(let e=0;e<c;e++){let t=r[e],i=(e*s+d)*12;p+=n[i]*t,m+=n[i+1]*t,h+=n[i+2]*t,g+=n[i+4]*t,_+=n[i+5]*t,v+=n[i+6]*t}if(i.length){u.fill(0);for(let e=d*a,t=e+a;e<t;e+=8)for(let t=0;t<4;t++){let n=l[e+4+t],r=i[e+t]*16;if(n)for(let e=0;e<16;e++)u[e]+=n*o[r+e]}let e=u[0]*p+u[4]*m+u[8]*h+u[12],t=u[1]*p+u[5]*m+u[9]*h+u[13];h=u[2]*p+u[6]*m+u[10]*h+u[14],p=e,m=t;let n=u[5]*u[10]-u[6]*u[9],r=u[6]*u[8]-u[4]*u[10],s=u[4]*u[9]-u[5]*u[8],c=u[9]*u[2]-u[10]*u[1],f=u[10]*u[0]-u[8]*u[2],y=u[8]*u[1]-u[9]*u[0],b=u[1]*u[6]-u[2]*u[5],x=u[2]*u[4]-u[0]*u[6],S=u[0]*u[5]-u[1]*u[4],C=u[0]*n+u[1]*r+u[2]*s>=0?1:-1,w=(n*g+c*_+b*v)*C,T=(r*g+f*_+x*v)*C,E=(s*g+y*_+S*v)*C,D=w*w+T*T+E*E>0;g=D?w:0,_=D?T:1,v=D?E:0}let y=Math.hypot(g,_,v)||1;t[f]=p,t[f+1]=m,t[f+2]=h,t[f+4]=g/y,t[f+5]=_/y,t[f+6]=v/y}}var ie=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Float32Array.prototype),`buffer`).get,ae=Reflect.apply,oe=[];function se(e){return ae(ie,e,oe)instanceof ArrayBuffer}var j=80,ce=48,le=16,ue=4,de=64,fe=48,pe=64,M=class{constructor(e,t,n=1){this.bytes=e,this.usage=t,this.align=n,this.capacity=0,this.top=0,this.ranges=/* @__PURE__ */ new Set}get live(){let e=0;for(let t of this.ranges)e+=t.size;return e}},me=class{constructor(e){this.source=new M(j,GPUBufferUsage.STORAGE),this.morphs=new M(ce,GPUBufferUsage.STORAGE),this.influences=new M(le,GPUBufferUsage.STORAGE),this.weights=new M(ue,GPUBufferUsage.STORAGE),this.bones=new M(de,GPUBufferUsage.STORAGE),this.slots=/* @__PURE__ */ new Set,this.blocks=/* @__PURE__ */ new Map,this.version=0;let t=1;for(;t*j%e;)t++;this.output=new M(j,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC,t)}get pools(){return[this.source,this.output,this.morphs,this.influences,this.weights,this.bones]}},N=/* @__PURE__ */ new WeakMap,P=(e,t)=>Math.ceil(e/t)*t,F=(e,t)=>t+`:`+e.count+`:`+(t===`i`?e.skin??``:``),I=(e,t)=>t===`s`?e.primitive.vertices:e.primitive.part?.vertexMap??e.definition,L=(e,t,n)=>e.asset===t.asset&&I(e,n)===I(t,n)&&F(e,n)===F(t,n),R=e=>Math.max(4,e),he=class e{constructor(e){this.device=e,this.pages=[],this.version=0,this.pipelines=[],this.modes=[void 0];let t=e.limits;this.limit=Math.min(t.maxStorageBufferBindingSize,t.maxBufferSize),this.alignment=t.minStorageBufferOffsetAlignment??256}static of(t){let n=N.get(t);return n||N.set(t,n=new e(t)),n}variant(e,t){let n=this.modes.indexOf(t);return n<0&&(n=this.modes.push(t)-1),n*2+ +e}pipeline(e,t){return this.pipelines[this.variant(e,t)]??=this.device.createComputePipeline({layout:`auto`,compute:{module:this.device.createShaderModule({code:t?.shader(e)??s(e)}),entryPoint:`main`}})}add(e){if(!e.length)return[];let t=/* @__PURE__ */ new Map,n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;for(let o of e){let e=this.needs(o);if(e.some((e,t)=>e*[j,j,ce,le,ue,de][t]>this.limit))throw RangeError(`Animation buffer exceeds device limit; split the mesh or reduce vertices, joints and morph targets`);let s=o.joints?o.primitive.node:void 0,c=s&&i.get(s)?.get(o.skin),l;if(c&&c.spec.joints===o.joints&&c.spec.mode===o.mode){let t=e[5];e[5]=0,this.fits(c.page,r.get(c.page),e)?(l=c.page,a.set(o,c.spec)):e[5]=t}if(l??=[...this.pages,...n].find(t=>this.fits(t,r.get(t),e)),l||n.push(l=new me(this.alignment)),s&&!c){let e=i.get(s);e||i.set(s,e=/* @__PURE__ */ new Map),e.set(o.skin,{spec:o,page:l})}let u=t.get(l)??[];(this.block(l,o,`s`)||u.some(e=>L(e,o,`s`)))&&(e[0]=0),(this.block(l,o,`m`)||u.some(e=>L(e,o,`m`)))&&(e[2]=0),(this.block(l,o,`i`)||u.some(e=>L(e,o,`i`)))&&(e[3]=0);let d=r.get(l)??[0,0,0,0,0,0];e.forEach((e,t)=>d[t]+=e),r.set(l,d);let f=t.get(l);f||t.set(l,f=[]),f.push(o)}this.pages.push(...n);for(let[e,n]of t)this.reserve(e,r.get(e),n);let o=/* @__PURE__ */ new Map,s=e.map(e=>{let n=[...t].find(([,t])=>t.includes(e))[0],r=this.place(n,e,o.get(a.get(e))?.bones);return o.set(e,r),r}),c=this.device.createCommandEncoder();for(let e of s)c.copyBufferToBuffer(e.page.source.buffer,e.source.range.offset*j,e.page.output.buffer,e.output.offset*j,e.count*j);return this.device.queue.submit([c.finish()]),this.version++,s}remove(e){let t=e.page;if(!t.slots.delete(e))return;let n=e.primitive;this.published(e)&&(n.deformed=n.deformedOffset=void 0),t.output.ranges.delete(e.output),t.weights.ranges.delete(e.weights),(e.bones.refs=(e.bones.refs??1)-1)<=0&&t.bones.ranges.delete(e.bones);for(let[n,r]of[[e.source,t.source],[e.morphs,t.morphs],[e.influences,t.influences]])if(n&&--n.refs===0){r.ranges.delete(n.range),n.owner.delete(n.key);let e=t.blocks.get(n.asset);n.owner.size||e.delete(n.holder),e.size||t.blocks.delete(n.asset)}if(t.version++,this.version++,!t.slots.size){for(let e of t.pools)e.buffer?.destroy();t.info?.buffer.destroy(),this.pages.splice(this.pages.indexOf(t),1)}}dispatches(e,t,n){if(n.version===this.version&&n.owners.length===e.length&&n.owners.every((t,n)=>t===e[n]))return n.dispatches;let r=[],i=/* @__PURE__ */ new Map;for(let n of e)for(let e of t(n)){let t=e.page;if(!t.slots.has(e))continue;this.records(t);let n=i.get(t);n||i.set(t,n=[]);let r=n[this.variant(e.extra,e.mode)]??=[];for(let t=0;t<e.count;t+=pe)r.push(e.index,t)}let a=this.device.limits.maxComputeWorkgroupsPerDimension??65535;try{for(let[e,t]of i)for(let n=0;n<t.length;n++){let i=t[n];if(!i?.length)continue;let o=i.length/2,s=this.pipeline(!!(n&1),this.modes[n>>1]),c=new Uint32Array(i.length+2);c[0]=o,c.set(i,2);let l=this.mapped(c),u=Math.min(o,a);r.push({pipeline:s,table:l,x:u,y:Math.ceil(o/u),group:void 0}),r[r.length-1].group=this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[e.source.buffer,e.output.buffer,e.morphs.buffer,e.weights.buffer,e.bones.buffer,e.influences.buffer,e.info.buffer,l].map((e,t)=>({binding:t,resource:{buffer:e}}))})}}catch(e){for(let e of r)e.table.destroy();throw e}return this.retire(n.dispatches.map(e=>e.table)),n.owners=e.slice(),n.version=this.version,n.dispatches=r,r}drop(e){for(let t of e.dispatches)t.table.destroy();e.dispatches=[],e.owners=[],e.version=-1}block(e,t,n){return e.blocks.get(t.asset)?.get(I(t,n))?.get(F(t,n))}needs(e){return[e.count,e.count,e.count*e.targets,e.joints?e.count*(e.extra?4:2):0,R(e.targets),e.joints]}fits(e,t,n){return e.pools.every((r,i)=>{let a=i===1?r.align*(e.slots.size+1):0;return(r.live+(t?.[i]??0)+n[i]+a)*r.bytes<=this.limit})}reserve(e,t,n){let r=e.pools,i=(e,i)=>e===1?n.reduce((e,t)=>P(e,r[1].align)+t.count,i):i+t[e];if(r.every((e,t)=>e.buffer&&i(t,e.top)<=e.capacity))return;let a=r.some(e=>e.ranges.size)?this.device.createCommandEncoder():void 0,o=[],s=[...e.slots].filter(e=>this.published(e));r.forEach((e,t)=>{let n=[...e.ranges].sort((e,t)=>e.offset-t.offset),r=0;for(let t of n)r=P(r,e.align)+t.size;let s=i(t,r),c=Math.floor(this.limit/e.bytes),l=Math.max(s,Math.min(c,e.capacity*2),1),u=this.device.createBuffer({size:Math.max(16,l*e.bytes),usage:e.usage|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),d=0;for(let t of n)d=P(d,e.align),t.size&&a.copyBufferToBuffer(e.buffer,t.offset*e.bytes,u,d*e.bytes,t.size*e.bytes),t.offset=d,d+=t.size;e.buffer&&o.push(e.buffer),e.buffer=u,e.capacity=Math.floor(u.size/e.bytes),e.top=d}),a&&this.device.queue.submit([a.finish()]),this.retire(o);for(let e of s)this.publish(e);e.version++,this.version++}place(e,t,n){let r=(e,t)=>{let n=P(e.top,e.align),r={offset:n,size:t};return e.top=n+t,e.ranges.add(r),r},i=(n,i,a,o)=>{if(!a&&i!==`s`)return;let s=e.blocks.get(t.asset);s||e.blocks.set(t.asset,s=/* @__PURE__ */ new Map);let c=I(t,i),l=s.get(c);l||s.set(c,l=/* @__PURE__ */ new Map);let u=F(t,i),d=l.get(u);return d||(d={range:r(n,a),refs:0,key:u,owner:l,asset:t.asset,holder:c},l.set(u,d),this.write(n,d.range,o())),d.refs++,d},a={page:e,primitive:t.primitive,count:t.count,targets:t.targets,joints:t.joints,extra:t.extra,mode:t.mode,source:i(e.source,`s`,t.count,()=>t.primitive.vertices),output:r(e.output,t.count),weights:r(e.weights,R(t.targets)),bones:n?(n.refs++,n):Object.assign(r(e.bones,t.joints),{refs:1}),morphs:i(e.morphs,`m`,t.count*t.targets,t.deltas),influences:i(e.influences,`i`,t.joints?t.count*(t.extra?4:2):0,t.influences),index:-1};return e.slots.add(a),e.version++,this.publish(a),a}published(e){let t=e.primitive;return t.deformed===e.page.output.buffer&&(t.deformedOffset??0)===e.output.offset*j}publish(e){let t=e.primitive;t.deformed=e.page.output.buffer,t.deformedOffset=e.output.offset*j}write(e,t,n){t.size&&this.device.queue.writeBuffer(e.buffer,t.offset*e.bytes,n)}records(e){if(e.info?.version===e.version)return;let t=new Uint32Array(Math.max(1,e.slots.size)*(fe/4)),n=0;for(let r of e.slots)r.index=n,t.set([r.source.range.offset,r.output.offset,r.count,r.targets,r.morphs?.range.offset??0,r.weights.offset,r.bones.offset,r.joints,r.influences?.range.offset??0],n++*(fe/4));e.info&&this.retire([e.info.buffer]),e.info={buffer:this.mapped(t),version:e.version}}mapped(e){let t=this.device.createBuffer({size:Math.max(16,e.byteLength),usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});return new Uint32Array(t.getMappedRange()).set(e),t.unmap(),t}retire(e){e.length&&this.device.queue.onSubmittedWorkDone().then(()=>{for(let t of e)t.destroy()})}},z=/* @__PURE__ */ new WeakMap;function B(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(t+` must be an object`);return e}function V(e,t){if(!Array.isArray(e)||e.length!==2||e.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw TypeError(t+` needs two finite Float32 values`)}function H(e,t,n){let r=e.asset.doc.accessors??[],i=f(t,r.length,`material accessor`),a=r[i];if(a.componentType!==5126||a.type!==n||a.normalized!==void 0&&a.normalized!==!1)throw TypeError(`Material animation accessors must be unnormalized Float32 `+n);if(!Number.isSafeInteger(a.count)||a.count<1)throw RangeError(`Material animation accessor count must be positive`);let o=e.asset.accessor(i,n);if(o.length!==a.count*(n===`SCALAR`?1:2)||o.some(e=>!Number.isFinite(e)))throw RangeError(`Material animation accessor length/values must match its definition`);return new Float32Array(o)}function U(e,t,n){let r=H(e,g(t.samplers[f(n,t.samplers.length,`material sampler`)]).input,`SCALAR`);if(r.some((e,t)=>e<0||t>0&&e<=r[t-1]))throw RangeError(`Material animation times must be nonnegative and strictly increasing`);return r}function ge(e,t){let n=[],r=[],i=/* @__PURE__ */ new Set,a=0;for(let o of t.channels){let s=B(o,`Animation channel`),c=B(s.target,`Animation target`),l=c.extensions===void 0?void 0:B(c.extensions,`Animation target extensions`);if(c.path!==`pointer`&&l?.KHR_animation_pointer===void 0){r.push(o);continue}if(c.path!==`pointer`||Object.hasOwn(c,`node`))throw TypeError(`Material animation pointer requires path pointer and an absent target node`);let u=B(l?.KHR_animation_pointer,`KHR_animation_pointer`).pointer,d=typeof u==`string`&&/^\/materials\/(0|[1-9]\d*)\/pbrMetallicRoughness\/baseColorTexture\/extensions\/KHR_texture_transform\/(offset|scale)$/.exec(u);if(!d)throw TypeError(`Unsupported material animation pointer; use baseColorTexture offset or scale`);let p=f(Number(d[1]),e.asset.doc.materials?.length??0,`material`),m=d[2],h=e.asset.doc.materials[p].pbrMetallicRoughness?.baseColorTexture;if(!h||!Number.isInteger(h.index)||h.index<0||h.index>=(e.asset.doc.textures?.length??0))throw TypeError(`Material animation target needs a real baseColorTexture`);if(V(B(h.extensions?.KHR_texture_transform,`Material animation initial transform`)[m],`Material animation initial `+m),k(h),!e.primitives.some(e=>e.definition.material===p))throw TypeError(`Material animation target must have a current model primitive`);let _=p+`:`+m;if(i.has(_))throw TypeError(`Duplicate material animation target; use one channel per property`);i.add(_);let v=g(t.samplers[f(s.sampler,t.samplers.length,`material sampler`)]);if(v.interpolation!==`STEP`)throw TypeError(`Material animation requires explicit STEP interpolation`);let y=U(e,t,s.sampler),b=H(e,v.output,`VEC2`);if(b.length!==y.length*2)throw RangeError(`Material animation output count must match its keys`);a=Math.max(a,y[y.length-1]),n.push({material:p,property:m,times:y,values:b})}return{tracks:n,nodeChannels:r,duration:a}}function W(e){if(!(e instanceof ee))throw TypeError(`Material animation needs a PBRModel`);let t=e.root,n=t.engine;if(e.disposed||n.disposed)throw new A(`disposed`,`Material animation model is disposed; load a new model`);if(n.meshes.get(t.id)!==t)throw new A(`state`,`Material animation model root is stale; load a new model`)}function G(e){let t=e.material.maps?.[0];if(!t||t.index!==e.texture||!Array.isArray(e.material.uvt)||e.material.uvt.length<8)throw new A(`state`,`Material animation binding changed; recreate the player for the current material`);let n=B(t.extensions?.KHR_texture_transform,`Material animation map transform`);for(let t of e.tracks.keys())V(n[t],`Material animation map `+t);return k(t),t}function _e(e,t={}){if(W(e),B(t,`Material animation options`),t.loop!==void 0&&typeof t.loop!=`boolean`)throw TypeError(`Material animation loop must be boolean`);let n=e.asset.doc.animations??[],r=f(t.clip===void 0?0:t.clip,n.length,`material clip`),i=y(n[r]),a=ge(e,i);if(!a.tracks.length)throw TypeError(`Selected clip needs supported material animation tracks`);let s=a.duration;for(let t of a.nodeChannels){let n=U(e,i,B(t,`Animation channel`).sampler);s=Math.max(s,n[n.length-1])}let c=e.asset,l=c.doc,u=/* @__PURE__ */ new Map,d=new Set(a.tracks.map(e=>e.material));for(let t of a.tracks)for(let n of e.primitives)if(n.definition.material===t.material){let e=u.get(n.material);e||(e={material:n.material,texture:l.materials[t.material].pbrMetallicRoughness.baseColorTexture.index,primitives:/* @__PURE__ */ new Map,tracks:/* @__PURE__ */ new Map},u.set(n.material,e));let r=e.tracks.get(t.property);if(r&&r!==t)throw TypeError(`Aliased material animation targets overlap; use one track per actual material property`);e.tracks.set(t.property,t),e.primitives.set(n,t.material)}let p=()=>{if(W(e),e.asset!==c||e.asset.doc!==l)throw new A(`state`,`Material animation asset changed; recreate the player`);let t=0,n=0;for(let t of u.values()){n+=t.primitives.size;for(let[n,r]of t.primitives)if(!e.primitives.includes(n)||n.material!==t.material||n.definition.material!==r||n.node.engine!==e.root.engine||n.node.engine.meshes.get(n.node.id)!==n.node)throw new A(`state`,`Material animation primitive binding changed; recreate the player`);G(t)}for(let n of e.primitives)d.has(n.definition.material)&&t++;if(t!==n)throw new A(`state`,`Material animation primitive bindings changed; recreate the player`)};p();for(let e of u.values())for(let t of e.tracks.keys())if(z.get(e.material)?.has(t))throw new A(`attached`,`Material animation property is already owned by an active player; dispose that player first`);for(let e of u.values()){let t=z.get(e.material);t||z.set(e.material,t=/* @__PURE__ */ new Set);for(let n of e.tracks.keys())t.add(n)}let m=!1,h,g=()=>{if(!m){m=!0,h?.(),h=void 0;for(let e of u.values()){let t=z.get(e.material);for(let n of e.tracks.keys())t.delete(n);t.size||z.delete(e.material)}}};try{h=e.onDispose(g)}catch(e){throw g(),e}let _=t.loop??!1;return{dispose:g,seek(e){if(m)throw new A(`disposed`,`Material animation player is disposed; create a new player`);if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw RangeError(`Material animation seconds must be finite and nonnegative`);p();let t=_&&s>0?e%s:Math.min(e,s),n=/* @__PURE__ */ new Map;for(let e of a.tracks){let r=o(e.times,e.values,2,t,`STEP`);n.set(e,[r[0],r[1]])}let r=Array.from(u.values(),e=>{let t=G(e),r=t.extensions.KHR_texture_transform,i={...r};for(let[t,r]of e.tracks)i[t]=n.get(r);i.offset&&=[...i.offset],i.scale&&=[...i.scale];let a=k(t).texCoord,o=te({...i,texCoord:a},a),s=e.material.uvt;return{binding:e,changed:[...e.tracks.keys()].some(e=>{let t=r[e],n=i[e];return!Object.is(t[0],n[0])||!Object.is(t[1],n[1])})||o.some((e,t)=>!Object.is(e,s[t])),map:{...t,extensions:{...t.extensions,KHR_texture_transform:i}},rows:o}});for(let{binding:e,changed:t,map:n,rows:i}of r)if(t){let t=e.material.maps.slice();t[0]=n,e.material.maps=t;for(let t=0;t<8;t++)e.material.uvt[t]=i[t]}}}}function ve(e,t,n,r={}){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))throw TypeError(`compileRigidClip needs arrays of bones, bindings and keys`);let i=(e,t,n)=>{let r=e;if(typeof r!=`object`||!r||r.length!==t)throw TypeError(`${n} needs ${t} numbers`);if(!Array.from(r).every(e=>typeof e==`number`&&Number.isFinite(e)))throw RangeError(`${n} must be finite numbers`);return Array.from(r)},a=/* @__PURE__ */ new Set;for(let t of e){if(typeof t?.id!=`string`||!t.id)throw TypeError(`Every rigid bone needs a nonempty string id`);i(t.translation,3,`Bone ${t.id} translation`),a.add(t.id)}let o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map;for(let e of t){if(typeof e?.object!=`string`||o.has(e.object))throw TypeError(`Binding for ${String(e?.object)} is missing or repeated; bind each mesh once`);if(!a.has(e.bone))throw TypeError(`Binding for ${e.object} names unknown bone ${e.bone}; bind it to a listed bone`);i(e.position,3,`Binding ${e.object} position`),i(e.rotation,4,`Binding ${e.object} rotation`),o.set(e.object,e),s.set(e.bone,[...s.get(e.bone)??[],e.object])}let c=/* @__PURE__ */ new Map;for(let e of n){if(typeof e?.object!=`string`)throw TypeError(`Every rigid key needs a string object`);if(typeof e.time!=`number`||!Number.isFinite(e.time)||e.time<0)throw RangeError(`Key of ${e.object} needs a finite time of 0 or more`);i(e.position,3,`Key of ${e.object} position`),i(e.rotation,4,`Key of ${e.object} rotation`);let t=o.get(e.object);t&&c.set(t.bone,[...c.get(t.bone)??[],e])}let{name:u,duration:d}=r;if(d!==void 0&&(typeof d!=`number`||!Number.isFinite(d)||d<0))throw RangeError(`duration must be a finite number of seconds, 0 or more`);let f=[];for(let t of e){let e=[...c.get(t.id)??[]].sort((e,t)=>e.time-t.time);if(!e.length)continue;let n=new Map((s.get(t.id)??[]).map((e,t)=>[e,t])),r=s.get(t.id),i=/* @__PURE__ */ new Map,a=[],l=[];e[0].time>0&&(a.push({time:0,value:t.translation,interpolation:`discrete`}),l.push({time:0,value:[0,0,0,1],interpolation:`discrete`}));let u=1/0;for(let s=0;s<e.length;){let c=e[s].time;for(;s<e.length&&e[s].time===c;){let t=e[s++];i.set(t.object,t),u=Math.min(u,n.get(t.object))}let d=o.get(r[u]),f=i.get(d.object);a.push({time:c,value:[0,1,2].map(e=>t.translation[e]+(f.position[e]-d.position[e])),interpolation:`discrete`}),l.push({time:c,value:D(O(f.rotation),E(O(d.rotation))),interpolation:`discrete`})}d!==void 0&&d>e[e.length-1].time&&(a.push({...a[a.length-1],time:d}),l.push({...l[l.length-1],time:d})),f.push({target:t.id,path:`translation`,keys:a},{target:t.id,path:`rotation`,keys:l})}return l(u===void 0?{tracks:f}:{name:u,tracks:f})}var K=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e))throw RangeError(`AnimationGroup ${t} ${e} is invalid; pass finite seconds`);return e},ye=0,be=class e{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t={}){if(this.clip=e,this.options=t,this.name=`animation-group:`+ye++,this.time=0,this.playing=!0,this.members=[],this.disposed=!1,typeof e!=`string`&&typeof e!=`number`&&!Array.isArray(e?.tracks))throw TypeError(`AnimationGroup clip must be a glTF clip name or index, or a KeyframeClip`);if(t.loop!==void 0&&typeof t.loop!=`boolean`)throw TypeError(`AnimationGroup loop must be a boolean`);let n=t.speed??1;if(typeof n!=`number`||!Number.isFinite(n)||n<0)throw RangeError(`AnimationGroup speed ${n} is invalid; pass a finite number >= 0`)}get size(){return this.members.length}has(e){return this.members.some(t=>t.target===e)}add(e,t=0){if(this.disposed)throw new C(`disposed`,`AnimationGroup is disposed; create a new group`);K(t,`offset`);let n=this.members.find(t=>t.target===e);if(n)return n.offset=t,this.pose(n),this;let r=this.clip,i=typeof r==`object`,a=-1;if(!i){let t=e;if(e instanceof u||!Array.isArray(t?.clips)||typeof t.seek!=`function`)throw TypeError(`AnimationGroup with a glTF clip needs Animation members; pass Animation.attach(model)`);if(a=typeof r==`string`?t.clips.findIndex(e=>e.name===r):r,!Number.isInteger(a)||a<0||a>=t.clips.length)throw RangeError(`AnimationGroup clip ${r} is not one of this model's clips; pass a name or index it has`);t.playing=!1}let o={target:e,offset:t,clip:a,bindings:i?this.bind(r,e):[]};return this.members.push(o),this.pose(o),this}remove(e){let t=this.members.findIndex(t=>t.target===e);return t>=0&&this.members.splice(t,1),this}setOffset(e,t){let n=this.members.find(t=>t.target===e);if(!n)throw RangeError(`AnimationGroup member not found; add it first`);return n.offset=K(t,`offset`),this.pose(n),this}seek(e){if(K(e,`time`)<0)throw RangeError(`AnimationGroup time ${e} is invalid; pass seconds >= 0`);return this.time=e,this.poseAll(),this}update(e){return this.advanceTime(e),this.poseAll(),this}advanceTime(e){if(K(e,`delta`)<0)throw RangeError(`AnimationGroup delta ${e} is invalid; pass >= 0`);this.playing&&!this.disposed&&(this.time+=e*(this.options.speed??1))}setup(e){if(this.disposed)throw new C(`disposed`,`AnimationGroup is disposed; create a new group`);this.engine=e}onPreUpdate(e){this.update(e)}dispose(){this.disposed||(this.disposed=!0,this.members.length=0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.engine=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}poseAll(){for(let e=this.members.length-1;e>=0;e--){let t=this.members[e].target;!(t instanceof u)&&t.model.disposed?this.members.splice(e,1):this.pose(this.members[e])}}pose(e){let t=this.time+e.offset;if(e.clip>=0){let n=e.target,r=n.clips[e.clip].duration;n.clip=e.clip,n.seek(t>=0?t:(n.options.loop??!0)&&r>0?t%r+r:0);return}let n=this.clip.duration,r=(this.options.loop??!0)&&n>0?(t%n+n)%n:Math.min(Math.max(t,0),n);for(let t=0;t<e.bindings.length;t++)e.bindings[t](r)}bind(e,t){let n=[];if(t instanceof u){for(let r of e.tracks){let e=r.path===`weights`?-1:t.index(r.target);if(e<0)continue;let i=new Float64Array(r.path===`rotation`?4:3),a={[r.path]:i};n.push(n=>{c(r,n,i),t.setPose(e,a)})}return n}let r=t,i=r?.model?.nodes;if(!Array.isArray(i)||typeof r.setMorph!=`function`)throw TypeError(`AnimationGroup members must be Skeletons or Animations; pass Animation.attach(model)`);for(let t of e.tracks){let e=i.findIndex(e=>e.name===t.target);if(e<0)continue;let a=i[e],o=t.values.length/t.times.length,s=new Float64Array(o),l=[0,0,0,1];if(t.path===`weights`){let n=r.model.primitives.find(t=>t.nodeIndex===e)?.weights.length??0;if(n!==o)throw RangeError(`Keyframe track ${t.target} weights has ${o} values but the node has ${n} morph targets; key one weight per target`)}n.push(n=>{if(c(t,n,s),t.path===`weights`)for(let t=0;t<o;t++)r.setMorph(e,t,s[t]);else if(t.path===`translation`)a.setPosition(s);else if(t.path===`scale`)a.setScale(s);else{for(let e=0;e<4;e++)l[e]=s[e];a.setQuaternion(l)}})}return n}};function xe(e,t,n){let r=[],i=[],a=0;return t.channels.forEach((o,s)=>{let c=o,l=c?.target?.extensions?.KHR_animation_pointer;if(c?.target?.path!==`pointer`&&l===void 0){r.push(o);return}let u=g(t.samplers[f(c.sampler,t.samplers.length,`sampler`)]);a=Math.max(a,e.asset.accessor(u.input,`SCALAR`).at(-1)??0),i.push(`Animation ${n} channel ${s}: pointer ${String(l?.pointer)} is not played; pass pointers from @margoengine/animation/pointer (Animation.attach(model, {pointers: pointerChannels}))`)}),{ordinary:r,nodes:[],duration:a,warnings:i}}var q=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Se(e){let t=new Float32Array(e*16);for(let e=0;e<t.length;e+=16)t[e]=t[e+5]=t[e+10]=t[e+15]=1;return t}var J=/* @__PURE__ */ new Float32Array,Ce=()=>/* @__PURE__ */ new Uint32Array,we=()=>J;function Te(e,t,n,r){for(let i=0;i<4;i++)for(let a=0;a<4;a++)r[i*4+a]=e[a]*t[n+i*4]+e[4+a]*t[n+i*4+1]+e[8+a]*t[n+i*4+2]+e[12+a]*t[n+i*4+3]}function Ee(){try{let e=globalThis.GPUQueue,t=typeof e==`function`?e.prototype:void 0,n=t&&Object.getOwnPropertyDescriptor(t,`writeBuffer`)?.value;if(t&&typeof n==`function`&&/^function writeBuffer\(\)\s*\{\s*\[native code\]\s*\}$/.test(Function.prototype.toString.call(n)))return{prototype:t,writer:n}}catch{}}var Y=/* @__PURE__ */ Ee(),De=Reflect.get(Object.prototype,`__lookupGetter__`),Oe=Symbol.for(`margoengine.writeBuffer.copiesInput`);function X(e,t){if(Object.hasOwn(e,`writeBuffer`)||typeof De!=`function`||De.call(e,`writeBuffer`)!==void 0)return!1;let n=Object.getPrototypeOf(e);return Y&&t===Y.writer&&n===Y.prototype?!0:!!n&&Object.getOwnPropertyDescriptor(n,`writeBuffer`)?.value===t&&t[Oe]===!0}function Z(e,t,n,r,i,a){let o=n.uploadArgs;o[0]=r,o[1]=i,o[2]=a;try{Reflect.apply(t,e,o)}finally{o[2]=void 0}}var Q=()=>({owners:[],version:-1,dispatches:[]}),ke=e=>e.slots,Ae=/* @__PURE__ */ new WeakMap,je=[`POSITION`,`NORMAL`,`TANGENT`];function Me(e,n,r,i){let a=new Float32Array(r*n.length*12);return n.forEach((n,o)=>je.forEach((s,c)=>{if(n[s]===void 0)return;let l=t(e.accessor(n[s],`VEC3`),3,i);for(let e=0;e<r;e++)a.set(l.subarray(e*3,e*3+3),(o*r+e)*12+c*4)})),a}function Ne(e){return{primitive:e,slot:void 0,get output(){return this.slot.page.output.buffer},get weights(){return this.slot.page.weights.buffer},get bones(){return this.slot.page.bones.buffer},palette:/* @__PURE__ */ new Float32Array,paletteBits:/* @__PURE__ */ new Uint32Array,spare:/* @__PURE__ */ new Float32Array,spareBits:/* @__PURE__ */ new Uint32Array,next:/* @__PURE__ */ new Float32Array,bonesChanged:!1,uploadedWeights:new Float32Array(e.weights.length),bonesUploaded:!1,weightsUploaded:!1,uploadArgs:[void 0,0,void 0],joints:[],inverseBind:J,influences:Ce,deltas:we}}function Pe(e,n,r,i,a,o,s,c){let l=new ArrayBuffer(Math.max(32,i*o*4)),u=new Uint32Array(l),d=new Float32Array(l),f=o===16;for(let e of Object.keys(r))if(/^(JOINTS|WEIGHTS)_/.test(e)&&!/^(JOINTS|WEIGHTS)_[01]$/.test(e))throw RangeError(`More than eight joint influences are unsupported; limit each vertex to JOINTS_0 and JOINTS_1`);let p=[];for(let i=0;i<(f?2:1);i++){let o=r[`JOINTS_`+i],s=r[`WEIGHTS_`+i];if(o===void 0||s===void 0)throw TypeError(`Skin attributes require paired JOINTS_`+i+` and WEIGHTS_`+i);let l=e.accessor(o,`VEC4`),u=e.accessor(s,`VEC4`),d=x(n,o);if(l.length!==a*4||u.length!==a*4||d?.componentType!==5121&&d?.componentType!==5123||d?.normalized)throw TypeError(`Invalid skin attributes; JOINTS_n must be unsigned byte or short VEC4, WEIGHTS_n VEC4, one per vertex`);let f=x(n,s);if(!f||f.componentType!==5126&&f.componentType!==5121&&f.componentType!==5123||f.componentType!==5126&&!f.normalized)throw TypeError(`Invalid skin weight component type; use float, or normalized unsigned byte or short weights`);p.push({ids:t(l,4,c),weights:t(u,4,c)})}for(let e=0;e<i;e++){let t=p[0].weights,n=t[e*4]+t[e*4+1]+t[e*4+2]+t[e*4+3];if(f){let t=p[1].weights;n+=t[e*4]+t[e*4+1]+t[e*4+2]+t[e*4+3]}if(n<=0)throw RangeError(`Skin weights must have a positive sum`);for(let t=0;t<p.length;t++)for(let r=0;r<4;r++){let{ids:i,weights:a}=p[t],c=e*4+r,l=e*o+t*8;if(!Number.isInteger(i[c])||i[c]<0||i[c]>=s||a[c]<0)throw RangeError(`Invalid skin joint/weight; joint indices must address the skin joints and weights must be >= 0`);u[l+r]=i[c],d[l+4+r]=a[c]/n}}return u}function $(e,t){e.setPipeline(t.pipeline),e.setBindGroup(0,t.group),e.dispatchWorkgroups(t.x,t.y)}var Fe=class o{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);constructor(e,t={}){this.model=e,this.options=t,this.playing=!0,this.time=0,this.clip=0,this.due=!1,this.resources=[],this.leaders=[],this.wholes=[/* @__PURE__ */ new Float32Array,/* @__PURE__ */ new Float32Array],this.deformedNodes=[],this.slots=[],this.cache=Q(),this.inverse=/* @__PURE__ */ new Float32Array(16),this.joint=/* @__PURE__ */ new Float32Array(16),this.product=/* @__PURE__ */ new Float32Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.quaternion=[0,0,0,1],this.disposed=!1,this.groupStart=/* @__PURE__ */ new Int32Array(1),this.groupItems=/* @__PURE__ */ new Int32Array,this.gpuWeights=!1,this.prepareDeformation=e=>this.deform(e),this.createDeformationRenderer=(e,t)=>{let n=new o(e,this.options);n.playing=!1;try{return n.setup(e.root.engine,t),{prepare:n.prepareDeformation,dispose:()=>n.dispose()}}catch(e){throw n.dispose(),e}},this.name=`animation:`+e.name,this.validate(),this.joints=t.skeleton??e,this.rest=e.nodes.map(e=>{let t=e.engine.store.transforms,n=e.id;return{position:[t.x[n],t.y[n],t.z[n]],scale:[t.sx[n],t.sy[n],t.sz[n]],rotation:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]]}});let n=h(e.asset.doc),r=[];this.clips=(t.skeleton?[]:n.animations).map((i,a)=>{let o=y(i),s=o.name??String(a),c=t.pointers?t.pointers(e,o,s):xe(e,o,s);r.push(...c.warnings);let l=/* @__PURE__ */ new Set,u=(t,r,i)=>{if(b(n.nodes[t]).matrix)throw TypeError(`Invalid animation target; glTF animations cannot drive a node that has a matrix, give it translation/rotation/scale`);let a=t+`:`+r;if(l.has(a))throw RangeError(`Duplicate animation target; give each node and path (translation, rotation, scale, weights) one channel per animation`);l.add(a);let s=g(o.samplers[f(i,o.samplers.length,`sampler`)]),c=e.asset.accessor(s.input,`SCALAR`),u=v(s.interpolation),d=!0;for(let e=0;e<c.length&&d;e++)d=!(c[e]<0||e>0&&c[e]<=c[e-1]);if(!d)throw RangeError(`Invalid animation time/interpolation; keyframe times must be >= 0 and strictly increasing`);if(x(n,s.input)?.componentType!==5126||x(n,s.output)?.componentType!==5126)throw TypeError(`Animation accessors must be Float32; re-export the glTF without quantised animation data`);let p=this.groupStart[t]<this.groupStart[t+1]?this.groupItems[this.groupStart[t]]:-1,m=p<0?void 0:e.primitives[p].weights.length,h=r===`rotation`?4:r===`weights`?m??0:3;if(!h)throw TypeError(`Animation target has no morph weights; animate weights only on a node whose mesh has morph targets`);let _=e.asset.accessor(s.output,r===`weights`?`SCALAR`:r===`rotation`?`VEC4`:`VEC3`),y=u===`CUBICSPLINE`?3:1;if(_.length!==c.length*h*y)throw RangeError(`Animation output count mismatch; the output accessor needs one value per key (three per key for CUBICSPLINE)`);return{node:t,path:r,times:c,values:_,width:h,interpolation:u,sample:new Float32Array(h),...r===`rotation`?{rotation:[0,0,0,1]}:{},cursor:0}},d=c.ordinary.map(t=>{let n=_(t);return u(f(n.target.node,e.nodes.length,`node`),p(n.target.path),n.sampler)});for(let e of c.nodes)d.push(u(e.node,e.path,e.sampler));return{name:o.name??`Animation `+a,duration:Math.max(c.duration,...d.map(e=>e.times.at(-1))),tracks:d,...c.bind?{bind:c.bind}:{}}}),this.warnings=r}static attach(e,t={}){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let n=new o(e,t),r=e.root.engine;return r.use(n,r.sceneOf(e)??e.root.scene),n}validate(){this.groupPrimitives(),this.checkWidths(),this.checkOptions()}groupPrimitives(){let e=this.model.primitives,t=new Int32Array(this.model.nodes.length+1),n=new Int32Array(e.length);for(let n of e)t[n.nodeIndex+1]++;for(let e=0;e<t.length-1;e++)t[e+1]+=t[e];let r=t.slice(0,-1);e.forEach((e,t)=>n[r[e.nodeIndex]++]=t),this.groupStart=t,this.groupItems=n}grouped(){let e=this.model.primitives,t=this.groupStart,n=this.groupItems;if(e.length!==n.length||t.length!==this.model.nodes.length+1)return!1;for(let r=0;r+1<t.length;r++)for(let i=t[r];i<t[r+1];i++)if(e[n[i]]?.nodeIndex!==r)return!1;return!0}checkWidths(){let e=this.model.primitives,t=this.groupStart,n=this.groupItems;for(let r=0;r+1<t.length;r++)for(let i=t[r]+1;i<t[r+1];i++)if(e[n[i]].weights.length!==e[n[t[r]]].weights.length)throw RangeError(`Morph target counts must match across a node's primitives; give every primitive of the mesh the same targets`)}checkFrame(){this.grouped()||this.groupPrimitives(),this.checkWidths(),this.checkOptions()}checkOptions(){if(this.options.loop!==void 0&&typeof this.options.loop!=`boolean`||!Number.isFinite(this.options.speed??1)||(this.options.speed??1)<0)throw RangeError(`Invalid animation options; loop must be a boolean and speed a finite number >= 0`);let e=this.options.skeleton;if(e!==void 0&&e.nodes?.length!==this.model.nodes.length)throw TypeError(`Invalid skeleton option; pass a model of the same file, with the same nodes`);let t=this.options.skinning;if(t!==void 0&&(typeof t?.shader!=`function`||typeof t.encode!=`function`))throw TypeError(`Invalid skinning option; pass dualQuaternionSkinning from @margoengine/animation/dqs`);if(this.options.pointers!==void 0&&typeof this.options.pointers!=`function`)throw TypeError(`Animation pointers option must be pointerChannels; import it from @margoengine/animation/pointer`)}play(e=0){if(this.disposed)throw new C(`disposed`,`Animation is disposed; create a new Animation`);let t=typeof e==`string`?this.clips.findIndex(t=>t.name===e):e;if(!Number.isInteger(t)||t<0||t>=this.clips.length)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);for(let[e,t]of this.rest.entries())this.model.nodes[e].setPosition(t.position).setScale(t.scale).setQuaternion(t.rotation);return this.clip=t,this.time=0,this.playing=!0,this.apply(0),this}captureState(){if(this.disposed)throw new C(`disposed`,`Cannot capture a disposed Animation; use a live player`);return{version:1,clip:this.clip,time:this.time,playing:this.playing,loop:this.options.loop??!0,speed:this.options.speed??1}}restoreState(e){if(this.disposed||!e||e.version!==1||!Number.isInteger(e.clip)||e.clip<0||e.clip>=Math.max(1,this.clips.length)||!Number.isFinite(e.time)||e.time<0||typeof e.playing!=`boolean`||typeof e.loop!=`boolean`||!Number.isFinite(e.speed)||e.speed<0)throw new C(`state`,`Invalid Animation state; restore a snapshot of this model`);return this.clip=e.clip,this.options.loop=e.loop,this.options.speed=e.speed,this.seek(e.time),this.playing=e.playing,this}seek(e){if(!Number.isFinite(e)||e<0||this.disposed)throw RangeError(`Invalid animation time; seek to a finite time >= 0 on a live Animation`);return this.time=e,this.apply(e),this}setMorph(e,t,n=NaN){if(typeof e==`string`){let n=[];for(let t of this.model.primitives)for(let r=0;r<t.targetNames.length;r++)t.targetNames[r]===e&&r<t.weights.length&&n.push([t,r]);if(!n.length||!Number.isFinite(Math.fround(t))||this.disposed)throw this.morphError(`name ${JSON.stringify(e)}`);for(let[e,r]of n)e.weights[r]=t;return}let r=this.model.primitives,i=!1,a=Number.isInteger(t)&&t>=0;for(let n=0;n<r.length;n++)r[n].nodeIndex===e&&(i=!0,t>=r[n].weights.length&&(a=!1));if(!i||!a||!Number.isFinite(Math.fround(n))||this.disposed)throw this.morphError(`node ${e}, target ${t}`);for(let i=0;i<r.length;i++)r[i].nodeIndex===e&&(r[i].weights[t]=n)}morphError(t){let n=/* @__PURE__ */ new Map;for(let e of this.model.primitives)e.weights.length&&n.set(e.nodeIndex,e.weights.length);return e(`Invalid morph target/weight; pass a morph target index the node has and a finite weight, on a live Animation; requested ${t}; available `+([...n].map(([e,t])=>`node ${e}: ${t} targets`).join(`, `)||`no morphed nodes`),`geometry`)}apply(e){this.due=!1;let t=this.clips[this.clip];if(!t)return;let n=(this.options.loop??!0)&&t.duration>0?e%t.duration:Math.min(e,t.duration);this.grouped()||this.groupPrimitives();for(let e=0;e<t.tracks.length;e++){let r=t.tracks[e],i=a(r,n,r.path===`rotation`,r.sample),o=this.model.nodes[r.node];if(r.path===`translation`)o.position.set(i[0],i[1],i[2]);else if(r.path===`scale`)o.scale.set(i[0],i[1],i[2]);else if(r.path===`rotation`){if(i.length!==4)o.setQuaternion(Array.from(i));else{for(let e=0;e<4;e++)this.quaternion[e]=i[e];o.setQuaternion(this.quaternion)}}else{o.check();let e=this.model.primitives,t=this.groupItems;for(let n=this.groupStart[r.node];n<this.groupStart[r.node+1];n++)e[t[n]].weights.set(i)}}t.bind&&d(t.bound??=t.bind(),n)}setup(e,r=e.gpu){if(e!==this.model.root.engine||this.model.disposed||this.disposed)throw new C(`attached`,`Animation model is disposed or belongs to another engine; attach the Animation to the engine that loaded the model`);if(!r)throw new C(`unsupported`,`Animation requires WebGPU; use a browser with WebGPU or leave skinning and morphing out; see https://margoengine.com/errors#webgpu`);this.device=r,this.unsubscribe?.(),this.unsubscribe=this.model.onDispose(()=>this.destroy());let i=this.arena=he.of(r),a=[],o=[],s=h(this.model.asset.doc);for(let e of this.model.primitives){let n=S(e.definition),r=n.targets,i=b(s.nodes[e.nodeIndex]).skin,c=typeof i==`number`?s.skins[i]:void 0;if(i!==void 0&&(typeof i!=`number`||!Number.isInteger(i)||i<0||!c))throw TypeError(`Missing glTF skin; the node must reference a skin index that exists in the glTF skins array`);if(!r.length&&i===void 0)continue;let l=e.vertices.length/20,u=Ne(e),d=this.model.asset,f=e.part?.vertexMap,p=f?d.accessor(n.attributes.POSITION,`VEC3`).length/3:l;if(l*r.length*48>this.device.limits.maxStorageBufferBindingSize)throw RangeError(`Morph deltas exceed device limit; reduce the vertex or morph target count`);for(let e of r)for(let t of je)if(e[t]!==void 0&&d.accessor(e[t],`VEC3`).length!==p*3)throw RangeError(`Morph target count mismatch; every morph attribute needs one VEC3 per vertex`);let h=J,g=[],_=n.attributes,v=i!==void 0&&(_.JOINTS_1!==void 0||_.WEIGHTS_1!==void 0),y=v?16:8,C=/* @__PURE__ */ new Uint32Array(8);if(i!==void 0){let e=m(c,this.model.nodes.length);if(g=e.joints,h=e.inverseBindMatrices===void 0?Se(g.length):this.model.asset.accessor(e.inverseBindMatrices,`MAT4`),e.inverseBindMatrices!==void 0&&x(s,e.inverseBindMatrices)?.componentType!==5126)throw TypeError(`Inverse bind matrices must be Float32; re-export the glTF without quantised matrices`);if(h.length!==g.length*16)throw RangeError(`Inverse bind matrix count mismatch; the skin needs one 4x4 matrix per joint`);let t=g.length;u.influences=()=>Pe(d,s,_,l,p,y,t,f),C=u.influences()}let w=g.length?this.options.skinning?.share?.(s.nodes[e.nodeIndex]?.extras):void 0;if(w){if(w.length!==p)throw RangeError(`Invalid skin share count; the node needs one share per vertex of its primitive`);let e=t(w,1,f);for(let t=0;t<l;t++){if(!(e[t]>=0&&e[t]<=1))throw RangeError(`Invalid skin share; each vertex needs a finite share between 0 and 1`);C[t*y]=C[t*y]&65535|Math.round(e[t]*65535)<<16}}u.joints=g,u.inverseBind=h,r.length&&(u.deltas=()=>Me(d,r,l,f)),g.length||(u.palette=Float32Array.from(q),u.paletteBits=new Uint32Array(u.palette.buffer)),a.push(u),o.push({primitive:e,count:l,targets:r.length,joints:g.length,extra:v,mode:g.length?this.options.skinning:void 0,asset:this.model.asset,definition:e.definition,skin:i,deltas:u.deltas,influences:()=>C.subarray(0,g.length?l*y:0)})}let c=i.add(o);this.slots.push(...c);for(let e of c)i.pipeline(e.extra,e.mode);a.forEach((e,t)=>{e.slot=c[t],e.leader=a.slice(0,t).find(e=>e.slot.bones===c[t].bones&&!e.leader)});let l=a.filter(e=>e.joints.length&&!e.leader).sort((e,t)=>e.slot.bones.offset-t.slot.bones.offset),u=l.reduce((e,t)=>e+t.joints.length*16,0),d=new Float32Array(u),f=new Float32Array(u),p=0;for(let e of l){let t=e.joints.length*16;e.palette=d.subarray(p,p+t),e.spare=f.subarray(p,p+t);for(let n=0;n<t;n+=16)e.palette.set(q,n);e.paletteBits=new Uint32Array(d.buffer,p*4,t),e.spareBits=new Uint32Array(f.buffer,p*4,t),p+=t}if(this.leaders.push(...l),this.wholes=[d,f],this.followLeaders(a),a.forEach((e,t)=>{let n=e.primitive.weights;n.length&&n.byteLength<=R(c[t].targets)*4&&r.queue.writeBuffer(e.weights,c[t].weights.offset*4,n)}),this.resources.push(...a),!this.options.skinning)for(let e of a)n(e.primitive,e.pose=()=>this.cpuPose(e));for(let e of a)this.deformedNodes.includes(e.primitive.node)||this.deformedNodes.push(e.primitive.node);this.model.prepareDeformation=this.prepareDeformation,this.model.createDeformationRenderer=this.createDeformationRenderer}onPreUpdate(e){this.model.disposed?this.model.root.engine.sceneOf(this)?.removePlugin(this.name):(this.checkFrame(),this.advanceTime(e),this.due&&this.apply(this.time))}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!this.playing||this.disposed)return;this.time+=e*(this.options.speed??1);let t=this.clips[this.clip]?.duration??0;(this.options.loop??!0)&&t>0&&(this.time%=t),this.due=!0,this.options.loop===!1&&this.time>=(this.clips[this.clip]?.duration??1/0)&&(this.playing=!1)}registerPasses(e){let t=Ae.get(e);t||Ae.set(e,t={members:/* @__PURE__ */ new Set,ran:0,cache:Q()}),t.members.add(this),this.group=t,e.add({name:this.name,order:-10,execute:e=>this.deformAll(e)})}deformAll(e){let t=this.group;if(!t||e.backend!==`webgpu`)return this.deform(e);let n=t.ran===0;if(t.ran=t.ran+1>=t.members.size?0:t.ran+1,n)try{let n=[];for(let r of t.members)r.upload(e)&&n.push(r);if(!n.length)return;let r=e.encoder.beginComputePass();try{n[0].arena.dispatches(n,ke,t.cache).forEach(e=>$(r,e))}finally{r.end()}}catch(e){throw t.ran=0,e}}deform(e){if(!this.upload(e))return;let t=e.encoder.beginComputePass();try{this.arena.dispatches([this],ke,this.cache).forEach(e=>$(t,e))}finally{t.end()}}upload(e){if(e.backend!==`webgpu`||this.model.disposed)return!1;let{store:t}=this.model.root.engine,n=i.has(this.model);for(let e=0;!n&&e<this.deformedNodes.length;e++)ne(t,this.deformedNodes[e].id)||(n=!0);if(!n)return!1;let r=this.contiguous();for(let t of this.resources){let n=t.primitive.weights;for(let e=0;e<n.length;e++)if(!Number.isFinite(n[e]))throw RangeError(`Invalid morph weights; set finite weights on the primitive`);if(t.joints.length&&!t.leader){let n=e.device.queue,i=n.writeBuffer,a=X(n,i),o=a&&t.bonesUploaded&&t.bonesQueue===n,s=t.next=o?t.spare:t.palette;if(!w(t.primitive.node.matrix,this.inverse,this.workspace))throw RangeError(`Singular skinned mesh transform; give the skinned node a non-zero scale`);for(let e=0;e<t.joints.length;e++)Te(this.joints.nodes[t.joints[e]].matrix,t.inverseBind,e*16,this.joint),T(this.inverse,this.joint,this.product),s.set(this.product,e*16);for(let e=0;e<s.length;e++)if(!Number.isFinite(s[e]))throw RangeError(`Skin matrix overflow; use finite joint transforms and inverse bind matrices`);this.options.skinning?.encode(s);let c=!o;for(let e=0;!c&&e<t.spareBits.length;e++)t.spareBits[e]!==t.paletteBits[e]&&(c=!0);t.bonesChanged=c,c&&!r&&this.uploadBones(n,i,a,t,s,t.slot.bones.offset)}if(t.primitive.weights.length){let n=t.primitive.weights,r=e.device.queue,i=r.writeBuffer,a=X(r,i),o=t.slot.weights.offset*4;if(n.byteLength>R(t.slot.targets)*4)throw RangeError(`Morph weights longer than the primitive has morph targets; give primitive.weights one value per target`);if(!a||!(n instanceof Float32Array)||!se(n)||n.length!==t.uploadedWeights.length){t.weightsUploaded=!1;try{Z(r,i,t,t.weights,o,n)}finally{t.weightsUploaded=!1}}else{let e=!t.weightsUploaded||t.weightsQueue!==r;for(let r=0;!e&&r<n.length;r++)Object.is(n[r],t.uploadedWeights[r])||(e=!0);e&&(t.weightsUploaded=!1,Z(r,i,t,t.weights,o,n),t.uploadedWeights.set(n),t.weightsQueue=r,t.weightsUploaded=!0)}}}if(r){let t=this.leaders,n=e.device.queue,r=t[0].next.buffer,i=t[0].next.byteOffset===0;for(let e=0;i&&e<t.length;e++)i=t[e].bonesChanged&&t[e].next.buffer===r;if(i){let e=n.writeBuffer,i=t[0];this.uploadBones(n,e,X(n,e),i,this.wholes[0].buffer===r?this.wholes[0]:this.wholes[1],i.slot.bones.offset,t)}else for(let e of t)if(e.bonesChanged){let t=n.writeBuffer;this.uploadBones(n,t,X(n,t),e,e.next,e.slot.bones.offset)}}for(let e of this.leaders)!e.bonesChanged&&e.next===e.spare&&this.swap(e);return this.resources.length>0}cpuPose(e){let t=e.primitive,n=t.weights;if(!t.deformed||t.deformed!==e.slot.page.output.buffer||(t.deformedOffset??0)!==e.slot.output.offset*80||this.gpuWeights&&n.length)return;let r=e.posed??={vertices:J,revision:0,bind:J,influences:e.influences(),deltas:e.deltas(),palette:new Float32Array(e.joints.length*16),weights:new Float32Array(n.length)},i=r.bind!==t.vertices;if(i&&(r.bind=t.vertices,r.vertices=new Float32Array(t.vertices.length)),e.joints.length&&!w(t.node.matrix,this.inverse,this.workspace))throw RangeError(`Singular skinned mesh transform; give the skinned node a non-zero scale`);for(let t=0;t<e.joints.length;t++){Te(this.joints.nodes[e.joints[t]].matrix,e.inverseBind,t*16,this.joint),T(this.inverse,this.joint,this.product);for(let e=0;e<16;e++)Object.is(r.palette[t*16+e],this.product[e])||(r.palette[t*16+e]=this.product[e],i=!0)}for(let e=0;e<r.weights.length;e++)Object.is(r.weights[e],Math.fround(n[e]))||(r.weights[e]=n[e],i=!0);return i&&(re(r.bind,r.vertices,r.deltas,r.weights,r.influences,e.slot.extra?16:8,r.palette),r.revision++),r}contiguous(){let e=this.leaders;if(e.length<2)return!1;let t=e[0],n=t.slot.page,r=t.slot.bones.offset+t.joints.length;for(let t=1;t<e.length;t++){let i=e[t];if(i.slot.page!==n||i.slot.bones.offset!==r)return!1;r+=i.joints.length}return(r-t.slot.bones.offset)*64===this.wholes[0].byteLength}swap(e){let t=e.palette,n=e.paletteBits;e.palette=e.spare,e.spare=t,e.paletteBits=e.spareBits,e.spareBits=n,this.followLeaders(this.resources)}uploadBones(e,t,n,r,i,a,o=[r]){let s=!1;for(let e of o)e.bonesUploaded=!1;try{if(Z(e,t,r,r.bones,a*64,i),n){for(let t of o)t.next===t.spare&&this.swap(t),t.bonesQueue=e;s=!0}}finally{for(let e of o)e.bonesUploaded=s}}followLeaders(e){for(let t of e)t.leader&&(t.palette=t.leader.palette,t.paletteBits=t.leader.paletteBits,t.spare=t.leader.spare,t.spareBits=t.leader.spareBits)}release(){if(this.model.createDeformationRenderer===this.createDeformationRenderer&&(this.model.createDeformationRenderer=void 0),this.model.prepareDeformation===this.prepareDeformation&&(this.model.prepareDeformation=void 0),this.arena){this.arena.drop(this.cache),this.group&&this.arena.drop(this.group.cache);for(let e of this.slots)this.arena.remove(e)}for(let e of this.resources)e.pose&&r(e.primitive,e.pose);this.resources=[],this.leaders=[],this.deformedNodes=[],this.slots=[],this.arena=void 0}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.model.root.engine.sceneOf(this)?.removePlugin(this.name),this.unsubscribe?.(),this.unsubscribe=void 0,this.release(),this.group?.members.delete(this),this.group=void 0,this.device=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}destroy(){this.dispose()}};export{_e as i,be as n,ve as r,Fe as t};
@@ -0,0 +1,50 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{t as e}from"./errors-t1ewumJS.js";import{t}from"./vertex-map-BC_WH7ER.js";import{t as n}from"./require-webgpu-Jrqt3Xy4.js";import{n as r,t as i}from"./hdr-format-cmvLFubB.js";import{MargoError as a}from"@margoengine/math/errors";import{invertMatrixStable as o,multiplyMatrices as s}from"@margoengine/math/mat4";var c=`fn pbrNeutral(input:vec3f)->vec3f {let x=min(input.r,min(input.g,input.b));let offset=select(0.04,x-6.25*x*x,x<0.08);var v=input-offset;let peak=max(v.r,max(v.g,v.b));if(peak<0.76){return v;}let newPeak=1.0-0.24*0.24/(peak+0.24-0.76);v*=newPeak/peak;return mix(v,vec3f(newPeak),1.0-1.0/(0.15*(peak-newPeak)+1.0));}
5
+ `;`${c}`;var l=/* @__PURE__ */ new WeakMap;function u(e,t){let n=l.get(t),r=n?.get(e);return r===void 0?m(e,t,n):r}var d=/mix\(vec3f\(0\.35,0\.3,0\.25\),vec3f\(1(?:\.0)?\),clamp\(([\w.]+)\.y\*0\.5\+0\.5,0\.0,1\.0\)\)/g,f=e=>e.replace(d,`margoSkyHook($1)`).replaceAll(`*f.radiance.w`,``),p=e=>e!==void 0&&new RegExp(d.source).test(e);function m(t,n,r){let i=e=>e&&(t.includes(` f0:vec3f`)?e:e.replaceAll(`s.f0`,`vec3f(0.04)`)).replaceAll(`s.sw`,t.includes(` sw:f32`)?`s.sw`:`1.0`),a=t,o=(t,n)=>{if(typeof t==`string`?!a.includes(t):a.search(t)<0)throw e(`unsupported`,`PBR lighting hook point missing: ${t}; use matching @margoengine/gltf/pbr and effect package versions`);a=a.replace(t,n)},s=t.includes(`fn margoAmbientLayers(`);if(n.direct){let e=n.direct(`direct`,t.includes(`fn margoLightSide(`)?`margoLightSide(s.n,l)`:void 0);if(t.includes(`var<private> margoDirectVisible:vec3f=vec3f(1);`)&&e!==`direct`){let n=t.includes(`fn margoLit(`)?`margoLit(s,l,direct)`:`vec3f(1)`;o(/(?:let margoAmbient=[^;]*;)?var color=/,t=>`{let direct=${n};margoDirectVisible=${e};}\n ${t}`),o(`direct+ambient(s)`,`direct*margoDirectVisible+ambient(s)`)}else o(`direct+ambient(s)`,e+`+ambient(s)`)}if(n.light){if(s){let e=a.split(`fn margoLocal`).length-1;o(`var color=`,`var color=margoLocal${e}(i,margoFront(s),v)+`),a+=`\nfn margoLocal${e}(i:Out,s:Surface,v:vec3f)->vec3f {return ${i(n.light)};}\n`}else o(`var color=`,`var color=`+i(n.light)+`+`)}let c=a.includes(`fn margoSkyHook(`);n.ambient&&((!c||p(n.ambient))&&o(/fn ambient\(s:Surface\)->vec3f \{[^}]*\}/,`fn ambient(s:Surface)->vec3f {return vec3f(0);}`),s&&o(`fn margoAmbientTerm(i:Out,s:Surface,v:vec3f)->vec3f {return vec3f(0);}`,()=>`fn margoAmbientTerm(i:Out,s:Surface,v:vec3f)->vec3f {return ${i(n.ambient)};}`),o(/var color=([^;]+)\+s\.emissive;/,(e,t)=>`let margoAmbient=${s?`margoAmbientLayers(i,s,v)`:i(n.ambient)};var color=${t}+s.emissive+margoAmbient;`));for(let[e,t]of[[`margoCoatAmbient`,n.coat],[`margoSheenAmbient`,n.sheen]])t&&a.includes(`fn ${e}(`)&&o(RegExp(`fn ${e}\\(s:Surface,v:vec3f\\)->vec3f \\{return [^;]*;\\}`),()=>`fn ${e}(s:Surface,v:vec3f)->vec3f {return ${t};}`);if(n.sky){if(c)throw e(`unsupported`,`Two sky lighting hooks on one shader; attach one HemisphereLight per engine`);let t=/let margoAmbient=([^;]*);/.exec(a)?.[1],r=/fn margoAmbientTerm\(i:Out,s:Surface,v:vec3f\)->vec3f \{return ([^;]*);\}/.exec(a)?.[1];t!==void 0&&!p(t)&&!p(r)&&o(`fn ambient(s:Surface)->vec3f {return vec3f(0);}`,`fn ambient(s:Surface)->vec3f {${a.includes(`fn margoHemisphere(`)?`return margoHemisphere(s);`:a.includes(`fn hemisphere_ambient(`)?`return hemisphere_ambient(s);`:`let f0=mix(vec3f(0.04),s.base.rgb,s.metal);return (s.base.rgb*(1.0-s.metal)+f0*0.5)*margoSkyHook(s.n)*s.occlusion;`}}`),a+=`
6
+ fn margoSkyHook(n:vec3f)->vec3f {return ${n.sky};}
7
+ `}(n.sky||c)&&(a=f(a));let u=`if(f.settings.w<0.5) {color=toDisplay(color);}`;if(n.output){let e=a.includes(u);o(e?u:`if(f.settings.w<0.5) {color=pbrNeutral(max(color,vec3f(0)));`,`color=${n.output(`select(color,pbrNeutral(max(color,vec3f(0))),f.settings.w<0.5)`)};if(f.settings.w<0.5) {${e?`color=select(color*12.92,1.055*pow(color,vec3f(1.0/2.4))-0.055,color>=vec3f(0.0031308));}`:``}`)}return a=n.declarations+a,n.finish&&(a=n.finish(a)),r||l.set(n,r=/* @__PURE__ */ new Map),r.size>=64&&r.clear(),r.set(t,a),a}var h=(e,t)=>`a2/(3.14159265*pow(max(dot(cross(${e},${t}),cross(${e},${t})),step(nh,0.0))+a2*nh*nh,2.0))`,g=`2.0*nl*nv/max(nl*sqrt(a2+(1.0-a2)*nv*nv)+nv*sqrt(a2+(1.0-a2)*nl*nl),1e-30)`;function _(e,t,n){let r=Math.hypot(n[0],n[1],n[2]);e[t]=n[0]/r,e[t+1]=n[1]/r,e[t+2]=n[2]/r,e[t+3]=n[3]}var v=2048;function y(e,t,n,r,i=v){let a=(e*r+t)*2+n;return[a%i,Math.floor(a/i)]}function b(e,{fps:n=30,clips:r}={}){let i=e.model,a=i.asset.doc,c=i.root.engine.store,l=i.asset,u=(r??e.clips.map((e,t)=>t)).map(t=>typeof t==`string`?e.clips.findIndex(e=>e.name===t):t);if(!(n>0&&n<=1e3)||!u.length||u.some(t=>!e.clips[t]))throw RangeError(`Invalid VAT fps or clips; pass fps in (0, 1000] and clip indices that exist in animation.clips`);let d=i.primitives.map(e=>{let n=e.definition,r=a.nodes[e.nodeIndex].skin===void 0?null:a.skins[a.nodes[e.nodeIndex].skin],i=r?.joints??[],o=e.part?.vertexMap;return{p:e,count:e.vertices.length/20,joints:i,deltas:(n.targets??[]).map(e=>[e.POSITION,e.NORMAL].map(e=>e===void 0?null:t(l.accessor(e,`VEC3`),3,o))),bind:r?.inverseBindMatrices===void 0?new Float32Array(i.length*16).map((e,t)=>+(t%16%5==0)):l.accessor(r.inverseBindMatrices,`MAT4`),ids:r?t(l.accessor(n.attributes.JOINTS_0,`VEC4`),4,o):null,weights:r?t(l.accessor(n.attributes.WEIGHTS_0,`VEC4`),4,o):null,palette:new Float32Array(Math.max(1,i.length)*16)}}),f=d.reduce((e,t)=>e+t.count,0),p=u.map(t=>Math.max(1,Math.ceil(e.clips[t].duration*n))),m=p.reduce((e,t)=>e+t+1,0),h=Math.ceil(m*f*2/v);if(h>8192)throw RangeError(`VAT data exceeds 8192 texture rows; bake fewer clips, a lower fps or a lighter mesh`);let g=new Float32Array(v*h*4),_=new Float32Array(f*2),y=[];for(let e=0,t=0;e<d.length;t+=d[e++].count){let n=d[e].p.vertices;for(let r=0;r<d[e].count;r++)_[(t+r)*2]=n[r*20+12],_[(t+r)*2+1]=1-n[r*20+13];for(let n of d[e].p.indices)y.push(t+n)}let b={clip:e.clip,time:e.time,playing:e.playing},x=/* @__PURE__ */ new Float32Array(16),S=/* @__PURE__ */ new Float32Array(16),C=/* @__PURE__ */ new Float64Array(12),w=/* @__PURE__ */ new Float64Array(52),T=0;try{u.forEach((t,n)=>{let r=e.clips[t].duration;e.play(t);for(let t=0;t<=p[n];t++,T++){if(e.seek(r*t/p[n]),c.tick(!1),!o(i.root.matrix,x,w))throw RangeError(`Singular VAT model root; give the model root a non-zero scale before baking`);let a=T*f*8;for(let e of d){let{p:t,joints:n,palette:r,ids:o,weights:c}=e,l=t.vertices;if(n.length)for(let t=0;t<n.length;t++)s(i.nodes[n[t]].matrix,e.bind.subarray(t*16,t*16+16),S),s(x,S,r.subarray(t*16,t*16+16));else s(x,t.node.matrix,r);for(let n=0;n<e.count;n++,a+=8){let i=l[n*20],s=l[n*20+1],u=l[n*20+2],d=l[n*20+4],f=l[n*20+5],p=l[n*20+6];for(let r=0;r<e.deltas.length;r++){let[a,o]=e.deltas[r],c=t.weights[r];a&&(i+=a[n*3]*c,s+=a[n*3+1]*c,u+=a[n*3+2]*c),o&&(d+=o[n*3]*c,f+=o[n*3+1]*c,p+=o[n*3+2]*c)}if(o){C.fill(0);let e=c[n*4]+c[n*4+1]+c[n*4+2]+c[n*4+3];for(let t=0;t<4;t++){let i=o[n*4+t]*16,a=c[n*4+t]/e;for(let e=0;e<12;e++)C[e]+=r[i+e+(e/3|0)]*a}}else for(let e=0;e<12;e++)C[e]=r[e+(e/3|0)];let m=C[0]*i+C[3]*s+C[6]*u+C[9],h=C[1]*i+C[4]*s+C[7]*u+C[10],_=C[2]*i+C[5]*s+C[8]*u+C[11],v=C[4]*C[8]-C[5]*C[7],y=C[5]*C[6]-C[3]*C[8],b=C[3]*C[7]-C[4]*C[6],x=C[7]*C[2]-C[8]*C[1],S=C[8]*C[0]-C[6]*C[2],w=C[6]*C[1]-C[7]*C[0],T=C[1]*C[5]-C[2]*C[4],E=C[2]*C[3]-C[0]*C[5],D=C[0]*C[4]-C[1]*C[3],O=C[0]*v+C[1]*y+C[2]*b<0?-1:1,k=(v*d+x*f+T*p)*O,A=(y*d+S*f+E*p)*O,j=(b*d+w*f+D*p)*O,M=Math.hypot(k,A,j);g[a]=m,g[a+1]=h,g[a+2]=_,g[a+3]=1,g[a+4]=M>0?k/M:0,g[a+5]=M>0?A/M:1,g[a+6]=M>0?j/M:0}}}})}finally{e.play(b.clip),e.seek(b.time),e.playing=b.playing,c.tick(!1)}for(let e=0;e<m*f*8;e++)if(!Number.isFinite(g[e]))throw RangeError(`VAT bake produced non-finite vertices (check skin weights)`);let E=0;return{vertexCount:f,rows:m,width:v,texels:g,indices:Uint32Array.from(y),uvs:_,clips:u.map((t,n)=>{let r={name:e.clips[t].name,start:E,frames:p[n],duration:e.clips[t].duration,loop:e.options.loop??!0};return E+=p[n]+1,r})}}var x=24,S=`
8
+ struct Frame {camera:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,base:vec4f,options:vec4f,vat:vec4f}
9
+ struct Instance {m:mat4x4f,p:vec4f,uv:vec4f}
10
+ @group(0) @binding(0) var<uniform> f:Frame;
11
+ @group(0) @binding(1) var<storage,read> instances:array<Instance>;
12
+ @group(0) @binding(2) var<storage,read> clips:array<vec4f>;
13
+ @group(0) @binding(3) var vat:texture_2d<f32>;
14
+ @group(0) @binding(4) var map:texture_2d<f32>;
15
+ @group(0) @binding(5) var mapSampler:sampler;
16
+ struct Out {@builtin(position) @invariant clip:vec4f,@location(0) position:vec3f,@location(1) normal:vec3f,@location(2) uv:vec2f}
17
+ fn texel(row:u32,v:u32,k:u32)->vec4f {let i=(row*u32(f.vat.x)+v)*2u+k;let w=u32(f.vat.y);return textureLoad(vat,vec2u(i%w,i/w),0);}
18
+ @vertex fn vertex(@location(0) uv:vec2f,@builtin(vertex_index) v:u32,@builtin(instance_index) id:u32)->Out {
19
+ let s=instances[id];let c=clips[u32(s.p.x)];var t=(f.options.x*s.p.z+s.p.y)/max(c.z,0.000001);
20
+ t=select(clamp(t,0.0,1.0),fract(t),c.w>0.5);let x=t*c.y;let a=min(floor(x),c.y-1.0);let w=x-a;let r=u32(c.x+a);
21
+ let p=mix(texel(r,v,0u),texel(r+1u,v,0u),w).xyz;let n=mix(texel(r,v,1u),texel(r+1u,v,1u),w).xyz;
22
+ let m=s.m;let c0=cross(m[1].xyz,m[2].xyz);let world=m*vec4f(p,1.0);
23
+ var o:Out;o.clip=f.camera*world;o.position=world.xyz;let bent=mat3x3f(c0,cross(m[2].xyz,m[0].xyz),cross(m[0].xyz,m[1].xyz))*n*select(-1.0,1.0,dot(m[0].xyz,c0)>=0.0);o.normal=select(vec3f(0,1,0),bent,dot(bent,bent)>0.0);o.uv=s.uv.xy+uv*s.uv.zw;return o;
24
+ }
25
+ `,C=`fn srgb(c:vec3f)->vec3f {let x=clamp(c,vec3f(0.0),vec3f(1.0));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}
26
+ `,w=e=>`${c}${e}${C}
27
+ @fragment fn fragment(i:Out,@builtin(front_facing) front:bool)->@location(0) vec4f {
28
+ let albedo=(f.base*textureSample(map,mapSampler,i.uv)).rgb;let rough=f.options.z;let metal=f.options.w;
29
+ let nn=normalize(i.normal)*select(-1.0,1.0,front);let v=normalize(f.eye.xyz-i.position);let l=f.light.xyz;let h=(v+l)/max(length(v+l),0.0001);
30
+ let nl=clamp(dot(nn,l),0.0,1.0);let nv=clamp(dot(nn,v),0.0001,1.0);let nh=clamp(dot(nn,h),0.0,1.0);let vh=clamp(dot(v,h),0.0,1.0);
31
+ let a=rough*rough;let a2=a*a;let d=${/* @__PURE__ */ h(`nn`,`h`)};let g=${g};
32
+ let f0=mix(vec3f(0.04),albedo,metal);let fresnel=f0+(1.0-f0)*pow(1.0-vh,5.0);
33
+ var color=((1.0-(0.04+0.96*pow(1.0-vh,5.0)))*(1.0-metal)*albedo/3.14159265+d*g*fresnel/max(4.0*nl*nv,0.0001))*nl*f.radiance.rgb*f.light.w
34
+ +(albedo*(1.0-metal)+f0*0.5)*mix(vec3f(0.35,0.3,0.25),vec3f(1.0),clamp(nn.y*0.5+0.5,0.0,1.0))*f.radiance.w;
35
+ if(f.vat.z<0.5){color=srgb(pbrNeutral(max(color,vec3f(0.0))));}
36
+ return vec4f(color,1.0);
37
+ }`,T=w(S),E=/* @__PURE__ */ new Map,D=e=>`${c}${e.replace(`vat:vec4f}`,`settings:vec4f}`).replaceAll(`f.vat.`,`f.settings.`)}${C}
38
+ struct Surface {base:vec4f,n:vec3f,roughness:f32,metal:f32,occlusion:f32,emissive:vec3f}
39
+ fn ambient(s:Surface)->vec3f {let f0=mix(vec3f(0.04),s.base.rgb,s.metal);return (s.base.rgb*(1.0-s.metal)+f0*0.5)*mix(vec3f(0.35,0.3,0.25),vec3f(1.0),clamp(s.n.y*0.5+0.5,0.0,1.0))*f.radiance.w*s.occlusion;}
40
+ @fragment fn fragment(i:Out,@builtin(front_facing) front:bool)->@location(0) vec4f {
41
+ var s:Surface;s.base=f.base*textureSample(map,mapSampler,i.uv);s.n=normalize(i.normal)*select(-1.0,1.0,front);s.roughness=f.options.z;s.metal=f.options.w;s.occlusion=1.0;
42
+ let v=normalize(f.eye.xyz-i.position);let l=f.light.xyz;let h=(v+l)/max(length(v+l),0.0001);
43
+ let nl=clamp(dot(s.n,l),0.0,1.0);let nv=clamp(dot(s.n,v),0.0001,1.0);let nh=clamp(dot(s.n,h),0.0,1.0);let vh=clamp(dot(v,h),0.0,1.0);
44
+ let a=s.roughness*s.roughness;let a2=a*a;let d=${/* @__PURE__ */ h(`s.n`,`h`)};let g=${g};
45
+ let f0=mix(vec3f(0.04),s.base.rgb,s.metal);let fresnel=f0+(1.0-f0)*pow(1.0-vh,5.0);
46
+ let direct=((1.0-(0.04+0.96*pow(1.0-vh,5.0)))*(1.0-s.metal)*s.base.rgb/3.14159265+d*g*fresnel/max(4.0*nl*nv,0.0001))*nl*f.radiance.rgb*f.light.w;
47
+ var color=direct+ambient(s)+s.emissive;
48
+ if(f.settings.w<0.5) {color=pbrNeutral(max(color,vec3f(0))); color=srgb(color);}
49
+ return vec4f(color,1.0);
50
+ }`;function O(e){let t=E.get(e);return t||E.set(e,t=D(e)),t}var k=0,A=class e{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,{color:t=[1,1,1,1],map:n=null,roughness:r=.6,metalness:i=0}={},a={vertex:S,stride:24,rowSize:e?.vertexCount,vertices:[],attributes:[]}){if(this.vat=e,this.layout=a,this.name=`vat:`+k++,this.time=0,this.disposed=!1,this.n=0,this.dirty=!0,this.key=``,this.bound=[],this.frame=/* @__PURE__ */ new Float32Array(40),this.lighting=/* @__PURE__ */ new Set,!(e?.texels instanceof Float32Array)||!e.clips?.length||t.length!==4||!(r>=0&&r<=1&&i>=0&&i<=1))throw TypeError(`Invalid VAT crowd; pass baked VAT data with clips, a 4-number color, and roughness and metalness in 0..1`);this.color=[...t],this.roughness=r,this.metalness=i,this.map=n,this.data=new Float32Array(a.stride*16),this.plain=this.code=a.vertex===S?T:w(a.vertex)}get rows(){return this.data}get count(){return this.n}add(e={}){let t=this.layout.stride;if(this.n*t===this.data.length){let e=new Float32Array(this.data.length*2);e.set(this.data),this.data=e}this.data.fill(0,this.n*t,(this.n+1)*t),this.data.set([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1,1],this.n*t),t>24&&(this.data[this.n*t+24+2]=1),this.n++;try{this.set(this.n-1,e)}catch(e){throw this.n--,e}return this.n-1}set(e,{matrix:t,clip:n,offset:r,speed:i,uvTransform:a}){if(!(Number.isInteger(e)&&e>=0&&e<this.n)||n!==void 0&&!(Number.isInteger(n)&&n>=0&&n<this.vat.clips.length)||t!==void 0&&t.length!==16)throw RangeError(`Invalid VAT instance; use an index below the instance count, a clip from vat.clips, a 16-number matrix and finite values`);let o=this.layout.stride,s=e*o,c=this.data;t&&c.set(t,s),n!==void 0&&(c[s+16]=n),r!==void 0&&(c[s+17]=r),i!==void 0&&(c[s+18]=i),a&&(c.set(a.offset??[0,0],s+20),c.set(a.scale??[1,1],s+22));for(let e=s;e<s+o;e++)if(!Number.isFinite(c[e]))throw RangeError(`Invalid VAT instance; use an index below the instance count, a clip from vat.clips, a 16-number matrix and finite values`);return this.dirty=!0,this}truncate(e){if(!(Number.isInteger(e)&&e>=0&&e<=this.n))throw RangeError(`Invalid VAT count; truncate to an integer from 0 to the current count`);this.n=e}setup(e){if(this.disposed)throw new a(`disposed`,`VATCrowd is disposed; create a new crowd before attaching`);n(e,`VATCrowd`),this.engine=e}onPreUpdate(e){this.advanceTime(e)}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid VAT delta; pass finite seconds >= 0`);this.disposed||(this.time+=e)}registerPasses(e){e.add({name:this.name,order:1,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}resources(e){if(this.device===e&&this.gpu)return this.gpu;this.release(),this.device=e;let t=this.vat,n=(t,n)=>{let r=e.createBuffer({size:Math.max(16,t.byteLength),usage:n|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(r,0,t),r},r=e.createTexture({size:[t.width,t.texels.length/t.width/4],format:`rgba32float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});e.queue.writeTexture({texture:r},t.texels,{bytesPerRow:t.width*16},[t.width,t.texels.length/t.width/4]);let i=e.createTexture({size:[1,1],format:`rgba8unorm`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});return e.queue.writeTexture({texture:i},new Uint8Array([255,255,255,255]),{bytesPerRow:4},[1,1]),this.gpu={vat:r,white:i,blank:[i.createView(),e.createSampler()],uvs:n(t.uvs,GPUBufferUsage.VERTEX),vertices:this.layout.vertices.map(e=>n(e,GPUBufferUsage.VERTEX)),index:n(t.indices,GPUBufferUsage.INDEX),frame:e.createBuffer({size:160,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),clips:n(Float32Array.from(t.clips.flatMap(e=>[e.start,e.frames,e.duration,+e.loop])),GPUBufferUsage.STORAGE)}}addLighting(e){if(this.disposed||!e||typeof e.pbr!=`function`||typeof e.bindings!=`function`)throw TypeError(`VAT crowd lighting needs a live crowd and an effect with pbr() and bindings() functions`);if(e.owner&&this.engine&&e.owner!==this.engine)throw new a(`attached`,`VAT lighting belongs to another engine; use an effect created on the crowd's engine`);return this.lighting.add(e),()=>{this.lighting.delete(e)}}drawShadow({context:e,pass:t,matrix:n,cascade:r}){if(!this.n||!this.engine)return;let i=e.device,a=this.upload(i),o=this.shadow;if(!o){let e=i.createShaderModule({code:this.layout.vertex});o=this.shadow={pipeline:i.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vertex`,buffers:this.vertexLayout()},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`less-equal`}}),frames:i.createBuffer({size:1024,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),groups:[],values:/* @__PURE__ */ new Float32Array(40)}}if(o.instances!==a.instances){o.instances=a.instances;let e=a.vat.createView();o.groups=[0,1,2,3].map(t=>i.createBindGroup({layout:o.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:o.frames,offset:t*256,size:160}},{binding:1,resource:{buffer:a.instances}},{binding:2,resource:{buffer:a.clips}},{binding:3,resource:e}]}))}let s=o.values;s.set(n),s[32]=this.time,s[36]=this.layout.rowSize,s[37]=this.vat.width,i.queue.writeBuffer(o.frames,r*256,s),t.setPipeline(o.pipeline),t.setBindGroup(0,o.groups[r]),this.bindVertices(t,a),t.setIndexBuffer(a.index,`uint32`),t.drawIndexed(this.vat.indices.length,this.n)}vertexLayout(){return[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:`float32x2`}]},...this.layout.attributes]}bindVertices(e,t){e.setVertexBuffer(0,t.uvs),t.vertices.forEach((t,n)=>e.setVertexBuffer(n+1,t))}upload(e){let t=this.resources(e),n=this.layout.stride;return(!t.instances||t.instances.size<this.n*n*4)&&(t.instances?.destroy(),t.instances=e.createBuffer({size:this.data.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.dirty=!0),this.dirty&&=(e.queue.writeBuffer(t.instances,0,this.data,0,this.n*n),!1),t}draw(e){let t=this.engine;if(!this.n||!t)return;let n=e.device,a=this.upload(n),o=e.descriptor.multisample?.count??1,s=e.descriptor.depthStencil.format,c=this.plain,l=[];for(let e of this.lighting){let t=e.pbr(1);t&&(c=u(c===this.plain?O(this.layout.vertex):c,t),l.push(...e.bindings()))}let d=this.frame;d.set(e.camera.matrix),d.set(e.camera.position,16),_(d,20,t.lighting.direction),d.set(t.lighting.radiance,24),d.set(this.color,28),d[32]=this.time,d[34]=Math.min(1,Math.max(.045,this.roughness)),d[35]=this.metalness,d[36]=this.layout.rowSize,d[37]=this.vat.width,d[38]=+i(e.format),d[39]=c===this.plain?0:d[38],n.queue.writeBuffer(a.frame,0,d);let f=e.format+o+s;if(this.key!==f||this.code!==c){let t=n.createShaderModule({code:c});this.key=f,this.code=c,this.pipeline=n.createRenderPipeline({layout:`auto`,vertex:{module:t,entryPoint:`vertex`,buffers:this.vertexLayout()},fragment:{module:t,entryPoint:`fragment`,targets:[{format:e.format}]},primitive:{cullMode:`back`},depthStencil:{format:s,depthWriteEnabled:!0,depthCompare:`greater-equal`},multisample:{count:o}})}let[p,m]=this.map?.bind(n,!0)??a.blank,h=[this.pipeline,a.instances,p,m];(!this.group||h.some((e,t)=>e!==this.bound[t]))&&(this.bound=h,this.group=n.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[a.frame,a.instances,a.clips].map((e,t)=>({binding:t,resource:{buffer:e}})).concat({binding:3,resource:a.vat.createView()},{binding:4,resource:p},{binding:5,resource:m})}));let g=e.encoder.beginRenderPass({colorAttachments:[{view:e.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:e.depth,depthLoadOp:`load`,depthStoreOp:`store`,stencilReadOnly:!0}});if(r(g,e),g.setPipeline(this.pipeline),g.setBindGroup(0,this.group),l.length){let e=[this.pipeline,...l.map(e=>`buffer`in e.resource?e.resource.buffer:e.resource)];(!this.light||e.length!==this.light.bound.length||e.some((e,t)=>e!==this.light.bound[t]))&&(this.light={bound:e,group:n.createBindGroup({layout:this.pipeline.getBindGroupLayout(1),entries:l})}),g.setBindGroup(1,this.light.group)}this.bindVertices(g,a),g.setIndexBuffer(a.index,`uint32`),g.drawIndexed(this.vat.indices.length,this.n),g.end(),t.stats.drawCalls++,t.stats.visible+=this.n}release(){let e=this.gpu;if(e)for(let t of[e.vat,e.white,e.uvs,...e.vertices,e.index,e.frame,e.clips,e.instances,this.shadow?.frames])t?.destroy();this.gpu=this.pipeline=this.group=this.light=this.shadow=void 0,this.key=``,this.code=this.plain,this.bound=[],this.device=void 0}onDeviceRestored(){this.release(),this.dirty=!0}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.lighting.clear(),this.release(),this.engine=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}};export{T as a,b as i,x as n,y as o,v as r,A as t};
package/dist/vat.d.ts ADDED
@@ -0,0 +1,178 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin, FrameGraph, PassContext } from '@margoengine/core/extension';
4
+ import type { Animation } from './index.js';
5
+ type Context = Extract<PassContext, {
6
+ backend: 'webgpu';
7
+ }>;
8
+ /** Rows `start`..`start + frames` hold the clip at `duration * row / frames`; a looping clip's last row equals its first. */
9
+ export interface VATClip {
10
+ name: string;
11
+ start: number;
12
+ frames: number;
13
+ duration: number;
14
+ loop: boolean;
15
+ }
16
+ /** Baked vertex animation: per row and vertex two rgba32float texels (model-root-space position, normal), wrapped at `width`. */
17
+ export interface VATData {
18
+ vertexCount: number;
19
+ rows: number;
20
+ width: number;
21
+ texels: Float32Array;
22
+ indices: Uint32Array;
23
+ /** UV0 with v up, like `@margoengine/materials` textures. */
24
+ uvs: Float32Array;
25
+ clips: VATClip[];
26
+ }
27
+ /** Options for {@link bakeVAT}. */
28
+ export interface VATBakeOptions {
29
+ /** Rows per second. Default 30. */ fps?: number;
30
+ /** Clip names or indices. Default: all. */
31
+ clips?: readonly (string | number)[];
32
+ }
33
+ /** Texture width VAT data wraps at (any WebGPU device takes 8192 rows of it). */
34
+ export declare const VAT_WIDTH = 2048;
35
+ /** Texel (x, y) of a baked row's vertex: k 0 is position, 1 is normal. The shader computes the same. */
36
+ export declare function vatTexel(row: number, vertex: number, k: number, vertexCount: number, width?: number): [number, number];
37
+ /**
38
+ * Bakes clips of a skinned and/or morphed glTF (an `Animation`) on the CPU into one vertex animation texture, all
39
+ * primitives merged in the model root's space. Skinning and morphs follow the GPU deformation pass. The animation's
40
+ * clip, time and playing state are restored afterwards.
41
+ */
42
+ export declare function bakeVAT(animation: Animation, { fps, clips }?: VATBakeOptions): VATData;
43
+ /** Instance layout (24 floats): world matrix, then clip, time offset (s), speed, 0, then UV offset.xy and scale.xy. */
44
+ export declare const VAT_STRIDE = 24;
45
+ /** One crowd member for {@link VATCrowd.add} and {@link VATCrowd.set}. */
46
+ export interface VATInstance {
47
+ /** Column-major 4x4 world matrix (16 numbers). Default identity. */
48
+ matrix?: ArrayLike<number>;
49
+ /** Index into `vat.clips`. Default 0. */
50
+ clip?: number;
51
+ /** Time offset into the clip in seconds, so crowd members do not move in step. Default 0. */
52
+ offset?: number;
53
+ /** Playback speed multiplier. Default 1. */
54
+ speed?: number;
55
+ /** Atlas region (offset and scale; no rotation). */
56
+ uvTransform?: {
57
+ offset?: readonly number[];
58
+ scale?: readonly number[];
59
+ };
60
+ }
61
+ /** Anything with `@margoengine/materials` Texture's `bind`. */
62
+ export interface VATMap {
63
+ bind(device: GPUDevice, srgb: boolean): [GPUTextureView, GPUSampler] | undefined;
64
+ }
65
+ /** Options for {@link VATCrowd}. */
66
+ export interface VATCrowdOptions {
67
+ /** Base colour, linear RGBA. Default `[1, 1, 1, 1]`. */
68
+ color?: readonly number[];
69
+ /** Base colour texture (a `@margoengine/materials` Texture). Default none. */
70
+ map?: VATMap | null;
71
+ /** Surface roughness, 0..1. Default 0.6. */
72
+ roughness?: number;
73
+ /** Metalness, 0..1. Default 0. */
74
+ metalness?: number;
75
+ }
76
+ /** @internal What a crowd of another kind changes: `@margoengine/animation/instanced-skin` draws through VATCrowd. */
77
+ export interface CrowdLayout {
78
+ /** Bindings, pose sampling and the vertex stage; location 0 is the UV. */
79
+ readonly vertex: string;
80
+ /** Floats per instance, the first 24 as {@link VAT_STRIDE}. */
81
+ readonly stride: number;
82
+ /** What the vertex stage multiplies a texture row by: vertices, or bones. */
83
+ readonly rowSize: number;
84
+ /** Vertex data after the UVs, and how the stage reads it. */
85
+ readonly vertices: readonly (Float32Array | Uint32Array)[];
86
+ readonly attributes: readonly GPUVertexBufferLayout[];
87
+ }
88
+ /** gltf/pbr's lighting hooks (its `PBRLighting`), declared here so the VAT entry does not import gltf/pbr. */
89
+ export interface VATLightingHooks {
90
+ readonly declarations: string;
91
+ direct?(direct: string): string;
92
+ readonly light?: string;
93
+ readonly ambient?: string;
94
+ output?(color: string): string;
95
+ }
96
+ /** What `crowd.addLighting` takes: an effect with gltf/pbr `pbr` hooks (Shadows, EnvironmentLighting, Fog), bound in group 1. */
97
+ export interface VATLighting {
98
+ pbr?(group: number): VATLightingHooks | undefined;
99
+ bindings(): GPUBindGroupEntry[];
100
+ readonly owner?: unknown;
101
+ }
102
+ /** The WGSL source the crowd draws with: bindings, vertex-texture pose sampling and neutral shading. Exposed for tooling and tests; {@link VATCrowd} builds its pipeline from it. */
103
+ export declare const vatShader: string;
104
+ /**
105
+ * Draws any number of copies of baked VAT data in one instanced call: each instance has its own matrix, clip, time
106
+ * offset, speed and atlas region, and the CPU does no per-instance work per frame (instance data uploads only when
107
+ * changed). Opaque; the GPU clips off-screen instances (no CPU culling). `shadows.add(crowd)` casts the posed crowd
108
+ * into `@margoengine/shadows` and shadows it; `lighting.add(crowd)` lights it with an EnvironmentLighting (IBL).
109
+ * No SSAO or clustered lights.
110
+ */
111
+ export declare class VATCrowd implements EnginePlugin {
112
+ readonly vat: VATData;
113
+ /** @internal */
114
+ private readonly layout;
115
+ readonly name: string;
116
+ /** Seconds since added; instance time is `time * speed + offset`. */
117
+ time: number;
118
+ readonly color: number[];
119
+ roughness: number;
120
+ metalness: number;
121
+ map: VATMap | null;
122
+ disposed: boolean;
123
+ private data;
124
+ private n;
125
+ /** The plain shader of this crowd's kind. */
126
+ private readonly plain;
127
+ private dirty;
128
+ private engine?;
129
+ private device?;
130
+ private gpu?;
131
+ private pipeline?;
132
+ private key;
133
+ private group?;
134
+ private bound;
135
+ private readonly frame;
136
+ private readonly lighting;
137
+ private code;
138
+ private light?;
139
+ private shadow?;
140
+ /** Same as `engine.use(new VATCrowd(...))`; returns the VATCrowd. */
141
+ static attach(engine: EngineKernel, vat: VATData, options?: VATCrowdOptions): VATCrowd;
142
+ constructor(vat: VATData, { color, map, roughness, metalness }?: VATCrowdOptions,
143
+ /** @internal */
144
+ layout?: CrowdLayout);
145
+ /** @internal This crowd's instance rows, for a kind that adds fields of its own. */
146
+ protected get rows(): Float32Array;
147
+ get count(): number;
148
+ /** Adds an instance (identity matrix, clip 0, offset 0, speed 1, whole texture by default) and returns its index. */
149
+ add(instance?: VATInstance): number;
150
+ /** Changes the given fields of one instance. */
151
+ set(index: number, { matrix, clip, offset, speed, uvTransform }: VATInstance): this;
152
+ /** Drops the last `count - n` instances. */
153
+ truncate(n: number): void;
154
+ setup(engine: Engine): void;
155
+ onPreUpdate(delta: number): void;
156
+ /** Moves `time` by `delta` seconds; the draw samples it per instance, so a seek replays it. */
157
+ advanceTime(delta: number): void;
158
+ registerPasses(graph: FrameGraph): void;
159
+ private resources;
160
+ /** Lights the crowd with an effect's gltf\/pbr `pbr` hooks; `shadows.add(crowd)` and `lighting.add(crowd)` call this. Returns a remover. */
161
+ addLighting(effect: VATLighting): () => void;
162
+ /** Shadows' per-cascade callback: the posed instances into that cascade's depth map, at the frame's crowd time. */
163
+ drawShadow({ context: c, pass, matrix, cascade, }: {
164
+ context: Context;
165
+ pass: GPURenderPassEncoder;
166
+ matrix: Float32Array;
167
+ cascade: number;
168
+ }): void;
169
+ private vertexLayout;
170
+ private bindVertices;
171
+ private upload;
172
+ private draw;
173
+ private release;
174
+ onDeviceRestored(): void;
175
+ dispose(): void;
176
+ [Symbol.dispose]: () => void;
177
+ }
178
+ export {};
package/dist/vat.js ADDED
@@ -0,0 +1 @@
1
+ export{t as VATCrowd,n as VAT_STRIDE,r as VAT_WIDTH,i as bakeVAT,a as vatShader,o as vatTexel}from"./vat-mWaj5B5R.js";
@@ -0,0 +1 @@
1
+ var e=/* @__PURE__ */ new WeakMap;function t(t,n,r){if(!r)return t;let i=e.get(r);i||e.set(r,i=/* @__PURE__ */ new WeakMap);let a=i.get(t);if(a)return a;a=new t.constructor(r.length*n);for(let e=0;e<r.length;e++){let i=r[e]*n;if(i+n>t.length)throw RangeError(`Part vertex out of range; every per-vertex accessor needs one element per vertex`);for(let r=0;r<n;r++)a[e*n+r]=t[i+r]}return i.set(t,a),a}export{t};
@@ -0,0 +1 @@
1
+ export declare function ordinaryWeightBuffer(values: Float32Array): boolean;