motionary 10.6.0 → 10.8.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 (153) hide show
  1. package/AGENTS.md +2 -0
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +77 -4
  4. package/bin/motionary-mcp.mjs +160 -11
  5. package/dist/chunks/{anim-image-DECLkPH4.cjs → anim-image-BzTQa2k3.cjs} +2 -2
  6. package/dist/chunks/{anim-image-DECLkPH4.cjs.map → anim-image-BzTQa2k3.cjs.map} +1 -1
  7. package/dist/chunks/{anim-image-DNghy017.js → anim-image-iD646Q7i.js} +2 -2
  8. package/dist/chunks/{anim-image-DNghy017.js.map → anim-image-iD646Q7i.js.map} +1 -1
  9. package/dist/chunks/{keyframes-F6vp6tZZ.js → keyframes-B4zefz0k.js} +2 -2
  10. package/dist/chunks/{keyframes-F6vp6tZZ.js.map → keyframes-B4zefz0k.js.map} +1 -1
  11. package/dist/chunks/{keyframes-CbUZjD_5.cjs → keyframes-BlOyB1PP.cjs} +2 -2
  12. package/dist/chunks/{keyframes-CbUZjD_5.cjs.map → keyframes-BlOyB1PP.cjs.map} +1 -1
  13. package/dist/chunks/{registry-dr1CPTk1.cjs → registry-BZxDVL3h.cjs} +2 -2
  14. package/dist/chunks/{registry-dr1CPTk1.cjs.map → registry-BZxDVL3h.cjs.map} +1 -1
  15. package/dist/chunks/{registry-D8LAoXI-.js → registry-Bkt3-3ET.js} +3 -3
  16. package/dist/chunks/{registry-D8LAoXI-.js.map → registry-Bkt3-3ET.js.map} +1 -1
  17. package/dist/chunks/runtime-link-CUiZ8lbE.cjs +38 -0
  18. package/dist/chunks/runtime-link-CUiZ8lbE.cjs.map +1 -0
  19. package/dist/chunks/runtime-link-c13gskBZ.js +36 -0
  20. package/dist/chunks/runtime-link-c13gskBZ.js.map +1 -0
  21. package/dist/chunks/{ticker-DaAlEyOd.cjs → ticker-BfxAECfO.cjs} +2 -2
  22. package/dist/chunks/{ticker-DaAlEyOd.cjs.map → ticker-BfxAECfO.cjs.map} +1 -1
  23. package/dist/chunks/{ticker-Do9bGsaV.js → ticker-ZtweD3U4.js} +2 -2
  24. package/dist/chunks/{ticker-Do9bGsaV.js.map → ticker-ZtweD3U4.js.map} +1 -1
  25. package/dist/chunks/{tween-CmkdSyaC.cjs → tween--MD-39y0.cjs} +2 -2
  26. package/dist/chunks/{tween-CmkdSyaC.cjs.map → tween--MD-39y0.cjs.map} +1 -1
  27. package/dist/chunks/{tween-BzCGq_Ba.js → tween-DACdkLyO.js} +2 -2
  28. package/dist/chunks/{tween-BzCGq_Ba.js.map → tween-DACdkLyO.js.map} +1 -1
  29. package/dist/components/ai.cjs +314 -0
  30. package/dist/components/ai.cjs.map +1 -0
  31. package/dist/components/ai.d.cts +58 -0
  32. package/dist/components/ai.d.ts +58 -0
  33. package/dist/components/ai.js +311 -0
  34. package/dist/components/ai.js.map +1 -0
  35. package/dist/components/snap-carousel.cjs +216 -0
  36. package/dist/components/snap-carousel.cjs.map +1 -0
  37. package/dist/components/snap-carousel.d.cts +80 -0
  38. package/dist/components/snap-carousel.d.ts +80 -0
  39. package/dist/components/snap-carousel.js +214 -0
  40. package/dist/components/snap-carousel.js.map +1 -0
  41. package/dist/components/widgets.cjs +626 -268
  42. package/dist/components/widgets.cjs.map +1 -1
  43. package/dist/components/widgets.d.cts +515 -39
  44. package/dist/components/widgets.d.ts +515 -39
  45. package/dist/components/widgets.js +617 -262
  46. package/dist/components/widgets.js.map +1 -1
  47. package/dist/llms-full.txt +191 -6
  48. package/dist/llms.txt +10 -3
  49. package/dist/manifest.json +497 -19
  50. package/dist/runtime/drag-snap.cjs +269 -0
  51. package/dist/runtime/drag-snap.cjs.map +1 -0
  52. package/dist/runtime/drag-snap.d.cts +109 -0
  53. package/dist/runtime/drag-snap.d.ts +109 -0
  54. package/dist/runtime/drag-snap.iife.js +2 -0
  55. package/dist/runtime/drag-snap.iife.js.map +1 -0
  56. package/dist/runtime/drag-snap.js +261 -0
  57. package/dist/runtime/drag-snap.js.map +1 -0
  58. package/dist/runtime/format-apng.cjs +4 -4
  59. package/dist/runtime/format-apng.js +4 -4
  60. package/dist/runtime/format-css.cjs +4 -4
  61. package/dist/runtime/format-css.js +4 -4
  62. package/dist/runtime/format-gif.cjs +4 -4
  63. package/dist/runtime/format-gif.js +4 -4
  64. package/dist/runtime/format-gltf.cjs +37 -18
  65. package/dist/runtime/format-gltf.cjs.map +1 -1
  66. package/dist/runtime/format-gltf.d.cts +18 -2
  67. package/dist/runtime/format-gltf.d.ts +18 -2
  68. package/dist/runtime/format-gltf.iife.js +1 -1
  69. package/dist/runtime/format-gltf.iife.js.map +1 -1
  70. package/dist/runtime/format-gltf.js +37 -18
  71. package/dist/runtime/format-gltf.js.map +1 -1
  72. package/dist/runtime/format-motion.cjs +4 -4
  73. package/dist/runtime/format-motion.js +4 -4
  74. package/dist/runtime/format-obj.cjs +1 -1
  75. package/dist/runtime/format-obj.d.cts +2 -0
  76. package/dist/runtime/format-obj.d.ts +2 -0
  77. package/dist/runtime/format-obj.iife.js.map +1 -1
  78. package/dist/runtime/format-obj.js +1 -1
  79. package/dist/runtime/format-scene.cjs +241 -0
  80. package/dist/runtime/format-scene.cjs.map +1 -0
  81. package/dist/runtime/format-scene.d.cts +349 -0
  82. package/dist/runtime/format-scene.d.ts +349 -0
  83. package/dist/runtime/format-scene.iife.js +2 -0
  84. package/dist/runtime/format-scene.iife.js.map +1 -0
  85. package/dist/runtime/format-scene.js +233 -0
  86. package/dist/runtime/format-scene.js.map +1 -0
  87. package/dist/runtime/format-sprite.cjs +3 -3
  88. package/dist/runtime/format-sprite.js +3 -3
  89. package/dist/runtime/format-svg.cjs +3 -3
  90. package/dist/runtime/format-svg.js +3 -3
  91. package/dist/runtime/format-webp.cjs +4 -4
  92. package/dist/runtime/format-webp.js +4 -4
  93. package/dist/runtime/gl.cjs +17 -4
  94. package/dist/runtime/gl.cjs.map +1 -1
  95. package/dist/runtime/gl.d.cts +2 -0
  96. package/dist/runtime/gl.d.ts +2 -0
  97. package/dist/runtime/gl.iife.js +1 -1
  98. package/dist/runtime/gl.iife.js.map +1 -1
  99. package/dist/runtime/gl.js +17 -4
  100. package/dist/runtime/gl.js.map +1 -1
  101. package/dist/runtime/gltf-anim.cjs +251 -0
  102. package/dist/runtime/gltf-anim.cjs.map +1 -0
  103. package/dist/runtime/gltf-anim.d.cts +216 -0
  104. package/dist/runtime/gltf-anim.d.ts +216 -0
  105. package/dist/runtime/gltf-anim.iife.js +2 -0
  106. package/dist/runtime/gltf-anim.iife.js.map +1 -0
  107. package/dist/runtime/gltf-anim.js +243 -0
  108. package/dist/runtime/gltf-anim.js.map +1 -0
  109. package/dist/runtime/physics.cjs +739 -0
  110. package/dist/runtime/physics.cjs.map +1 -0
  111. package/dist/runtime/physics.d.cts +250 -0
  112. package/dist/runtime/physics.d.ts +250 -0
  113. package/dist/runtime/physics.iife.js +2 -0
  114. package/dist/runtime/physics.iife.js.map +1 -0
  115. package/dist/runtime/physics.js +731 -0
  116. package/dist/runtime/physics.js.map +1 -0
  117. package/dist/runtime/scroll.cjs +2 -2
  118. package/dist/runtime/scroll.js +2 -2
  119. package/dist/runtime/smooth.cjs +1 -1
  120. package/dist/runtime/smooth.js +1 -1
  121. package/dist/runtime/text.cjs +1 -1
  122. package/dist/runtime/text.js +1 -1
  123. package/dist/runtime/vector.cjs +421 -11
  124. package/dist/runtime/vector.cjs.map +1 -1
  125. package/dist/runtime/vector.d.cts +20 -4
  126. package/dist/runtime/vector.d.ts +20 -4
  127. package/dist/runtime/vector.iife.js +1 -1
  128. package/dist/runtime/vector.iife.js.map +1 -1
  129. package/dist/runtime/vector.js +421 -12
  130. package/dist/runtime/vector.js.map +1 -1
  131. package/dist/runtime.cjs +3 -3
  132. package/dist/runtime.d.cts +1 -1
  133. package/dist/runtime.d.ts +1 -1
  134. package/dist/runtime.iife.js +1 -1
  135. package/dist/runtime.iife.js.map +1 -1
  136. package/dist/runtime.js +5 -5
  137. package/dist/widgets.umd.js +1 -1
  138. package/dist/widgets.umd.js.map +1 -1
  139. package/docs/ROADMAP.md +2 -2
  140. package/docs/components/README.md +5 -2
  141. package/docs/components/usa-gl-scene.md +27 -6
  142. package/docs/components/usa-lottie-player.md +18 -0
  143. package/docs/components/usa-motion-prompt.md +32 -0
  144. package/docs/components/usa-physics-playground.md +63 -0
  145. package/docs/components/usa-snap-carousel.md +68 -0
  146. package/docs/components.md +95 -3
  147. package/docs/runtime/drag-snap.md +60 -0
  148. package/docs/runtime/format-gltf.md +3 -2
  149. package/docs/runtime/format-scene.md +59 -0
  150. package/docs/runtime/gltf-anim.md +62 -0
  151. package/docs/runtime/physics.md +61 -0
  152. package/docs/runtime/vector.md +3 -2
  153. package/package.json +61 -1
@@ -0,0 +1,216 @@
1
+ /** A runtime module: `{ id, version, api }`, registered with `use()`. */
2
+ interface RuntimeModule<A = unknown> {
3
+ /** Module id: 'core', 'format-css', 'scroll', … (import path `motionary/runtime/<id>`). */
4
+ id: string;
5
+ version: string;
6
+ /** Other modules this one needs (registered first by `use()` callers). */
7
+ requires?: string[];
8
+ /** The module's public API (what `requireModule(id)` returns). */
9
+ api: A;
10
+ /** Optional one-time setup, called on first registration. */
11
+ setup?(registry: RuntimeRegistry): void;
12
+ }
13
+ interface RuntimeRegistry {
14
+ version: string;
15
+ modules: Map<string, RuntimeModule>;
16
+ /** Shared per-page state slots (the ticker lives here). */
17
+ slots: Record<string, unknown>;
18
+ }
19
+
20
+ /**
21
+ * `motionary/runtime/gl` (10.5) — a small WebGL2 scene renderer written for
22
+ * Motionary (not a Three.js clone; own API, own shaders):
23
+ *
24
+ * - **math** (`mat4`, quaternions — column-major `Float32Array`s), pure;
25
+ * - **scene graph**: `GlNode` (position / rotation quaternion / scale,
26
+ * children, optional mesh), `Camera` (perspective, `lookAt`), lights
27
+ * (`ambient`, up to 4 directional / point), `bounds()` + `frameNode()`;
28
+ * - **geometry** builders (`box`, `plane`, `sphere`, `torus`) and custom
29
+ * geometry from typed arrays (indexed 16 / 32-bit or not);
30
+ * - **materials**: `standard` (metallic-roughness PBR approximation, base
31
+ * colour texture, emissive, ACES-free Reinhard tone mapping, sRGB),
32
+ * `unlit`, and `shader` (your GLSL ES 3.00 fragment with the standard
33
+ * varyings + your uniforms);
34
+ * - **textures** from images, canvases, bitmaps and **videos** (updated per
35
+ * decoded frame with `requestVideoFrameCallback`; `scrubVideo()` seeks a
36
+ * video from a 0–1 progress, e.g. a scroll scene);
37
+ * - `orbitControls()` — drag / wheel / pinch / arrow keys, damping, optional
38
+ * auto-rotate (off under reduced motion).
39
+ *
40
+ * Math, geometry and the scene graph are pure (SSR / workers); rendering
41
+ * needs WebGL2 (`createRenderer()` throws a clear error without it). Model
42
+ * loaders live in `motionary/runtime/format-gltf` and `format-obj`.
43
+ */
44
+
45
+ type Vec3 = [number, number, number];
46
+ type Quat = [number, number, number, number];
47
+ type Mat4 = Float32Array;
48
+ interface Geometry {
49
+ positions: Float32Array;
50
+ normals?: Float32Array;
51
+ uvs?: Float32Array;
52
+ indices?: Uint16Array | Uint32Array;
53
+ /** 'triangles' (default), 'lines', 'points'. */
54
+ mode?: 'triangles' | 'lines' | 'points';
55
+ /** Bump after changing positions / normals in place (10.8: skinning, morph targets) — the renderer re-uploads them. */
56
+ version?: number;
57
+ /** Renderer cache. */
58
+ _gpu?: unknown;
59
+ }
60
+ interface GlTexture {
61
+ source: TexImageSource | {
62
+ width: number;
63
+ height: number;
64
+ data: Uint8Array | Uint8ClampedArray;
65
+ };
66
+ /** sRGB colour data (default true for colour maps). */
67
+ srgb?: boolean;
68
+ repeat?: boolean;
69
+ flipY?: boolean;
70
+ /** Re-upload every frame a new video frame is ready. */
71
+ video?: boolean;
72
+ needsUpdate?: boolean;
73
+ _gpu?: unknown;
74
+ }
75
+ interface Material {
76
+ type: 'standard' | 'unlit' | 'shader';
77
+ /** Linear RGBA multiplier (sRGB input converted by the shader). */
78
+ color: [number, number, number, number];
79
+ map?: GlTexture | null;
80
+ metallic: number;
81
+ roughness: number;
82
+ emissive: Vec3;
83
+ doubleSided?: boolean;
84
+ transparent?: boolean;
85
+ wireframe?: boolean;
86
+ /** 'shader' materials: GLSL ES 3.00 fragment body + uniforms. */
87
+ fragment?: string;
88
+ uniforms?: Record<string, number | number[] | Float32Array | GlTexture>;
89
+ _gpu?: unknown;
90
+ }
91
+ interface Mesh {
92
+ geometry: Geometry;
93
+ material: Material;
94
+ }
95
+ declare class GlNode {
96
+ name: string;
97
+ position: Vec3;
98
+ rotation: Quat;
99
+ scale: Vec3;
100
+ /** Set to use a fixed local matrix instead of position / rotation / scale (glTF `matrix`). */
101
+ matrix: Mat4 | null;
102
+ children: GlNode[];
103
+ parent: GlNode | null;
104
+ mesh: Mesh | Mesh[] | null;
105
+ visible: boolean;
106
+ /** Free-form data (loaders put source info here). */
107
+ extras: Record<string, unknown>;
108
+ readonly world: Mat4;
109
+ constructor(name?: string, mesh?: Mesh | Mesh[] | null);
110
+ add(...nodes: GlNode[]): this;
111
+ remove(n: GlNode): void;
112
+ setEuler(x: number, y: number, z: number): this;
113
+ local(): Mat4;
114
+ /** Recompute world matrices of this subtree. */
115
+ updateWorld(parent?: Mat4): void;
116
+ traverse(fn: (n: GlNode) => void): void;
117
+ find(name: string): GlNode | null;
118
+ }
119
+
120
+ /**
121
+ * `motionary/runtime/gltf-anim` (10.8) — glTF 2.0 animation, skinning and
122
+ * morph targets for models loaded by `motionary/runtime/format-gltf`
123
+ * (own implementation; requires `use(gl, formatGltf, gltfAnim)`).
124
+ *
125
+ * - animation channels on node `translation` / `rotation` / `scale` /
126
+ * `weights` with `LINEAR` (quaternions slerped), `STEP` and
127
+ * `CUBICSPLINE` (Hermite with in / out tangents) samplers;
128
+ * - morph targets (POSITION + NORMAL deltas) with mesh default weights,
129
+ * node weights and animated weights;
130
+ * - skins: joint hierarchy, inverse bind matrices, 4 joints / vertex
131
+ * (JOINTS_0 / WEIGHTS_0), skinned on the CPU and re-uploaded each frame
132
+ * (`geometry.version`), so it works with every runtime/gl material;
133
+ * - `gltfAnimator(model)` plays a clip (by name or index) with loop / speed
134
+ * / seek, `update(dt)` from your loop or `play()` on the shared ticker.
135
+ *
136
+ * Sampling and deformation are pure (SSR / workers / tests).
137
+ */
138
+
139
+ type Num = number;
140
+ type ChannelPath = 'translation' | 'rotation' | 'scale' | 'weights';
141
+ type Interpolation = 'LINEAR' | 'STEP' | 'CUBICSPLINE';
142
+ interface GltfChannel {
143
+ node: GlNode;
144
+ path: ChannelPath;
145
+ interpolation: Interpolation;
146
+ times: Float32Array;
147
+ values: Float32Array;
148
+ /** Components per key (3, 4 or the morph target count). */
149
+ size: Num;
150
+ }
151
+ interface GltfClip {
152
+ name: string;
153
+ duration: Num;
154
+ channels: GltfChannel[];
155
+ }
156
+ /** Morph / skin source data kept on a geometry by format-gltf (10.8). */
157
+ interface DeformSource {
158
+ positions: Float32Array;
159
+ normals?: Float32Array;
160
+ joints?: Float32Array;
161
+ weights?: Float32Array;
162
+ targets?: {
163
+ positions?: Float32Array;
164
+ normals?: Float32Array;
165
+ }[];
166
+ }
167
+ /** The animation clips of a loaded model. */
168
+ declare function gltfClips(root: GlNode): GltfClip[];
169
+ /** Value of a channel at time `t` (seconds; clamped to the key range). */
170
+ declare function sampleChannel(ch: GltfChannel, t: Num): Num[];
171
+ /** Pose the model at time `t` of a clip (sets node TRS and morph weights). */
172
+ declare function applyClip(clip: GltfClip, t: Num): void;
173
+ /**
174
+ * Apply morph weights and skins to every deformable mesh of the model
175
+ * (call after posing; updates world matrices). Returns how many meshes changed.
176
+ */
177
+ declare function deformModel(root: GlNode): Num;
178
+ /** Morph + skin one geometry from its source data (pure). */
179
+ declare function deformGeometry(g: Geometry, src: DeformSource, weights: Num[], joints: Mat4[] | null): void;
180
+ interface GltfAnimatorOptions {
181
+ /** Clip name or index (default 0). */
182
+ clip?: string | Num;
183
+ loop?: boolean;
184
+ speed?: Num;
185
+ }
186
+ interface GltfAnimator {
187
+ readonly clips: GltfClip[];
188
+ readonly clip: GltfClip | null;
189
+ time: Num;
190
+ speed: Num;
191
+ loop: boolean;
192
+ readonly playing: boolean;
193
+ /** Switch clip (name or index); keeps playing state. */
194
+ use(clip: string | Num): void;
195
+ seek(t: Num): void;
196
+ /** Advance by `dt` seconds and pose + deform. */
197
+ update(dt: Num): void;
198
+ /** Run on the shared ticker. */
199
+ play(): void;
200
+ pause(): void;
201
+ dispose(): void;
202
+ }
203
+ /** A clip player for a loaded model. */
204
+ declare function gltfAnimator(root: GlNode, o?: GltfAnimatorOptions): GltfAnimator;
205
+ interface GltfAnimApi {
206
+ gltfClips: typeof gltfClips;
207
+ sampleChannel: typeof sampleChannel;
208
+ applyClip: typeof applyClip;
209
+ deformModel: typeof deformModel;
210
+ deformGeometry: typeof deformGeometry;
211
+ gltfAnimator: typeof gltfAnimator;
212
+ }
213
+ declare const gltfAnim: RuntimeModule<GltfAnimApi>;
214
+
215
+ export { applyClip, deformGeometry, deformModel, gltfAnim, gltfAnimator, gltfClips, sampleChannel };
216
+ export type { ChannelPath, DeformSource, GltfAnimApi, GltfAnimator, GltfAnimatorOptions, GltfChannel, GltfClip, Interpolation };
@@ -0,0 +1,2 @@
1
+ !function(t,n){"use strict";const e={identity:()=>new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),multiply(t,n,e=new Float32Array(16)){for(let o=0;o<4;o++)for(let r=0;r<4;r++)e[4*o+r]=t[r]*n[4*o]+t[4+r]*n[4*o+1]+t[8+r]*n[4*o+2]+t[12+r]*n[4*o+3];return e},perspective(t,n,e,o){const r=1/Math.tan(t/2),i=1/(e-o);return new Float32Array([r/n,0,0,0,0,r,0,0,0,0,(o+e)*i,-1,0,0,2*o*e*i,0])},lookAt(t,n,e=[0,1,0]){let a=o(t,n);a=s(a.some(t=>t)?a:[0,0,1]);let l=i(e,a);l.some(t=>Math.abs(t)>1e-9)||(l=i([0,0,1],a)),l=s(l);const m=i(a,l);return new Float32Array([l[0],m[0],a[0],0,l[1],m[1],a[1],0,l[2],m[2],a[2],0,-r(l,t),-r(m,t),-r(a,t),1])},compose(t,n,e){const[o,r,i,s]=n,a=o+o,l=r+r,m=i+i,c=o*a,p=o*l,u=o*m,f=r*l,h=r*m,g=i*m,d=s*a,y=s*l,M=s*m;return new Float32Array([(1-(f+g))*e[0],(p+M)*e[0],(u-y)*e[0],0,(p-M)*e[1],(1-(c+g))*e[1],(h+d)*e[1],0,(u+y)*e[2],(h-d)*e[2],(1-(c+f))*e[2],0,t[0],t[1],t[2],1])},invert(t){const n=new Float32Array(16),[e,o,r,i,s,a,l,m,c,p,u,f,h,g,d,y]=t,M=e*a-o*s,w=e*l-r*s,A=e*m-i*s,v=o*l-r*a,C=o*m-i*a,F=r*m-i*l,b=c*g-p*h,k=c*d-u*h,x=c*y-f*h,E=p*d-u*g,I=p*y-f*g,N=u*y-f*d;let j=M*N-w*I+A*E+v*x-C*k+F*b;return j?(j=1/j,n[0]=(a*N-l*I+m*E)*j,n[1]=(r*I-o*N-i*E)*j,n[2]=(g*F-d*C+y*v)*j,n[3]=(u*C-p*F-f*v)*j,n[4]=(l*x-s*N-m*k)*j,n[5]=(e*N-r*x+i*k)*j,n[6]=(d*A-h*F-y*w)*j,n[7]=(c*F-u*A+f*w)*j,n[8]=(s*I-a*x+m*b)*j,n[9]=(o*x-e*I-i*b)*j,n[10]=(h*C-g*A+y*M)*j,n[11]=(p*A-c*C-f*M)*j,n[12]=(a*k-s*E-l*b)*j,n[13]=(e*E-o*k+r*b)*j,n[14]=(g*w-h*v-d*M)*j,n[15]=(c*v-p*w+u*M)*j,n):null},normal(t){const n=e.invert(t)||e.identity();return new Float32Array([n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]])},transformPoint(t,n){const e=t[3]*n[0]+t[7]*n[1]+t[11]*n[2]+t[15]||1;return[(t[0]*n[0]+t[4]*n[1]+t[8]*n[2]+t[12])/e,(t[1]*n[0]+t[5]*n[1]+t[9]*n[2]+t[13])/e,(t[2]*n[0]+t[6]*n[1]+t[10]*n[2]+t[14])/e]}},o=(t,n)=>[t[0]-n[0],t[1]-n[1],t[2]-n[2]],r=(t,n)=>t[0]*n[0]+t[1]*n[1]+t[2]*n[2],i=(t,n)=>[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]],s=t=>{const n=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/n,t[1]/n,t[2]/n]};const a=t=>{const n=t.extras;if(!n?.gltf||!n.read)throw new Error("[motionary] gltf-anim: pass the node returned by loadGltf() / gltfToNode() (motionary/runtime/format-gltf 10.8+)");return n};function l(t){const{gltf:n,nodes:e,read:o}=a(t);return(n.animations||[]).map((t,n)=>{let r=0;const i=[];for(const n of t.channels||[]){const s=e[n.target?.node],a=t.samplers?.[n.sampler];if(!s||!a||!["translation","rotation","scale","weights"].includes(n.target.path))continue;const l=o(a.input),m=o(a.output),c=a.interpolation||"LINEAR",p=m.length/l.length/("CUBICSPLINE"===c?3:1);r=Math.max(r,l[l.length-1]||0),i.push({node:s,path:n.target.path,interpolation:c,times:l,values:m,size:p})}return{name:t.name||`animation${n}`,duration:r,channels:i}})}function m(t,n){const{times:e,values:o,size:r}=t,i="CUBICSPLINE"===t.interpolation,s=t=>Array.from(o.subarray((i?3*t+1:t)*r,(i?3*t+1:t)*r+r)),a=e.length-1;if(n<=e[0]||0===a)return s(0);if(n>=e[a])return s(a);let l=0;for(;l<a-1&&e[l+1]<=n;)l++;const m=e[l+1]-e[l],c=(n-e[l])/m;let p;if("STEP"===t.interpolation)return s(l);if(i){const n=c*c,e=n*c,i=2*e-3*n+1,s=e-2*n+c,a=-2*e+3*n,u=e-n,f=3*l*r,h=3*(l+1)*r;if(p=Array.from({length:r},(t,n)=>i*o[f+r+n]+s*m*o[f+2*r+n]+a*o[h+r+n]+u*m*o[h+n]),"rotation"===t.path){const t=Math.hypot(...p)||1;p=p.map(n=>n/t)}return p}const u=s(l),f=s(l+1);return"rotation"===t.path?function(t,n,e){let o=t[0]*n[0]+t[1]*n[1]+t[2]*n[2]+t[3]*n[3];const r=o<0?n.map(t=>-t):n;if(o=Math.abs(o),o>.9995){const n=t.map((t,n)=>t+(r[n]-t)*e),o=Math.hypot(...n)||1;return n.map(t=>t/o)}const i=Math.acos(o),s=Math.sin(i),a=Math.sin((1-e)*i)/s,l=Math.sin(e*i)/s;return t.map((t,n)=>t*a+r[n]*l)}(u,f,c):u.map((t,n)=>t+(f[n]-t)*c)}function c(t,n){for(const e of t.channels){const t=m(e,n),o=e.node;"weights"===e.path?o.extras.weights=t:(o.matrix=null,"translation"===e.path?o.position=t:"rotation"===e.path?o.rotation=t:o.scale=t)}}const p=t=>t.mesh?Array.isArray(t.mesh)?t.mesh:[t.mesh]:[];function u(t){var n;const{gltf:o,nodes:r,read:i}=a(t);t.updateWorld();let s=0;const l=(n=t.extras).skinCache||(n.skinCache={});for(const t of r){const n=p(t);if(!n.length)continue;const a=t.extras.skin;let m=null;if(void 0!==a&&o.skins?.[a]){const n=o.skins[a],s=l[a]||(l[a]={joints:n.joints.map(t=>r[t]),ibm:n.joints.map((t,o)=>void 0!==n.inverseBindMatrices?new Float32Array(i(n.inverseBindMatrices).subarray(16*o,16*o+16)):e.identity())}),c=e.invert(t.world)||e.identity();m=s.joints.map((t,n)=>e.multiply(c,e.multiply(t.world,s.ibm[n])))}const c=t.extras.weights||[];for(const t of n){const n=t.geometry,e=n.deform;e&&(m||e.targets?.length)&&(f(n,e,c,m),s++)}}return s}function f(t,n,e,o){const r=n.positions,i=n.normals,s=r.length/3,a=t.positions!==r&&t.positions.length===r.length?t.positions:t.positions=new Float32Array(r.length),l=i?t.normals&&t.normals!==i&&t.normals.length===i.length?t.normals:t.normals=new Float32Array(i.length):null;if(a.set(r),l&&i&&l.set(i),(n.targets||[]).forEach((t,n)=>{const o=e[n]||0;if(o){if(t.positions)for(let n=0;n<a.length;n++)a[n]+=o*t.positions[n];if(t.normals&&l)for(let n=0;n<l.length;n++)l[n]+=o*t.normals[n]}}),o&&n.joints&&n.weights){const t=n.joints,e=n.weights,r=new Float32Array(16);for(let n=0;n<s;n++){r.fill(0);let i=0;for(let s=0;s<4;s++){const a=e[4*n+s];if(!a)continue;const l=o[t[4*n+s]];if(l){i+=a;for(let t=0;t<16;t++)r[t]+=a*l[t]}}if(!i)continue;const s=a[3*n],m=a[3*n+1],c=a[3*n+2];if(a[3*n]=r[0]*s+r[4]*m+r[8]*c+r[12],a[3*n+1]=r[1]*s+r[5]*m+r[9]*c+r[13],a[3*n+2]=r[2]*s+r[6]*m+r[10]*c+r[14],l){const t=l[3*n],e=l[3*n+1],o=l[3*n+2],i=r[0]*t+r[4]*e+r[8]*o,s=r[1]*t+r[5]*e+r[9]*o,a=r[2]*t+r[6]*e+r[10]*o,m=Math.hypot(i,s,a)||1;l[3*n]=i/m,l[3*n+1]=s/m,l[3*n+2]=a/m}}}t.version=(t.version||0)+1}function h(t,e={}){const o=l(t);let r=null,i=null;const s=t=>("number"==typeof t?o[t]:o.find(n=>n.name===t)||o[Number(t)])||null,a=()=>{r&&c(r,m.time),u(t)},m={clips:o,get clip(){return r},time:0,speed:e.speed??1,loop:e.loop??!0,get playing(){return!!i},use(t){r=s(t),m.time=0,a()},seek(t){const n=r?.duration||0;m.time=n?m.loop?(t%n+n)%n:Math.min(n,Math.max(0,t)):0,a()},update(t){m.seek(m.time+t*m.speed)},play(){i||(i=n.requireModule("core","motionary/runtime/gltf-anim").getTicker().add((t,n)=>m.update(Math.min(n,100)/1e3)))},pause(){i?.(),i=null},dispose(){m.pause()}};return r=s(e.clip??0),a(),m}const g={id:"gltf-anim",version:n.RUNTIME_VERSION,requires:["core","gl","format-gltf"],api:{gltfClips:l,sampleChannel:m,applyClip:c,deformModel:u,deformGeometry:f,gltfAnimator:h}};n.register(g),t.applyClip=c,t.deformGeometry=f,t.deformModel=u,t.gltfAnim=g,t.gltfAnimator=h,t.gltfClips=l,t.sampleChannel=m}(this.MotionaryRuntime=this.MotionaryRuntime||{},MotionaryRuntime);
2
+ //# sourceMappingURL=gltf-anim.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gltf-anim.iife.js","sources":["../../src/runtime/gl.ts","../../src/runtime/gltf-anim.ts","../../src/runtime/iife/gltf-anim.ts"],"sourcesContent":["/**\n * `motionary/runtime/gl` (10.5) — a small WebGL2 scene renderer written for\n * Motionary (not a Three.js clone; own API, own shaders):\n *\n * - **math** (`mat4`, quaternions — column-major `Float32Array`s), pure;\n * - **scene graph**: `GlNode` (position / rotation quaternion / scale,\n * children, optional mesh), `Camera` (perspective, `lookAt`), lights\n * (`ambient`, up to 4 directional / point), `bounds()` + `frameNode()`;\n * - **geometry** builders (`box`, `plane`, `sphere`, `torus`) and custom\n * geometry from typed arrays (indexed 16 / 32-bit or not);\n * - **materials**: `standard` (metallic-roughness PBR approximation, base\n * colour texture, emissive, ACES-free Reinhard tone mapping, sRGB),\n * `unlit`, and `shader` (your GLSL ES 3.00 fragment with the standard\n * varyings + your uniforms);\n * - **textures** from images, canvases, bitmaps and **videos** (updated per\n * decoded frame with `requestVideoFrameCallback`; `scrubVideo()` seeks a\n * video from a 0–1 progress, e.g. a scroll scene);\n * - `orbitControls()` — drag / wheel / pinch / arrow keys, damping, optional\n * auto-rotate (off under reduced motion).\n *\n * Math, geometry and the scene graph are pure (SSR / workers); rendering\n * needs WebGL2 (`createRenderer()` throws a clear error without it). Model\n * loaders live in `motionary/runtime/format-gltf` and `format-obj`.\n */\nimport { RUNTIME_VERSION, type RuntimeModule } from './registry';\n\n// ------------------------------------------------------------------ math\nexport type Vec3 = [number, number, number];\nexport type Quat = [number, number, number, number];\nexport type Mat4 = Float32Array;\n\nexport const mat4 = {\n identity: (): Mat4 => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),\n multiply(a: Mat4, b: Mat4, out: Mat4 = new Float32Array(16)): Mat4 {\n for (let c = 0; c < 4; c++)\n for (let r = 0; r < 4; r++) out[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];\n return out;\n },\n perspective(fovy: number, aspect: number, near: number, far: number): Mat4 {\n const f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far);\n return new Float32Array([f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, 2 * far * near * nf, 0]);\n },\n lookAt(eye: Vec3, target: Vec3, up: Vec3 = [0, 1, 0]): Mat4 {\n let z = sub(eye, target);\n z = norm(z.some((v) => v) ? z : [0, 0, 1]);\n let x = cross(up, z);\n if (!x.some((v) => Math.abs(v) > 1e-9)) x = cross([0, 0, 1], z);\n x = norm(x);\n const y = cross(z, x);\n return new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, eye), -dot(y, eye), -dot(z, eye), 1]);\n },\n /** Translation · rotation (quaternion) · scale. */\n compose(t: Vec3, q: Quat, s: Vec3): Mat4 {\n const [x, y, z, w] = q, x2 = x + x, y2 = y + y, z2 = z + z;\n const xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;\n return new Float32Array([(1 - (yy + zz)) * s[0], (xy + wz) * s[0], (xz - wy) * s[0], 0, (xy - wz) * s[1], (1 - (xx + zz)) * s[1], (yz + wx) * s[1], 0, (xz + wy) * s[2], (yz - wx) * s[2], (1 - (xx + yy)) * s[2], 0, t[0], t[1], t[2], 1]);\n },\n invert(m: Mat4): Mat4 | null {\n const o = new Float32Array(16);\n const [a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33] = m;\n const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;\n let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n if (!det) return null;\n det = 1 / det;\n o[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; o[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; o[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; o[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n o[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; o[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; o[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; o[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n o[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; o[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; o[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; o[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n o[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; o[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; o[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; o[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return o;\n },\n /** Inverse-transpose of the upper 3×3 (normal matrix), as a mat3. */\n normal(m: Mat4): Float32Array {\n const i = mat4.invert(m) || mat4.identity();\n return new Float32Array([i[0], i[4], i[8], i[1], i[5], i[9], i[2], i[6], i[10]]);\n },\n transformPoint(m: Mat4, p: Vec3): Vec3 {\n const w = m[3] * p[0] + m[7] * p[1] + m[11] * p[2] + m[15] || 1;\n return [(m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12]) / w, (m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13]) / w, (m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]) / w];\n },\n};\nconst sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\nconst dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\nconst cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\nconst norm = (a: Vec3): Vec3 => {\n const l = Math.hypot(a[0], a[1], a[2]) || 1;\n return [a[0] / l, a[1] / l, a[2] / l];\n};\n\n/** Quaternion from Euler angles (radians, XYZ order). */\nexport function quatFromEuler(x: number, y: number, z: number): Quat {\n const cx = Math.cos(x / 2), sx = Math.sin(x / 2), cy = Math.cos(y / 2), sy = Math.sin(y / 2), cz = Math.cos(z / 2), sz = Math.sin(z / 2);\n return [sx * cy * cz + cx * sy * sz, cx * sy * cz - sx * cy * sz, cx * cy * sz + sx * sy * cz, cx * cy * cz - sx * sy * sz];\n}\n/** Hamilton product a·b. */\nexport function quatMultiply(a: Quat, b: Quat): Quat {\n return [a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1], a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0], a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3], a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]];\n}\n/** Spherical interpolation. */\nexport function quatSlerp(a: Quat, b: Quat, t: number): Quat {\n let d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n const bb = d < 0 ? (b.map((v) => -v) as Quat) : b;\n d = Math.abs(d);\n if (d > 0.9995) {\n const r = a.map((v, i) => v + (bb[i] - v) * t) as Quat;\n const l = Math.hypot(...r) || 1;\n return r.map((v) => v / l) as Quat;\n }\n const th = Math.acos(d), s = Math.sin(th), wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s;\n return a.map((v, i) => v * wa + bb[i] * wb) as Quat;\n}\n\n// ------------------------------------------------------------------ geometry\nexport interface Geometry {\n positions: Float32Array;\n normals?: Float32Array;\n uvs?: Float32Array;\n indices?: Uint16Array | Uint32Array;\n /** 'triangles' (default), 'lines', 'points'. */\n mode?: 'triangles' | 'lines' | 'points';\n /** Bump after changing positions / normals in place (10.8: skinning, morph targets) — the renderer re-uploads them. */\n version?: number;\n /** Renderer cache. */\n _gpu?: unknown;\n}\n\nconst geo = (p: number[], n: number[], uv: number[], idx: number[]): Geometry => ({ positions: new Float32Array(p), normals: new Float32Array(n), uvs: new Float32Array(uv), indices: p.length / 3 > 65535 ? new Uint32Array(idx) : new Uint16Array(idx) });\n\n/** Axis-aligned box centred on the origin. */\nexport function box(w = 1, h = 1, d = 1): Geometry {\n const p: number[] = [], n: number[] = [], uv: number[] = [], idx: number[] = [];\n const faces: [Vec3, Vec3, Vec3][] = [[[1, 0, 0], [0, 0, -1], [0, 1, 0]], [[-1, 0, 0], [0, 0, 1], [0, 1, 0]], [[0, 1, 0], [1, 0, 0], [0, 0, -1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]], [[0, 0, 1], [1, 0, 0], [0, 1, 0]], [[0, 0, -1], [-1, 0, 0], [0, 1, 0]]];\n const half: Vec3 = [w / 2, h / 2, d / 2];\n for (const [nn, u, v] of faces) {\n const b = p.length / 3;\n for (const [su, sv] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {\n for (let k = 0; k < 3; k++) p.push((nn[k] + u[k] * su + v[k] * sv) * half[k]);\n n.push(...nn);\n uv.push((su + 1) / 2, (1 - sv) / 2);\n }\n idx.push(b, b + 1, b + 2, b, b + 2, b + 3);\n }\n return geo(p, n, uv, idx);\n}\n/** XY plane facing +Z. */\nexport function plane(w = 1, h = 1, sx = 1, sy = 1): Geometry {\n const p: number[] = [], n: number[] = [], uv: number[] = [], idx: number[] = [];\n for (let j = 0; j <= sy; j++)\n for (let i = 0; i <= sx; i++) {\n p.push((i / sx - 0.5) * w, (j / sy - 0.5) * h, 0);\n n.push(0, 0, 1);\n uv.push(i / sx, 1 - j / sy);\n }\n for (let j = 0; j < sy; j++)\n for (let i = 0; i < sx; i++) {\n const a = j * (sx + 1) + i, b = a + 1, c = a + sx + 1, d = c + 1;\n idx.push(a, b, d, a, d, c);\n }\n return geo(p, n, uv, idx);\n}\n/** UV sphere. */\nexport function sphere(r = 0.5, ws = 32, hs = 16): Geometry {\n const p: number[] = [], n: number[] = [], uv: number[] = [], idx: number[] = [];\n for (let j = 0; j <= hs; j++) {\n const v = j / hs, th = v * Math.PI;\n for (let i = 0; i <= ws; i++) {\n const u = i / ws, ph = u * Math.PI * 2;\n const x = -Math.cos(ph) * Math.sin(th), y = Math.cos(th), z = Math.sin(ph) * Math.sin(th);\n p.push(x * r, y * r, z * r);\n n.push(x, y, z);\n uv.push(u, v);\n }\n }\n for (let j = 0; j < hs; j++)\n for (let i = 0; i < ws; i++) {\n const a = j * (ws + 1) + i, b = a + ws + 1;\n if (j) idx.push(a, b, a + 1);\n if (j < hs - 1) idx.push(a + 1, b, b + 1);\n }\n return geo(p, n, uv, idx);\n}\n/** Torus in the XY plane. */\nexport function torus(R = 0.5, r = 0.18, rs = 48, ts = 16): Geometry {\n const p: number[] = [], n: number[] = [], uv: number[] = [], idx: number[] = [];\n for (let j = 0; j <= ts; j++)\n for (let i = 0; i <= rs; i++) {\n const u = (i / rs) * Math.PI * 2, v = (j / ts) * Math.PI * 2;\n const cx = R * Math.cos(u), cy = R * Math.sin(u);\n const x = (R + r * Math.cos(v)) * Math.cos(u), y = (R + r * Math.cos(v)) * Math.sin(u), z = r * Math.sin(v);\n p.push(x, y, z);\n const nn = norm([x - cx, y - cy, z]);\n n.push(...nn);\n uv.push(i / rs, j / ts);\n }\n for (let j = 1; j <= ts; j++)\n for (let i = 1; i <= rs; i++) {\n const a = (rs + 1) * j + i - 1, b = (rs + 1) * (j - 1) + i - 1, c = (rs + 1) * (j - 1) + i, d = (rs + 1) * j + i;\n idx.push(a, b, d, b, c, d);\n }\n return geo(p, n, uv, idx);\n}\n/** Flat normals for a geometry without them (per triangle; un-indexes the mesh). */\nexport function computeNormals(g: Geometry): Geometry {\n const P = g.positions, I = g.indices;\n const count = I ? I.length : P.length / 3;\n const pos = new Float32Array(count * 3), nrm = new Float32Array(count * 3), uvs = g.uvs ? new Float32Array(count * 2) : undefined;\n for (let t = 0; t < count; t += 3) {\n const v = [0, 1, 2].map((k) => (I ? I[t + k] : t + k));\n const a: Vec3 = [P[v[0] * 3], P[v[0] * 3 + 1], P[v[0] * 3 + 2]], b: Vec3 = [P[v[1] * 3], P[v[1] * 3 + 1], P[v[1] * 3 + 2]], c: Vec3 = [P[v[2] * 3], P[v[2] * 3 + 1], P[v[2] * 3 + 2]];\n const nn = norm(cross(sub(b, a), sub(c, a)));\n v.forEach((vi, k) => {\n pos.set(P.subarray(vi * 3, vi * 3 + 3), (t + k) * 3);\n nrm.set(nn, (t + k) * 3);\n if (uvs && g.uvs) uvs.set(g.uvs.subarray(vi * 2, vi * 2 + 2), (t + k) * 2);\n });\n }\n return { positions: pos, normals: nrm, uvs, mode: g.mode };\n}\n\n// ------------------------------------------------------------------ materials & textures\nexport interface GlTexture {\n source: TexImageSource | { width: number; height: number; data: Uint8Array | Uint8ClampedArray };\n /** sRGB colour data (default true for colour maps). */\n srgb?: boolean;\n repeat?: boolean;\n flipY?: boolean;\n /** Re-upload every frame a new video frame is ready. */\n video?: boolean;\n needsUpdate?: boolean;\n _gpu?: unknown;\n}\n\nexport interface Material {\n type: 'standard' | 'unlit' | 'shader';\n /** Linear RGBA multiplier (sRGB input converted by the shader). */\n color: [number, number, number, number];\n map?: GlTexture | null;\n metallic: number;\n roughness: number;\n emissive: Vec3;\n doubleSided?: boolean;\n transparent?: boolean;\n wireframe?: boolean;\n /** 'shader' materials: GLSL ES 3.00 fragment body + uniforms. */\n fragment?: string;\n uniforms?: Record<string, number | number[] | Float32Array | GlTexture>;\n _gpu?: unknown;\n}\n\nexport function standardMaterial(o: Partial<Material> = {}): Material {\n return { type: 'standard', color: [1, 1, 1, 1], metallic: 0, roughness: 0.6, emissive: [0, 0, 0], ...o };\n}\nexport function unlitMaterial(o: Partial<Material> = {}): Material {\n return { ...standardMaterial(o), type: 'unlit' };\n}\n/**\n * Custom fragment shader: `fragment` is GLSL ES 3.00 code defining\n * `vec4 shade()`; available: `v_pos` (world), `v_nrm`, `v_uv`, `u_time`,\n * `u_camPos`, `u_res` and your `uniforms` (float, vec2–4, sampler2D).\n */\nexport function shaderMaterial(fragment: string, uniforms: Material['uniforms'] = {}, o: Partial<Material> = {}): Material {\n return { ...standardMaterial(o), type: 'shader', fragment, uniforms };\n}\n/** '#ff8800' / 'rgb(…)' / [r, g, b] → linear-ready [r, g, b, a] (sRGB values 0–1; the shader linearises). */\nexport function color(c: string | number[], a = 1): [number, number, number, number] {\n if (Array.isArray(c)) return [c[0], c[1], c[2], c[3] ?? a];\n const h = /^#([0-9a-f]{3,8})$/i.exec(c.trim());\n if (h) {\n let s = h[1];\n if (s.length <= 4) s = s.split('').map((x) => x + x).join('');\n const v = parseInt(s.slice(0, 6), 16);\n return [((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, s.length === 8 ? parseInt(s.slice(6), 16) / 255 : a];\n }\n const m = /rgba?\\(([^)]+)\\)/.exec(c);\n if (m) {\n const p = m[1].split(/[\\s,/]+/).filter(Boolean).map(Number);\n return [p[0] / 255, p[1] / 255, p[2] / 255, p[3] ?? a];\n }\n return [1, 1, 1, a];\n}\nexport function texture(source: GlTexture['source'], o: Partial<GlTexture> = {}): GlTexture {\n const isVideo = typeof HTMLVideoElement !== 'undefined' && source instanceof HTMLVideoElement;\n return { source, srgb: true, repeat: true, flipY: false, video: isVideo, needsUpdate: true, ...o };\n}\n\n// ------------------------------------------------------------------ scene graph\nexport interface Mesh {\n geometry: Geometry;\n material: Material;\n}\n\nexport class GlNode {\n name = '';\n position: Vec3 = [0, 0, 0];\n rotation: Quat = [0, 0, 0, 1];\n scale: Vec3 = [1, 1, 1];\n /** Set to use a fixed local matrix instead of position / rotation / scale (glTF `matrix`). */\n matrix: Mat4 | null = null;\n children: GlNode[] = [];\n parent: GlNode | null = null;\n mesh: Mesh | Mesh[] | null = null;\n visible = true;\n /** Free-form data (loaders put source info here). */\n extras: Record<string, unknown> = {};\n readonly world: Mat4 = mat4.identity();\n constructor(name = '', mesh: Mesh | Mesh[] | null = null) {\n this.name = name;\n this.mesh = mesh;\n }\n add(...nodes: GlNode[]): this {\n for (const n of nodes) {\n n.parent?.remove(n);\n n.parent = this;\n this.children.push(n);\n }\n return this;\n }\n remove(n: GlNode): void {\n const i = this.children.indexOf(n);\n if (i >= 0) this.children.splice(i, 1);\n n.parent = null;\n }\n setEuler(x: number, y: number, z: number): this {\n this.rotation = quatFromEuler(x, y, z);\n return this;\n }\n local(): Mat4 {\n return this.matrix || mat4.compose(this.position, this.rotation, this.scale);\n }\n /** Recompute world matrices of this subtree. */\n updateWorld(parent?: Mat4): void {\n const m = parent ? mat4.multiply(parent, this.local()) : this.local();\n this.world.set(m);\n for (const c of this.children) c.updateWorld(this.world);\n }\n traverse(fn: (n: GlNode) => void): void {\n fn(this);\n for (const c of this.children) c.traverse(fn);\n }\n find(name: string): GlNode | null {\n let hit: GlNode | null = null;\n this.traverse((n) => {\n if (!hit && n.name === name) hit = n;\n });\n return hit;\n }\n}\n\nexport class Camera extends GlNode {\n fov = (45 * Math.PI) / 180;\n near = 0.05;\n far = 500;\n aspect = 1;\n target: Vec3 = [0, 0, 0];\n up: Vec3 = [0, 1, 0];\n constructor(o: { fov?: number; near?: number; far?: number; position?: Vec3; target?: Vec3 } = {}) {\n super('camera');\n if (o.fov) this.fov = (o.fov * Math.PI) / 180;\n if (o.near) this.near = o.near;\n if (o.far) this.far = o.far;\n if (o.position) this.position = [...o.position];\n if (o.target) this.target = [...o.target];\n }\n view(): Mat4 {\n return mat4.lookAt(this.position, this.target, this.up);\n }\n projection(): Mat4 {\n return mat4.perspective(this.fov, this.aspect, this.near, this.far);\n }\n}\n\nexport interface Light {\n type: 'directional' | 'point';\n /** Direction the light travels (directional) or position (point). */\n vector: Vec3;\n color: Vec3;\n intensity: number;\n}\n\nexport class Scene {\n root = new GlNode('scene');\n ambient: Vec3 = [0.35, 0.35, 0.4];\n lights: Light[] = [{ type: 'directional', vector: [-0.4, -1, -0.6], color: [1, 1, 1], intensity: 2.2 }];\n /** Clear colour (sRGB, 0–1) or null for transparent. */\n background: [number, number, number, number] | null = null;\n exposure = 1;\n add(...n: GlNode[]): this {\n this.root.add(...n);\n return this;\n }\n}\n\n/** World-space bounding box of a subtree's meshes. */\nexport function bounds(node: GlNode): { min: Vec3; max: Vec3; center: Vec3; radius: number } {\n node.updateWorld(node.parent ? node.parent.world : undefined);\n const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity];\n node.traverse((n) => {\n const meshes = n.mesh ? (Array.isArray(n.mesh) ? n.mesh : [n.mesh]) : [];\n for (const m of meshes) {\n const P = m.geometry.positions;\n for (let i = 0; i < P.length; i += 3) {\n const q = mat4.transformPoint(n.world, [P[i], P[i + 1], P[i + 2]]);\n for (let k = 0; k < 3; k++) {\n if (q[k] < min[k]) min[k] = q[k];\n if (q[k] > max[k]) max[k] = q[k];\n }\n }\n }\n });\n if (min[0] === Infinity) return { min: [0, 0, 0], max: [0, 0, 0], center: [0, 0, 0], radius: 0 };\n const center: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];\n return { min, max, center, radius: Math.hypot(max[0] - center[0], max[1] - center[1], max[2] - center[2]) };\n}\n\n/** Point the camera at a subtree so it fills the view. */\nexport function frameNode(camera: Camera, node: GlNode, padding = 1.25): void {\n const b = bounds(node);\n const dist = ((b.radius || 1) * padding) / Math.sin(camera.fov / 2);\n const dir = norm(sub(camera.position, camera.target).some((v) => v) ? sub(camera.position, camera.target) : [0.6, 0.4, 1]);\n camera.target = b.center;\n camera.position = [b.center[0] + dir[0] * dist, b.center[1] + dir[1] * dist, b.center[2] + dir[2] * dist];\n camera.near = Math.max(0.01, dist / 100);\n camera.far = dist * 10 + b.radius * 2;\n}\n\n// ------------------------------------------------------------------ video\n/** Seek a video from a 0–1 progress (scroll-scrubbed video). Pauses it. */\nexport function scrubVideo(video: HTMLVideoElement, progress: number): void {\n if (!video.duration || !isFinite(video.duration)) return;\n video.pause();\n const t = Math.min(video.duration - 0.001, Math.max(0, progress * video.duration));\n if ('fastSeek' in video && Math.abs(video.currentTime - t) > 1) (video as any).fastSeek(t);\n else video.currentTime = t;\n}\n\n// ------------------------------------------------------------------ renderer\nconst VS = `#version 300 es\nlayout(location=0) in vec3 a_pos;layout(location=1) in vec3 a_nrm;layout(location=2) in vec2 a_uv;\nuniform mat4 u_model,u_view,u_proj;uniform mat3 u_nmat;out vec3 v_pos,v_nrm;out vec2 v_uv;\nvoid main(){vec4 w=u_model*vec4(a_pos,1.0);v_pos=w.xyz;v_nrm=normalize(u_nmat*a_nrm);v_uv=a_uv;gl_Position=u_proj*u_view*w;gl_PointSize=2.0;}`;\nconst FS_HEAD = `#version 300 es\nprecision highp float;in vec3 v_pos,v_nrm;in vec2 v_uv;out vec4 o;\nuniform vec4 u_color;uniform vec3 u_emissive,u_camPos,u_ambient;uniform float u_metal,u_rough,u_exposure,u_time;uniform vec2 u_res;\nuniform sampler2D u_map;uniform int u_hasMap,u_nl,u_unlit;uniform vec4 u_lvec[4];uniform vec3 u_lcol[4];\nvec3 lin(vec3 c){return pow(c,vec3(2.2));}vec3 srgb(vec3 c){return pow(c,vec3(1.0/2.2));}\n`;\nconst FS_STD = `${FS_HEAD}void main(){vec4 base=vec4(lin(u_color.rgb),u_color.a);if(u_hasMap==1){vec4 t=texture(u_map,v_uv);base*=vec4(lin(t.rgb),t.a);}\nif(u_unlit==1){o=vec4(srgb(base.rgb),base.a);return;}\nvec3 N=normalize(v_nrm);if(!gl_FrontFacing)N=-N;vec3 V=normalize(u_camPos-v_pos);float r=clamp(u_rough,0.04,1.0),m=clamp(u_metal,0.0,1.0);\nvec3 F0=mix(vec3(0.04),base.rgb,m);vec3 c=u_ambient*base.rgb*(1.0-0.6*m)+u_ambient*F0*0.4;\nfor(int i=0;i<4;i++){if(i>=u_nl)break;vec3 L;float at=1.0;if(u_lvec[i].w>0.5){vec3 d=u_lvec[i].xyz-v_pos;float l=length(d);L=d/l;at=1.0/(1.0+0.09*l*l);}else L=normalize(-u_lvec[i].xyz);\nvec3 H=normalize(L+V);float NL=max(dot(N,L),0.0),NH=max(dot(N,H),0.0),NV=max(dot(N,V),1e-3),a=r*r,a2=a*a,dd=NH*NH*(a2-1.0)+1.0,D=a2/(3.14159*dd*dd),k=(r+1.0)*(r+1.0)/8.0;\nfloat G=NL/(NL*(1.0-k)+k)*NV/(NV*(1.0-k)+k);vec3 F=F0+(1.0-F0)*pow(1.0-max(dot(H,V),0.0),5.0);vec3 S=D*G*F/(4.0*NL*NV+1e-3);\nc+=((1.0-F)*(1.0-m)*base.rgb/3.14159+S)*u_lcol[i]*NL*at;}\nc=(c+u_emissive)*u_exposure;c=c/(c+1.0);o=vec4(srgb(c),base.a);}`;\n\nexport interface RendererOptions {\n alpha?: boolean;\n antialias?: boolean;\n /** Device-pixel-ratio cap (default 2). */\n maxDpr?: number;\n preserveDrawingBuffer?: boolean;\n}\n\nexport interface Renderer {\n gl: WebGL2RenderingContext;\n canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Match the canvas backing store to its CSS size × DPR (returns true when it changed). */\n resize(width?: number, height?: number): boolean;\n render(scene: Scene, camera: Camera, time?: number): void;\n /** Draw calls of the last frame. */\n readonly drawCalls: number;\n dispose(): void;\n}\n\n/** Create a WebGL2 renderer on a canvas (throws a clear error when WebGL2 is unavailable). */\nexport function createRenderer(canvas: HTMLCanvasElement | OffscreenCanvas, o: RendererOptions = {}): Renderer {\n const gl = canvas.getContext('webgl2', { alpha: o.alpha ?? true, antialias: o.antialias ?? true, premultipliedAlpha: false, preserveDrawingBuffer: !!o.preserveDrawingBuffer }) as WebGL2RenderingContext | null;\n if (!gl) throw new Error('[motionary] runtime/gl: WebGL2 is not available in this browser / context');\n const programs = new Map<string, { p: WebGLProgram; u: Map<string, WebGLUniformLocation | null> }>();\n const owned: { del(): void }[] = [];\n let draws = 0;\n const compile = (key: string, fs: string) => {\n let pr = programs.get(key);\n if (pr) return pr;\n const sh = (type: number, src: string) => {\n const s = gl.createShader(type)!;\n gl.shaderSource(s, src);\n gl.compileShader(s);\n if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error('[motionary] runtime/gl shader: ' + gl.getShaderInfoLog(s));\n return s;\n };\n const p = gl.createProgram()!;\n gl.attachShader(p, sh(gl.VERTEX_SHADER, VS));\n gl.attachShader(p, sh(gl.FRAGMENT_SHADER, fs));\n gl.linkProgram(p);\n if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error('[motionary] runtime/gl link: ' + gl.getProgramInfoLog(p));\n pr = { p, u: new Map() };\n programs.set(key, pr);\n owned.push({ del: () => gl.deleteProgram(p) });\n return pr;\n };\n const loc = (pr: { p: WebGLProgram; u: Map<string, WebGLUniformLocation | null> }, n: string) => {\n if (!pr.u.has(n)) pr.u.set(n, gl.getUniformLocation(pr.p, n));\n return pr.u.get(n)!;\n };\n const uploadGeo = (g: Geometry) => {\n const c = g._gpu as { vao: WebGLVertexArrayObject; count: number; type: number; indexed: boolean; v?: number; b: (WebGLBuffer | undefined)[] } | undefined;\n if (c) {\n if (c.v !== g.version) {\n c.v = g.version;\n [g.positions, g.normals].forEach((d, i) => {\n if (d && c.b[i]) {\n gl.bindBuffer(gl.ARRAY_BUFFER, c.b[i]!);\n gl.bufferData(gl.ARRAY_BUFFER, d, gl.DYNAMIC_DRAW);\n }\n });\n }\n return c;\n }\n const bufs: (WebGLBuffer | undefined)[] = [];\n const vao = gl.createVertexArray()!;\n gl.bindVertexArray(vao);\n const attr = (i: number, data: Float32Array | undefined, size: number, fallback: number[]) => {\n if (!data) {\n gl.disableVertexAttribArray(i);\n if (size === 3) gl.vertexAttrib3f(i, fallback[0], fallback[1], fallback[2]);\n else gl.vertexAttrib2f(i, fallback[0], fallback[1]);\n return;\n }\n const b = gl.createBuffer()!;\n owned.push({ del: () => gl.deleteBuffer(b) });\n bufs[i] = b;\n gl.bindBuffer(gl.ARRAY_BUFFER, b);\n gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(i);\n gl.vertexAttribPointer(i, size, gl.FLOAT, false, 0, 0);\n };\n attr(0, g.positions, 3, [0, 0, 0]);\n attr(1, g.normals, 3, [0, 0, 1]);\n attr(2, g.uvs, 2, [0, 0]);\n let count = g.positions.length / 3, type = 0;\n if (g.indices) {\n const b = gl.createBuffer()!;\n owned.push({ del: () => gl.deleteBuffer(b) });\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, g.indices, gl.STATIC_DRAW);\n count = g.indices.length;\n type = g.indices instanceof Uint32Array ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;\n }\n gl.bindVertexArray(null);\n owned.push({ del: () => gl.deleteVertexArray(vao) });\n return (g._gpu = { vao, count, type, indexed: !!g.indices, v: g.version, b: bufs });\n };\n const uploadTex = (t: GlTexture, unit: number) => {\n let tex = t._gpu as WebGLTexture | undefined;\n gl.activeTexture(gl.TEXTURE0 + unit);\n if (!tex) {\n tex = gl.createTexture()!;\n t._gpu = tex;\n owned.push({ del: () => gl.deleteTexture(tex!) });\n t.needsUpdate = true;\n if (t.video) {\n const v = t.source as HTMLVideoElement;\n const mark = () => {\n t.needsUpdate = true;\n (v as any).requestVideoFrameCallback?.(mark);\n };\n if ((v as any).requestVideoFrameCallback) (v as any).requestVideoFrameCallback(mark);\n }\n }\n gl.bindTexture(gl.TEXTURE_2D, tex);\n const v = t.video ? (t.source as HTMLVideoElement) : null;\n const videoReady = !v || v.readyState >= 2;\n if ((t.needsUpdate || (v && !(v as any).requestVideoFrameCallback && !v.paused)) && videoReady) {\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!t.flipY);\n const s = t.source as any;\n if (s && s.data && !(s instanceof ImageData)) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, s.width, s.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(s.data.buffer, s.data.byteOffset, s.data.byteLength));\n else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, s);\n const pot = (n: number) => (n & (n - 1)) === 0;\n const w = s.videoWidth || s.naturalWidth || s.width, h = s.videoHeight || s.naturalHeight || s.height;\n const mip = !v && pot(w) && pot(h);\n if (mip) gl.generateMipmap(gl.TEXTURE_2D);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, mip ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n const wrap = t.repeat && pot(w) && pot(h) ? gl.REPEAT : gl.CLAMP_TO_EDGE;\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n t.needsUpdate = false;\n }\n };\n const r: Renderer = {\n gl,\n canvas,\n get drawCalls() {\n return draws;\n },\n resize(w?: number, h?: number) {\n const c = canvas as HTMLCanvasElement;\n const dpr = Math.min(o.maxDpr ?? 2, (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1);\n const W = Math.max(1, Math.round((w ?? c.clientWidth ?? c.width) * dpr)), H = Math.max(1, Math.round((h ?? c.clientHeight ?? c.height) * dpr));\n if (c.width === W && c.height === H) return false;\n c.width = W;\n c.height = H;\n return true;\n },\n render(scene: Scene, camera: Camera, time = 0) {\n draws = 0;\n const W = gl.drawingBufferWidth, H = gl.drawingBufferHeight;\n gl.viewport(0, 0, W, H);\n camera.aspect = W / H || 1;\n const bg = scene.background;\n gl.clearColor(bg ? bg[0] : 0, bg ? bg[1] : 0, bg ? bg[2] : 0, bg ? bg[3] : 0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.enable(gl.DEPTH_TEST);\n scene.root.updateWorld();\n const view = camera.view(), proj = camera.projection();\n const lv = new Float32Array(16), lc = new Float32Array(12);\n scene.lights.slice(0, 4).forEach((l, i) => {\n lv.set([...l.vector, l.type === 'point' ? 1 : 0], i * 4);\n lc.set(l.color.map((c) => c * l.intensity), i * 3);\n });\n const opaque: [GlNode, Mesh][] = [], blend: [GlNode, Mesh][] = [];\n scene.root.traverse((n) => {\n if (!n.visible || !n.mesh) return;\n for (const m of Array.isArray(n.mesh) ? n.mesh : [n.mesh]) (m.material.transparent || m.material.color[3] < 1 ? blend : opaque).push([n, m]);\n });\n for (const [n, m] of [...opaque, ...blend]) {\n const mat = m.material;\n const key = mat.type === 'shader' ? 'shader:' + mat.fragment : 'std';\n const pr = compile(key, mat.type === 'shader' ? `${FS_HEAD}${Object.entries(mat.uniforms || {}).map(([k, v]) => `uniform ${typeof v === 'number' ? 'float' : (v as GlTexture).source ? 'sampler2D' : `vec${(v as number[]).length}`} ${k};`).join('')}\\n${mat.fragment}\\nvoid main(){o=shade();}` : FS_STD);\n gl.useProgram(pr.p);\n const U = (nm: string) => loc(pr, nm);\n gl.uniformMatrix4fv(U('u_model'), false, n.world);\n gl.uniformMatrix4fv(U('u_view'), false, view);\n gl.uniformMatrix4fv(U('u_proj'), false, proj);\n gl.uniformMatrix3fv(U('u_nmat'), false, mat4.normal(n.world));\n gl.uniform4fv(U('u_color'), mat.color);\n gl.uniform3fv(U('u_emissive'), mat.emissive);\n gl.uniform3fv(U('u_camPos'), camera.position);\n gl.uniform3fv(U('u_ambient'), scene.ambient);\n gl.uniform1f(U('u_metal'), mat.metallic);\n gl.uniform1f(U('u_rough'), mat.roughness);\n gl.uniform1f(U('u_exposure'), scene.exposure);\n gl.uniform1f(U('u_time'), time / 1000);\n gl.uniform2f(U('u_res'), W, H);\n gl.uniform1i(U('u_unlit'), mat.type === 'unlit' ? 1 : 0);\n gl.uniform1i(U('u_nl'), Math.min(4, scene.lights.length));\n gl.uniform4fv(U('u_lvec'), lv);\n gl.uniform3fv(U('u_lcol'), lc);\n let unit = 0;\n if (mat.map) {\n uploadTex(mat.map, unit);\n gl.uniform1i(U('u_map'), unit++);\n }\n gl.uniform1i(U('u_hasMap'), mat.map ? 1 : 0);\n for (const [k, v] of Object.entries(mat.uniforms || {})) {\n if (typeof v === 'number') gl.uniform1f(U(k), v);\n else if ((v as GlTexture).source) {\n uploadTex(v as GlTexture, unit);\n gl.uniform1i(U(k), unit++);\n } else {\n const a = v as number[];\n (a.length === 2 ? gl.uniform2fv : a.length === 3 ? gl.uniform3fv : gl.uniform4fv).call(gl, U(k), a as any);\n }\n }\n if (mat.doubleSided) gl.disable(gl.CULL_FACE);\n else gl.enable(gl.CULL_FACE);\n if (mat.transparent || mat.color[3] < 1) {\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n gl.depthMask(false);\n } else {\n gl.disable(gl.BLEND);\n gl.depthMask(true);\n }\n const g = uploadGeo(m.geometry);\n gl.bindVertexArray(g.vao);\n const mode = m.geometry.mode === 'lines' || mat.wireframe ? gl.LINES : m.geometry.mode === 'points' ? gl.POINTS : gl.TRIANGLES;\n if (g.indexed) gl.drawElements(mode, g.count, g.type, 0);\n else gl.drawArrays(mode, 0, g.count);\n draws++;\n }\n gl.bindVertexArray(null);\n gl.depthMask(true);\n },\n dispose() {\n owned.splice(0).forEach((x) => x.del());\n programs.clear();\n },\n };\n return r;\n}\n\n// ------------------------------------------------------------------ orbit controls\nexport interface OrbitOptions {\n autoRotate?: number;\n damping?: number;\n minDistance?: number;\n maxDistance?: number;\n zoom?: boolean;\n}\n\n/** Drag to orbit, wheel / pinch to zoom, arrow keys (when the element has focus). Call `update(dt)` per frame. */\nexport function orbitControls(camera: Camera, el: HTMLElement, o: OrbitOptions = {}): { update(dt: number): boolean; dispose(): void; autoRotate: number } {\n const off = sub(camera.position, camera.target);\n let dist = Math.hypot(...off), theta = Math.atan2(off[0], off[2]), phi = Math.acos(Math.min(1, Math.max(-1, off[1] / (dist || 1))));\n let vt = 0, vp = 0, vz = 0, drag = false, lx = 0, ly = 0;\n const pts = new Map<number, [number, number]>();\n let pinch = 0;\n const damp = o.damping ?? 0.12;\n const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n const ctl = { autoRotate: reduce ? 0 : o.autoRotate ?? 0, update, dispose };\n const on = (t: EventTarget, ty: string, f: (e: any) => void, opt?: AddEventListenerOptions) => {\n t.addEventListener(ty, f, opt);\n return () => t.removeEventListener(ty, f, opt);\n };\n const offs = [\n on(el, 'pointerdown', (e: PointerEvent) => {\n pts.set(e.pointerId, [e.clientX, e.clientY]);\n drag = true;\n lx = e.clientX;\n ly = e.clientY;\n el.setPointerCapture?.(e.pointerId);\n }),\n on(el, 'pointermove', (e: PointerEvent) => {\n if (!pts.has(e.pointerId)) return;\n pts.set(e.pointerId, [e.clientX, e.clientY]);\n if (pts.size === 2 && o.zoom !== false) {\n const [a, b] = Array.from(pts.values());\n const d = Math.hypot(a[0] - b[0], a[1] - b[1]);\n if (pinch) vz += (pinch - d) * 0.004;\n pinch = d;\n return;\n }\n if (!drag) return;\n vt -= (e.clientX - lx) * 0.005;\n vp -= (e.clientY - ly) * 0.005;\n lx = e.clientX;\n ly = e.clientY;\n }),\n on(el, 'pointerup', (e: PointerEvent) => {\n pts.delete(e.pointerId);\n pinch = 0;\n drag = pts.size > 0;\n }),\n on(el, 'pointercancel', (e: PointerEvent) => {\n pts.delete(e.pointerId);\n drag = false;\n }),\n on(el, 'wheel', (e: WheelEvent) => {\n if (o.zoom === false) return;\n e.preventDefault();\n vz += Math.sign(e.deltaY) * 0.08;\n }, { passive: false }),\n on(el, 'keydown', (e: KeyboardEvent) => {\n const k = { ArrowLeft: [0.1, 0, 0], ArrowRight: [-0.1, 0, 0], ArrowUp: [0, 0.1, 0], ArrowDown: [0, -0.1, 0], '+': [0, 0, -0.1], '-': [0, 0, 0.1] }[e.key];\n if (!k) return;\n e.preventDefault();\n vt += k[0];\n vp += k[1];\n vz += k[2];\n }),\n ];\n function update(dt: number): boolean {\n const moving = Math.abs(vt) + Math.abs(vp) + Math.abs(vz) > 1e-5 || ctl.autoRotate;\n theta += vt + (ctl.autoRotate && !drag ? (ctl.autoRotate * dt) / 1000 : 0);\n phi = Math.min(Math.PI - 0.05, Math.max(0.05, phi + vp));\n dist = Math.min(o.maxDistance ?? Infinity, Math.max(o.minDistance ?? 0.01, dist * (1 + vz)));\n const k = Math.pow(1 - damp, dt / 16.7);\n vt *= k;\n vp *= k;\n vz *= k;\n const t = camera.target;\n camera.position = [t[0] + dist * Math.sin(phi) * Math.sin(theta), t[1] + dist * Math.cos(phi), t[2] + dist * Math.sin(phi) * Math.cos(theta)];\n return !!moving;\n }\n function dispose() {\n offs.forEach((f) => f());\n }\n return ctl;\n}\n\nexport interface GlApi {\n mat4: typeof mat4;\n quatFromEuler: typeof quatFromEuler;\n quatMultiply: typeof quatMultiply;\n quatSlerp: typeof quatSlerp;\n box: typeof box;\n plane: typeof plane;\n sphere: typeof sphere;\n torus: typeof torus;\n computeNormals: typeof computeNormals;\n standardMaterial: typeof standardMaterial;\n unlitMaterial: typeof unlitMaterial;\n shaderMaterial: typeof shaderMaterial;\n color: typeof color;\n texture: typeof texture;\n GlNode: typeof GlNode;\n Camera: typeof Camera;\n Scene: typeof Scene;\n bounds: typeof bounds;\n frameNode: typeof frameNode;\n scrubVideo: typeof scrubVideo;\n createRenderer: typeof createRenderer;\n orbitControls: typeof orbitControls;\n}\n\n/** The module object for `use(gl)`. */\nexport const gl: RuntimeModule<GlApi> = {\n id: 'gl',\n version: RUNTIME_VERSION,\n requires: ['core'],\n api: { mat4, quatFromEuler, quatMultiply, quatSlerp, box, plane, sphere, torus, computeNormals, standardMaterial, unlitMaterial, shaderMaterial, color, texture, GlNode, Camera, Scene, bounds, frameNode, scrubVideo, createRenderer, orbitControls },\n};\n","/**\n * `motionary/runtime/gltf-anim` (10.8) — glTF 2.0 animation, skinning and\n * morph targets for models loaded by `motionary/runtime/format-gltf`\n * (own implementation; requires `use(gl, formatGltf, gltfAnim)`).\n *\n * - animation channels on node `translation` / `rotation` / `scale` /\n * `weights` with `LINEAR` (quaternions slerped), `STEP` and\n * `CUBICSPLINE` (Hermite with in / out tangents) samplers;\n * - morph targets (POSITION + NORMAL deltas) with mesh default weights,\n * node weights and animated weights;\n * - skins: joint hierarchy, inverse bind matrices, 4 joints / vertex\n * (JOINTS_0 / WEIGHTS_0), skinned on the CPU and re-uploaded each frame\n * (`geometry.version`), so it works with every runtime/gl material;\n * - `gltfAnimator(model)` plays a clip (by name or index) with loop / speed\n * / seek, `update(dt)` from your loop or `play()` on the shared ticker.\n *\n * Sampling and deformation are pure (SSR / workers / tests).\n */\nimport { RUNTIME_VERSION, requireModule, type RuntimeModule } from './registry';\nimport type { CoreApi } from './index';\nimport { mat4, quatSlerp, type GlNode, type Geometry, type Mat4, type Quat } from './gl';\n\ntype Num = number;\nexport type ChannelPath = 'translation' | 'rotation' | 'scale' | 'weights';\nexport type Interpolation = 'LINEAR' | 'STEP' | 'CUBICSPLINE';\nexport interface GltfChannel {\n node: GlNode;\n path: ChannelPath;\n interpolation: Interpolation;\n times: Float32Array;\n values: Float32Array;\n /** Components per key (3, 4 or the morph target count). */\n size: Num;\n}\nexport interface GltfClip {\n name: string;\n duration: Num;\n channels: GltfChannel[];\n}\n\n/** Morph / skin source data kept on a geometry by format-gltf (10.8). */\nexport interface DeformSource {\n positions: Float32Array;\n normals?: Float32Array;\n joints?: Float32Array;\n weights?: Float32Array;\n targets?: { positions?: Float32Array; normals?: Float32Array }[];\n}\n\nconst model = (root: GlNode): { gltf: any; nodes: GlNode[]; read: (i: Num) => Float32Array } => {\n const x = root.extras as any;\n if (!x?.gltf || !x.read) throw new Error('[motionary] gltf-anim: pass the node returned by loadGltf() / gltfToNode() (motionary/runtime/format-gltf 10.8+)');\n return x;\n};\n\n/** The animation clips of a loaded model. */\nexport function gltfClips(root: GlNode): GltfClip[] {\n const { gltf, nodes, read } = model(root);\n return (gltf.animations || []).map((a: any, ai: Num) => {\n let duration = 0;\n const channels: GltfChannel[] = [];\n for (const c of a.channels || []) {\n const node = nodes[c.target?.node];\n const s = a.samplers?.[c.sampler];\n if (!node || !s || !['translation', 'rotation', 'scale', 'weights'].includes(c.target.path)) continue; // KHR_animation_pointer etc.\n const times = read(s.input), values = read(s.output);\n const interpolation: Interpolation = s.interpolation || 'LINEAR';\n const size = values.length / times.length / (interpolation === 'CUBICSPLINE' ? 3 : 1);\n duration = Math.max(duration, times[times.length - 1] || 0);\n channels.push({ node, path: c.target.path, interpolation, times, values, size });\n }\n return { name: a.name || `animation${ai}`, duration, channels };\n });\n}\n\n/** Value of a channel at time `t` (seconds; clamped to the key range). */\nexport function sampleChannel(ch: GltfChannel, t: Num): Num[] {\n const { times: T, values: V, size: n } = ch;\n const cubic = ch.interpolation === 'CUBICSPLINE';\n const at = (k: Num) => Array.from(V.subarray((cubic ? k * 3 + 1 : k) * n, (cubic ? k * 3 + 1 : k) * n + n));\n const last = T.length - 1;\n if (t <= T[0] || last === 0) return at(0);\n if (t >= T[last]) return at(last);\n let k = 0;\n while (k < last - 1 && T[k + 1] <= t) k++;\n const td = T[k + 1] - T[k], s = (t - T[k]) / td;\n let out: Num[];\n if (ch.interpolation === 'STEP') return at(k);\n if (cubic) {\n const s2 = s * s, s3 = s2 * s;\n const h00 = 2 * s3 - 3 * s2 + 1, h10 = s3 - 2 * s2 + s, h01 = -2 * s3 + 3 * s2, h11 = s3 - s2;\n const p0 = k * 3 * n, p1 = (k + 1) * 3 * n;\n out = Array.from({ length: n }, (_, i) => h00 * V[p0 + n + i] + h10 * td * V[p0 + 2 * n + i] + h01 * V[p1 + n + i] + h11 * td * V[p1 + i]);\n if (ch.path === 'rotation') {\n const l = Math.hypot(...out) || 1;\n out = out.map((v) => v / l);\n }\n return out;\n }\n const a = at(k), b = at(k + 1);\n if (ch.path === 'rotation') return quatSlerp(a as Quat, b as Quat, s);\n return a.map((v, i) => v + (b[i] - v) * s);\n}\n\n/** Pose the model at time `t` of a clip (sets node TRS and morph weights). */\nexport function applyClip(clip: GltfClip, t: Num): void {\n for (const ch of clip.channels) {\n const v = sampleChannel(ch, t);\n const n = ch.node;\n if (ch.path === 'weights') n.extras.weights = v;\n else {\n n.matrix = null; // animated nodes are TRS (glTF spec)\n if (ch.path === 'translation') n.position = v as [Num, Num, Num];\n else if (ch.path === 'rotation') n.rotation = v as Quat;\n else n.scale = v as [Num, Num, Num];\n }\n }\n}\n\nconst meshesOf = (n: GlNode) => (n.mesh ? (Array.isArray(n.mesh) ? n.mesh : [n.mesh]) : []);\n\n/**\n * Apply morph weights and skins to every deformable mesh of the model\n * (call after posing; updates world matrices). Returns how many meshes changed.\n */\nexport function deformModel(root: GlNode): Num {\n const { gltf, nodes, read } = model(root);\n root.updateWorld();\n let changed = 0;\n const cache = ((root.extras as any).skinCache ||= {}) as Record<Num, { joints: GlNode[]; ibm: Mat4[] }>;\n for (const node of nodes) {\n const ms = meshesOf(node);\n if (!ms.length) continue;\n const si = node.extras.skin as Num | undefined;\n let jm: Mat4[] | null = null;\n if (si !== undefined && gltf.skins?.[si]) {\n const sk = gltf.skins[si];\n const c = (cache[si] ||= {\n joints: sk.joints.map((j: Num) => nodes[j]),\n ibm: sk.joints.map((_: Num, i: Num) => (sk.inverseBindMatrices !== undefined ? new Float32Array(read(sk.inverseBindMatrices).subarray(i * 16, i * 16 + 16)) : mat4.identity())),\n });\n const inv = mat4.invert(node.world) || mat4.identity();\n jm = c.joints.map((j, i) => mat4.multiply(inv, mat4.multiply(j.world, c.ibm[i])));\n }\n const w = (node.extras.weights as Num[] | undefined) || [];\n for (const m of ms) {\n const g = m.geometry as Geometry & { deform?: DeformSource };\n const src = g.deform;\n if (!src || (!jm && !src.targets?.length)) continue;\n deformGeometry(g, src, w, jm);\n changed++;\n }\n }\n return changed;\n}\n\n/** Morph + skin one geometry from its source data (pure). */\nexport function deformGeometry(g: Geometry, src: DeformSource, weights: Num[], joints: Mat4[] | null): void {\n const P = src.positions, N = src.normals, n = P.length / 3;\n const pos = g.positions !== P && g.positions.length === P.length ? g.positions : (g.positions = new Float32Array(P.length));\n const nrm = N ? (g.normals && g.normals !== N && g.normals.length === N.length ? g.normals : (g.normals = new Float32Array(N.length))) : null;\n pos.set(P);\n if (nrm && N) nrm.set(N);\n (src.targets || []).forEach((tg, k) => {\n const wk = weights[k] || 0;\n if (!wk) return;\n if (tg.positions) for (let i = 0; i < pos.length; i++) pos[i] += wk * tg.positions[i];\n if (tg.normals && nrm) for (let i = 0; i < nrm.length; i++) nrm[i] += wk * tg.normals[i];\n });\n if (joints && src.joints && src.weights) {\n const J = src.joints, W = src.weights, m = new Float32Array(16);\n for (let v = 0; v < n; v++) {\n m.fill(0);\n let tw = 0;\n for (let k = 0; k < 4; k++) {\n const wt = W[v * 4 + k];\n if (!wt) continue;\n const jm = joints[J[v * 4 + k]];\n if (!jm) continue;\n tw += wt;\n for (let e = 0; e < 16; e++) m[e] += wt * jm[e];\n }\n if (!tw) continue;\n const x = pos[v * 3], y = pos[v * 3 + 1], z = pos[v * 3 + 2];\n pos[v * 3] = m[0] * x + m[4] * y + m[8] * z + m[12];\n pos[v * 3 + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];\n pos[v * 3 + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];\n if (nrm) {\n const a = nrm[v * 3], b = nrm[v * 3 + 1], c = nrm[v * 3 + 2];\n const nx = m[0] * a + m[4] * b + m[8] * c, ny = m[1] * a + m[5] * b + m[9] * c, nz = m[2] * a + m[6] * b + m[10] * c;\n const l = Math.hypot(nx, ny, nz) || 1;\n nrm[v * 3] = nx / l;\n nrm[v * 3 + 1] = ny / l;\n nrm[v * 3 + 2] = nz / l;\n }\n }\n }\n g.version = (g.version || 0) + 1;\n}\n\nexport interface GltfAnimatorOptions {\n /** Clip name or index (default 0). */\n clip?: string | Num;\n loop?: boolean;\n speed?: Num;\n}\nexport interface GltfAnimator {\n readonly clips: GltfClip[];\n readonly clip: GltfClip | null;\n time: Num;\n speed: Num;\n loop: boolean;\n readonly playing: boolean;\n /** Switch clip (name or index); keeps playing state. */\n use(clip: string | Num): void;\n seek(t: Num): void;\n /** Advance by `dt` seconds and pose + deform. */\n update(dt: Num): void;\n /** Run on the shared ticker. */\n play(): void;\n pause(): void;\n dispose(): void;\n}\n\n/** A clip player for a loaded model. */\nexport function gltfAnimator(root: GlNode, o: GltfAnimatorOptions = {}): GltfAnimator {\n const clips = gltfClips(root);\n let clip: GltfClip | null = null, off: (() => void) | null = null;\n const pick = (c: string | Num) => (typeof c === 'number' ? clips[c] : clips.find((x) => x.name === c) || clips[Number(c)]) || null;\n const pose = () => {\n if (clip) applyClip(clip, a.time);\n deformModel(root);\n };\n const a: GltfAnimator = {\n clips,\n get clip() {\n return clip;\n },\n time: 0,\n speed: o.speed ?? 1,\n loop: o.loop ?? true,\n get playing() {\n return !!off;\n },\n use(c) {\n clip = pick(c);\n a.time = 0;\n pose();\n },\n seek(t) {\n const d = clip?.duration || 0;\n a.time = d ? (a.loop ? ((t % d) + d) % d : Math.min(d, Math.max(0, t))) : 0;\n pose();\n },\n update(dt) {\n a.seek(a.time + dt * a.speed);\n },\n play() {\n if (!off) off = requireModule<CoreApi>('core', 'motionary/runtime/gltf-anim').getTicker().add((_, ms) => a.update(Math.min(ms, 100) / 1000));\n },\n pause() {\n off?.();\n off = null;\n },\n dispose() {\n a.pause();\n },\n };\n clip = pick(o.clip ?? 0);\n pose();\n return a;\n}\n\nexport interface GltfAnimApi {\n gltfClips: typeof gltfClips;\n sampleChannel: typeof sampleChannel;\n applyClip: typeof applyClip;\n deformModel: typeof deformModel;\n deformGeometry: typeof deformGeometry;\n gltfAnimator: typeof gltfAnimator;\n}\n\nexport const gltfAnim: RuntimeModule<GltfAnimApi> = { id: 'gltf-anim', version: RUNTIME_VERSION, requires: ['core', 'gl', 'format-gltf'], api: { gltfClips, sampleChannel, applyClip, deformModel, deformGeometry, gltfAnimator } };\n","// CDN build: load runtime.iife.js first, then this file → registers motionary/runtime/gltf-anim and adds its API to window.MotionaryRuntime.\nimport { register } from '../registry';\nimport { gltfAnim } from '../gltf-anim';\nexport * from '../gltf-anim';\nregister(gltfAnim);\n"],"names":["mat4","identity","Float32Array","multiply","a","b","out","c","r","perspective","fovy","aspect","near","far","f","Math","tan","nf","lookAt","eye","target","up","z","sub","norm","some","v","x","cross","abs","y","dot","compose","t","q","s","w","x2","y2","z2","xx","xy","xz","yy","yz","zz","wx","wy","wz","invert","m","o","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","normal","i","transformPoint","p","l","hypot","model","root","extras","gltf","read","Error","gltfClips","nodes","animations","map","ai","duration","channels","node","samplers","sampler","includes","path","times","input","values","output","interpolation","size","length","max","push","name","sampleChannel","ch","T","V","n","cubic","at","k","Array","from","subarray","last","td","s2","s3","h00","h10","h01","h11","p0","p1","_","d","bb","th","acos","sin","wa","wb","quatSlerp","applyClip","clip","weights","matrix","position","rotation","scale","meshesOf","mesh","isArray","deformModel","updateWorld","changed","cache","_a","skinCache","ms","si","skin","jm","undefined","skins","sk","joints","j","ibm","inverseBindMatrices","inv","world","g","geometry","src","deform","targets","deformGeometry","P","positions","N","normals","pos","nrm","set","forEach","tg","wk","J","W","fill","tw","wt","e","nx","ny","nz","version","gltfAnimator","clips","off","pick","find","Number","pose","time","speed","loop","playing","use","seek","min","update","dt","play","requireModule","getTicker","add","pause","dispose","gltfAnim","id","RUNTIME_VERSION","requires","api","register"],"mappings":"4BA+BO,MAAMA,EAAO,CAClBC,SAAU,IAAY,IAAIC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,OACJ,GAIF,OAFA1E,EAAOyD,EAAKxJ,EAAE+F,MAAQ,GACtB4D,IACO1M,CACT,CAWO,MAAM0N,EAAuC,CAAEC,GAAI,YAAaxB,QAASyB,kBAAiBC,SAAU,CAAC,OAAQ,KAAM,eAAgBC,IAAK,CAAErI,YAAWsB,gBAAe8B,YAAWU,cAAawB,iBAAgBqB,iBCtRnN2B,EAAAA,SAASL"}
@@ -0,0 +1,243 @@
1
+ import { R as RUNTIME_VERSION, r as requireModule } from '../chunks/registry-Bkt3-3ET.js';
2
+ import { mat4, quatSlerp } from './gl.js';
3
+
4
+ /**
5
+ * `motionary/runtime/gltf-anim` (10.8) — glTF 2.0 animation, skinning and
6
+ * morph targets for models loaded by `motionary/runtime/format-gltf`
7
+ * (own implementation; requires `use(gl, formatGltf, gltfAnim)`).
8
+ *
9
+ * - animation channels on node `translation` / `rotation` / `scale` /
10
+ * `weights` with `LINEAR` (quaternions slerped), `STEP` and
11
+ * `CUBICSPLINE` (Hermite with in / out tangents) samplers;
12
+ * - morph targets (POSITION + NORMAL deltas) with mesh default weights,
13
+ * node weights and animated weights;
14
+ * - skins: joint hierarchy, inverse bind matrices, 4 joints / vertex
15
+ * (JOINTS_0 / WEIGHTS_0), skinned on the CPU and re-uploaded each frame
16
+ * (`geometry.version`), so it works with every runtime/gl material;
17
+ * - `gltfAnimator(model)` plays a clip (by name or index) with loop / speed
18
+ * / seek, `update(dt)` from your loop or `play()` on the shared ticker.
19
+ *
20
+ * Sampling and deformation are pure (SSR / workers / tests).
21
+ */
22
+ const model = (root) => {
23
+ const x = root.extras;
24
+ if (!x?.gltf || !x.read)
25
+ throw new Error('[motionary] gltf-anim: pass the node returned by loadGltf() / gltfToNode() (motionary/runtime/format-gltf 10.8+)');
26
+ return x;
27
+ };
28
+ /** The animation clips of a loaded model. */
29
+ function gltfClips(root) {
30
+ const { gltf, nodes, read } = model(root);
31
+ return (gltf.animations || []).map((a, ai) => {
32
+ let duration = 0;
33
+ const channels = [];
34
+ for (const c of a.channels || []) {
35
+ const node = nodes[c.target?.node];
36
+ const s = a.samplers?.[c.sampler];
37
+ if (!node || !s || !['translation', 'rotation', 'scale', 'weights'].includes(c.target.path))
38
+ continue; // KHR_animation_pointer etc.
39
+ const times = read(s.input), values = read(s.output);
40
+ const interpolation = s.interpolation || 'LINEAR';
41
+ const size = values.length / times.length / (interpolation === 'CUBICSPLINE' ? 3 : 1);
42
+ duration = Math.max(duration, times[times.length - 1] || 0);
43
+ channels.push({ node, path: c.target.path, interpolation, times, values, size });
44
+ }
45
+ return { name: a.name || `animation${ai}`, duration, channels };
46
+ });
47
+ }
48
+ /** Value of a channel at time `t` (seconds; clamped to the key range). */
49
+ function sampleChannel(ch, t) {
50
+ const { times: T, values: V, size: n } = ch;
51
+ const cubic = ch.interpolation === 'CUBICSPLINE';
52
+ const at = (k) => Array.from(V.subarray((cubic ? k * 3 + 1 : k) * n, (cubic ? k * 3 + 1 : k) * n + n));
53
+ const last = T.length - 1;
54
+ if (t <= T[0] || last === 0)
55
+ return at(0);
56
+ if (t >= T[last])
57
+ return at(last);
58
+ let k = 0;
59
+ while (k < last - 1 && T[k + 1] <= t)
60
+ k++;
61
+ const td = T[k + 1] - T[k], s = (t - T[k]) / td;
62
+ let out;
63
+ if (ch.interpolation === 'STEP')
64
+ return at(k);
65
+ if (cubic) {
66
+ const s2 = s * s, s3 = s2 * s;
67
+ const h00 = 2 * s3 - 3 * s2 + 1, h10 = s3 - 2 * s2 + s, h01 = -2 * s3 + 3 * s2, h11 = s3 - s2;
68
+ const p0 = k * 3 * n, p1 = (k + 1) * 3 * n;
69
+ out = Array.from({ length: n }, (_, i) => h00 * V[p0 + n + i] + h10 * td * V[p0 + 2 * n + i] + h01 * V[p1 + n + i] + h11 * td * V[p1 + i]);
70
+ if (ch.path === 'rotation') {
71
+ const l = Math.hypot(...out) || 1;
72
+ out = out.map((v) => v / l);
73
+ }
74
+ return out;
75
+ }
76
+ const a = at(k), b = at(k + 1);
77
+ if (ch.path === 'rotation')
78
+ return quatSlerp(a, b, s);
79
+ return a.map((v, i) => v + (b[i] - v) * s);
80
+ }
81
+ /** Pose the model at time `t` of a clip (sets node TRS and morph weights). */
82
+ function applyClip(clip, t) {
83
+ for (const ch of clip.channels) {
84
+ const v = sampleChannel(ch, t);
85
+ const n = ch.node;
86
+ if (ch.path === 'weights')
87
+ n.extras.weights = v;
88
+ else {
89
+ n.matrix = null; // animated nodes are TRS (glTF spec)
90
+ if (ch.path === 'translation')
91
+ n.position = v;
92
+ else if (ch.path === 'rotation')
93
+ n.rotation = v;
94
+ else
95
+ n.scale = v;
96
+ }
97
+ }
98
+ }
99
+ const meshesOf = (n) => (n.mesh ? (Array.isArray(n.mesh) ? n.mesh : [n.mesh]) : []);
100
+ /**
101
+ * Apply morph weights and skins to every deformable mesh of the model
102
+ * (call after posing; updates world matrices). Returns how many meshes changed.
103
+ */
104
+ function deformModel(root) {
105
+ var _a;
106
+ const { gltf, nodes, read } = model(root);
107
+ root.updateWorld();
108
+ let changed = 0;
109
+ const cache = ((_a = root.extras).skinCache || (_a.skinCache = {}));
110
+ for (const node of nodes) {
111
+ const ms = meshesOf(node);
112
+ if (!ms.length)
113
+ continue;
114
+ const si = node.extras.skin;
115
+ let jm = null;
116
+ if (si !== undefined && gltf.skins?.[si]) {
117
+ const sk = gltf.skins[si];
118
+ const c = (cache[si] || (cache[si] = {
119
+ joints: sk.joints.map((j) => nodes[j]),
120
+ ibm: sk.joints.map((_, i) => (sk.inverseBindMatrices !== undefined ? new Float32Array(read(sk.inverseBindMatrices).subarray(i * 16, i * 16 + 16)) : mat4.identity())),
121
+ }));
122
+ const inv = mat4.invert(node.world) || mat4.identity();
123
+ jm = c.joints.map((j, i) => mat4.multiply(inv, mat4.multiply(j.world, c.ibm[i])));
124
+ }
125
+ const w = node.extras.weights || [];
126
+ for (const m of ms) {
127
+ const g = m.geometry;
128
+ const src = g.deform;
129
+ if (!src || (!jm && !src.targets?.length))
130
+ continue;
131
+ deformGeometry(g, src, w, jm);
132
+ changed++;
133
+ }
134
+ }
135
+ return changed;
136
+ }
137
+ /** Morph + skin one geometry from its source data (pure). */
138
+ function deformGeometry(g, src, weights, joints) {
139
+ const P = src.positions, N = src.normals, n = P.length / 3;
140
+ const pos = g.positions !== P && g.positions.length === P.length ? g.positions : (g.positions = new Float32Array(P.length));
141
+ const nrm = N ? (g.normals && g.normals !== N && g.normals.length === N.length ? g.normals : (g.normals = new Float32Array(N.length))) : null;
142
+ pos.set(P);
143
+ if (nrm && N)
144
+ nrm.set(N);
145
+ (src.targets || []).forEach((tg, k) => {
146
+ const wk = weights[k] || 0;
147
+ if (!wk)
148
+ return;
149
+ if (tg.positions)
150
+ for (let i = 0; i < pos.length; i++)
151
+ pos[i] += wk * tg.positions[i];
152
+ if (tg.normals && nrm)
153
+ for (let i = 0; i < nrm.length; i++)
154
+ nrm[i] += wk * tg.normals[i];
155
+ });
156
+ if (joints && src.joints && src.weights) {
157
+ const J = src.joints, W = src.weights, m = new Float32Array(16);
158
+ for (let v = 0; v < n; v++) {
159
+ m.fill(0);
160
+ let tw = 0;
161
+ for (let k = 0; k < 4; k++) {
162
+ const wt = W[v * 4 + k];
163
+ if (!wt)
164
+ continue;
165
+ const jm = joints[J[v * 4 + k]];
166
+ if (!jm)
167
+ continue;
168
+ tw += wt;
169
+ for (let e = 0; e < 16; e++)
170
+ m[e] += wt * jm[e];
171
+ }
172
+ if (!tw)
173
+ continue;
174
+ const x = pos[v * 3], y = pos[v * 3 + 1], z = pos[v * 3 + 2];
175
+ pos[v * 3] = m[0] * x + m[4] * y + m[8] * z + m[12];
176
+ pos[v * 3 + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];
177
+ pos[v * 3 + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];
178
+ if (nrm) {
179
+ const a = nrm[v * 3], b = nrm[v * 3 + 1], c = nrm[v * 3 + 2];
180
+ const nx = m[0] * a + m[4] * b + m[8] * c, ny = m[1] * a + m[5] * b + m[9] * c, nz = m[2] * a + m[6] * b + m[10] * c;
181
+ const l = Math.hypot(nx, ny, nz) || 1;
182
+ nrm[v * 3] = nx / l;
183
+ nrm[v * 3 + 1] = ny / l;
184
+ nrm[v * 3 + 2] = nz / l;
185
+ }
186
+ }
187
+ }
188
+ g.version = (g.version || 0) + 1;
189
+ }
190
+ /** A clip player for a loaded model. */
191
+ function gltfAnimator(root, o = {}) {
192
+ const clips = gltfClips(root);
193
+ let clip = null, off = null;
194
+ const pick = (c) => (typeof c === 'number' ? clips[c] : clips.find((x) => x.name === c) || clips[Number(c)]) || null;
195
+ const pose = () => {
196
+ if (clip)
197
+ applyClip(clip, a.time);
198
+ deformModel(root);
199
+ };
200
+ const a = {
201
+ clips,
202
+ get clip() {
203
+ return clip;
204
+ },
205
+ time: 0,
206
+ speed: o.speed ?? 1,
207
+ loop: o.loop ?? true,
208
+ get playing() {
209
+ return !!off;
210
+ },
211
+ use(c) {
212
+ clip = pick(c);
213
+ a.time = 0;
214
+ pose();
215
+ },
216
+ seek(t) {
217
+ const d = clip?.duration || 0;
218
+ a.time = d ? (a.loop ? ((t % d) + d) % d : Math.min(d, Math.max(0, t))) : 0;
219
+ pose();
220
+ },
221
+ update(dt) {
222
+ a.seek(a.time + dt * a.speed);
223
+ },
224
+ play() {
225
+ if (!off)
226
+ off = requireModule('core', 'motionary/runtime/gltf-anim').getTicker().add((_, ms) => a.update(Math.min(ms, 100) / 1000));
227
+ },
228
+ pause() {
229
+ off?.();
230
+ off = null;
231
+ },
232
+ dispose() {
233
+ a.pause();
234
+ },
235
+ };
236
+ clip = pick(o.clip ?? 0);
237
+ pose();
238
+ return a;
239
+ }
240
+ const gltfAnim = { id: 'gltf-anim', version: RUNTIME_VERSION, requires: ['core', 'gl', 'format-gltf'], api: { gltfClips, sampleChannel, applyClip, deformModel, deformGeometry, gltfAnimator } };
241
+
242
+ export { applyClip, deformGeometry, deformModel, gltfAnim, gltfAnimator, gltfClips, sampleChannel };
243
+ //# sourceMappingURL=gltf-anim.js.map