motionary 10.4.0 → 10.5.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 (94) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +37 -0
  3. package/dist/chunks/{anim-image-DDdb9q3X.js → anim-image-BlNPv4JG.js} +2 -2
  4. package/dist/chunks/{anim-image-DDdb9q3X.js.map → anim-image-BlNPv4JG.js.map} +1 -1
  5. package/dist/chunks/{anim-image-blQgPFFS.cjs → anim-image-DuxvYhq6.cjs} +2 -2
  6. package/dist/chunks/{anim-image-blQgPFFS.cjs.map → anim-image-DuxvYhq6.cjs.map} +1 -1
  7. package/dist/chunks/{keyframes-B5PWe5bU.js → keyframes-B8ITIAVa.js} +2 -2
  8. package/dist/chunks/{keyframes-B5PWe5bU.js.map → keyframes-B8ITIAVa.js.map} +1 -1
  9. package/dist/chunks/{keyframes-tC3I7anQ.cjs → keyframes-Ce1s05n3.cjs} +2 -2
  10. package/dist/chunks/{keyframes-tC3I7anQ.cjs.map → keyframes-Ce1s05n3.cjs.map} +1 -1
  11. package/dist/chunks/{registry-CT-TT_bx.js → registry-DXdFb2fJ.js} +2 -2
  12. package/dist/chunks/{registry-CT-TT_bx.js.map → registry-DXdFb2fJ.js.map} +1 -1
  13. package/dist/chunks/{registry-tzwKkldE.cjs → registry-VhfPSI0v.cjs} +2 -2
  14. package/dist/chunks/{registry-tzwKkldE.cjs.map → registry-VhfPSI0v.cjs.map} +1 -1
  15. package/dist/chunks/{ticker-C8lSGml9.js → ticker-C5RMHMW7.js} +2 -2
  16. package/dist/chunks/{ticker-C8lSGml9.js.map → ticker-C5RMHMW7.js.map} +1 -1
  17. package/dist/chunks/{ticker-Un0bvTWR.cjs → ticker-DvmC6WLS.cjs} +2 -2
  18. package/dist/chunks/{ticker-Un0bvTWR.cjs.map → ticker-DvmC6WLS.cjs.map} +1 -1
  19. package/dist/chunks/{tween-BcejKpsx.js → tween-CPtm-EdT.js} +2 -2
  20. package/dist/chunks/{tween-BcejKpsx.js.map → tween-CPtm-EdT.js.map} +1 -1
  21. package/dist/chunks/{tween-CwLLC3Ko.cjs → tween-_BGIl6hK.cjs} +2 -2
  22. package/dist/chunks/{tween-CwLLC3Ko.cjs.map → tween-_BGIl6hK.cjs.map} +1 -1
  23. package/dist/components/widgets.cjs +745 -212
  24. package/dist/components/widgets.cjs.map +1 -1
  25. package/dist/components/widgets.d.cts +202 -2
  26. package/dist/components/widgets.d.ts +202 -2
  27. package/dist/components/widgets.js +738 -213
  28. package/dist/components/widgets.js.map +1 -1
  29. package/dist/llms-full.txt +150 -1
  30. package/dist/llms.txt +9 -2
  31. package/dist/manifest.json +394 -1
  32. package/dist/runtime/format-apng.cjs +4 -4
  33. package/dist/runtime/format-apng.js +4 -4
  34. package/dist/runtime/format-css.cjs +4 -4
  35. package/dist/runtime/format-css.js +4 -4
  36. package/dist/runtime/format-gif.cjs +4 -4
  37. package/dist/runtime/format-gif.js +4 -4
  38. package/dist/runtime/format-gltf.cjs +207 -0
  39. package/dist/runtime/format-gltf.cjs.map +1 -0
  40. package/dist/runtime/format-gltf.d.cts +251 -0
  41. package/dist/runtime/format-gltf.d.ts +251 -0
  42. package/dist/runtime/format-gltf.iife.js +2 -0
  43. package/dist/runtime/format-gltf.iife.js.map +1 -0
  44. package/dist/runtime/format-gltf.js +200 -0
  45. package/dist/runtime/format-gltf.js.map +1 -0
  46. package/dist/runtime/format-motion.cjs +4 -4
  47. package/dist/runtime/format-motion.js +4 -4
  48. package/dist/runtime/format-obj.cjs +181 -0
  49. package/dist/runtime/format-obj.cjs.map +1 -0
  50. package/dist/runtime/format-obj.d.cts +176 -0
  51. package/dist/runtime/format-obj.d.ts +176 -0
  52. package/dist/runtime/format-obj.iife.js +2 -0
  53. package/dist/runtime/format-obj.iife.js.map +1 -0
  54. package/dist/runtime/format-obj.js +174 -0
  55. package/dist/runtime/format-obj.js.map +1 -0
  56. package/dist/runtime/format-sprite.cjs +3 -3
  57. package/dist/runtime/format-sprite.js +3 -3
  58. package/dist/runtime/format-svg.cjs +3 -3
  59. package/dist/runtime/format-svg.js +3 -3
  60. package/dist/runtime/format-webp.cjs +4 -4
  61. package/dist/runtime/format-webp.js +4 -4
  62. package/dist/runtime/gl.cjs +763 -0
  63. package/dist/runtime/gl.cjs.map +1 -0
  64. package/dist/runtime/gl.d.cts +260 -0
  65. package/dist/runtime/gl.d.ts +260 -0
  66. package/dist/runtime/gl.iife.js +2 -0
  67. package/dist/runtime/gl.iife.js.map +1 -0
  68. package/dist/runtime/gl.js +739 -0
  69. package/dist/runtime/gl.js.map +1 -0
  70. package/dist/runtime/scroll.cjs +2 -2
  71. package/dist/runtime/scroll.js +2 -2
  72. package/dist/runtime/smooth.cjs +1 -1
  73. package/dist/runtime/smooth.js +1 -1
  74. package/dist/runtime/text.cjs +1 -1
  75. package/dist/runtime/text.js +1 -1
  76. package/dist/runtime.cjs +3 -3
  77. package/dist/runtime.d.cts +1 -1
  78. package/dist/runtime.d.ts +1 -1
  79. package/dist/runtime.iife.js +1 -1
  80. package/dist/runtime.iife.js.map +1 -1
  81. package/dist/runtime.js +5 -5
  82. package/dist/widgets.umd.js +1 -1
  83. package/dist/widgets.umd.js.map +1 -1
  84. package/docs/ROADMAP.md +1 -1
  85. package/docs/components/README.md +8 -1
  86. package/docs/components/usa-gl-scene.md +66 -0
  87. package/docs/components/usa-gpu-particles.md +32 -0
  88. package/docs/components/usa-shader-backdrop.md +36 -0
  89. package/docs/components/usa-three-scene.md +20 -0
  90. package/docs/components.md +48 -0
  91. package/docs/runtime/format-gltf.md +63 -0
  92. package/docs/runtime/format-obj.md +59 -0
  93. package/docs/runtime/gl.md +62 -0
  94. package/package.json +32 -2
@@ -0,0 +1,251 @@
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
+ /** Renderer cache. */
56
+ _gpu?: unknown;
57
+ }
58
+ interface GlTexture {
59
+ source: TexImageSource | {
60
+ width: number;
61
+ height: number;
62
+ data: Uint8Array | Uint8ClampedArray;
63
+ };
64
+ /** sRGB colour data (default true for colour maps). */
65
+ srgb?: boolean;
66
+ repeat?: boolean;
67
+ flipY?: boolean;
68
+ /** Re-upload every frame a new video frame is ready. */
69
+ video?: boolean;
70
+ needsUpdate?: boolean;
71
+ _gpu?: unknown;
72
+ }
73
+ interface Material {
74
+ type: 'standard' | 'unlit' | 'shader';
75
+ /** Linear RGBA multiplier (sRGB input converted by the shader). */
76
+ color: [number, number, number, number];
77
+ map?: GlTexture | null;
78
+ metallic: number;
79
+ roughness: number;
80
+ emissive: Vec3;
81
+ doubleSided?: boolean;
82
+ transparent?: boolean;
83
+ wireframe?: boolean;
84
+ /** 'shader' materials: GLSL ES 3.00 fragment body + uniforms. */
85
+ fragment?: string;
86
+ uniforms?: Record<string, number | number[] | Float32Array | GlTexture>;
87
+ _gpu?: unknown;
88
+ }
89
+ interface Mesh {
90
+ geometry: Geometry;
91
+ material: Material;
92
+ }
93
+ declare class GlNode {
94
+ name: string;
95
+ position: Vec3;
96
+ rotation: Quat;
97
+ scale: Vec3;
98
+ /** Set to use a fixed local matrix instead of position / rotation / scale (glTF `matrix`). */
99
+ matrix: Mat4 | null;
100
+ children: GlNode[];
101
+ parent: GlNode | null;
102
+ mesh: Mesh | Mesh[] | null;
103
+ visible: boolean;
104
+ /** Free-form data (loaders put source info here). */
105
+ extras: Record<string, unknown>;
106
+ readonly world: Mat4;
107
+ constructor(name?: string, mesh?: Mesh | Mesh[] | null);
108
+ add(...nodes: GlNode[]): this;
109
+ remove(n: GlNode): void;
110
+ setEuler(x: number, y: number, z: number): this;
111
+ local(): Mat4;
112
+ /** Recompute world matrices of this subtree. */
113
+ updateWorld(parent?: Mat4): void;
114
+ traverse(fn: (n: GlNode) => void): void;
115
+ find(name: string): GlNode | null;
116
+ }
117
+
118
+ /**
119
+ * `motionary/runtime/format-gltf` (10.5) — glTF 2.0 / GLB loader for
120
+ * `motionary/runtime/gl` (own implementation):
121
+ *
122
+ * - `.gltf` (JSON + external or `data:` buffers / images) and `.glb`
123
+ * (binary container: JSON + BIN chunks);
124
+ * - scenes and the node hierarchy (TRS or `matrix`), meshes with several
125
+ * primitives (POSITION, NORMAL, TEXCOORD_0, indices; any component type,
126
+ * normalised integers, interleaved `byteStride`; modes points, lines,
127
+ * triangles, strips, fans);
128
+ * - PBR metallic-roughness materials (base colour factor + texture,
129
+ * metallic / roughness factors, emissive factor, alpha modes, double-sided);
130
+ * images from buffer views or URIs (decoded with `createImageBitmap`);
131
+ * - files that *require* an extension we do not implement (e.g. Draco /
132
+ * KTX2 compression) fail with a clear error naming it.
133
+ *
134
+ * Skins, morph targets and animations arrive in 10.8. `parseGlb()` /
135
+ * `gltfToNode()` with an `images` override are pure (SSR / workers).
136
+ */
137
+
138
+ interface GltfJson {
139
+ asset: {
140
+ version: string;
141
+ generator?: string;
142
+ };
143
+ scene?: number;
144
+ scenes?: {
145
+ nodes?: number[];
146
+ name?: string;
147
+ }[];
148
+ nodes?: {
149
+ name?: string;
150
+ children?: number[];
151
+ mesh?: number;
152
+ matrix?: number[];
153
+ translation?: number[];
154
+ rotation?: number[];
155
+ scale?: number[];
156
+ skin?: number;
157
+ camera?: number;
158
+ }[];
159
+ meshes?: {
160
+ name?: string;
161
+ primitives: {
162
+ attributes: Record<string, number>;
163
+ indices?: number;
164
+ material?: number;
165
+ mode?: number;
166
+ targets?: Record<string, number>[];
167
+ }[];
168
+ weights?: number[];
169
+ }[];
170
+ accessors?: {
171
+ bufferView?: number;
172
+ byteOffset?: number;
173
+ componentType: number;
174
+ normalized?: boolean;
175
+ count: number;
176
+ type: string;
177
+ min?: number[];
178
+ max?: number[];
179
+ sparse?: unknown;
180
+ }[];
181
+ bufferViews?: {
182
+ buffer: number;
183
+ byteOffset?: number;
184
+ byteLength: number;
185
+ byteStride?: number;
186
+ }[];
187
+ buffers?: {
188
+ uri?: string;
189
+ byteLength: number;
190
+ }[];
191
+ materials?: {
192
+ name?: string;
193
+ pbrMetallicRoughness?: {
194
+ baseColorFactor?: number[];
195
+ baseColorTexture?: {
196
+ index: number;
197
+ };
198
+ metallicFactor?: number;
199
+ roughnessFactor?: number;
200
+ };
201
+ emissiveFactor?: number[];
202
+ alphaMode?: string;
203
+ doubleSided?: boolean;
204
+ extensions?: Record<string, any>;
205
+ }[];
206
+ textures?: {
207
+ source?: number;
208
+ sampler?: number;
209
+ }[];
210
+ images?: {
211
+ uri?: string;
212
+ bufferView?: number;
213
+ mimeType?: string;
214
+ }[];
215
+ extensionsUsed?: string[];
216
+ extensionsRequired?: string[];
217
+ animations?: unknown[];
218
+ skins?: unknown[];
219
+ }
220
+ /** Extensions this loader understands (others that a file *requires* make it fail clearly). */
221
+ declare const SUPPORTED_EXTENSIONS: string[];
222
+ /** Split a GLB container into its JSON and BIN chunk (pure). */
223
+ declare function parseGlb(input: ArrayBuffer | Uint8Array): {
224
+ json: GltfJson;
225
+ bin: Uint8Array | null;
226
+ };
227
+ /** Read an accessor into a flat typed array (floats are de-interleaved; normalised ints become floats). */
228
+ declare function readAccessor(json: GltfJson, buffers: Uint8Array[], index: number, asFloat?: boolean): Float32Array | Uint16Array | Uint32Array | Uint8Array;
229
+ interface GltfImages {
230
+ /** Decoded images by glTF image index (pass your own for SSR / tests). */
231
+ [index: number]: TexImageSource | undefined;
232
+ }
233
+ /** Build a runtime/gl node tree from parsed glTF (pure, given buffers and decoded images). */
234
+ declare function gltfToNode(json: GltfJson, buffers: Uint8Array[], images?: GltfImages, sceneIndex?: number): GlNode;
235
+ /** Load a `.gltf` / `.glb` (URL or bytes) with its buffers and images and build a node tree. */
236
+ declare function loadGltf(src: string | ArrayBuffer | Uint8Array, o?: {
237
+ baseUrl?: string;
238
+ scene?: number;
239
+ }): Promise<GlNode>;
240
+ interface FormatGltfApi {
241
+ parseGlb: typeof parseGlb;
242
+ readAccessor: typeof readAccessor;
243
+ gltfToNode: typeof gltfToNode;
244
+ loadGltf: typeof loadGltf;
245
+ SUPPORTED_EXTENSIONS: typeof SUPPORTED_EXTENSIONS;
246
+ }
247
+ /** The module object for `use(formatGltf)` (needs `gl`). */
248
+ declare const formatGltf: RuntimeModule<FormatGltfApi>;
249
+
250
+ export { SUPPORTED_EXTENSIONS, formatGltf, gltfToNode, loadGltf, parseGlb, readAccessor };
251
+ export type { FormatGltfApi, GltfImages, GltfJson };
@@ -0,0 +1,2 @@
1
+ !function(t,e){"use strict";const r={identity:()=>new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),multiply(t,e,r=new Float32Array(16)){for(let o=0;o<4;o++)for(let n=0;n<4;n++)r[4*o+n]=t[n]*e[4*o]+t[4+n]*e[4*o+1]+t[8+n]*e[4*o+2]+t[12+n]*e[4*o+3];return r},perspective(t,e,r,o){const n=1/Math.tan(t/2),i=1/(r-o);return new Float32Array([n/e,0,0,0,0,n,0,0,0,0,(o+r)*i,-1,0,0,2*o*r*i,0])},lookAt(t,e,r=[0,1,0]){let a=o(t,e);a=s(a.some(t=>t)?a:[0,0,1]);let l=i(r,a);l.some(t=>Math.abs(t)>1e-9)||(l=i([0,0,1],a)),l=s(l);const c=i(a,l);return new Float32Array([l[0],c[0],a[0],0,l[1],c[1],a[1],0,l[2],c[2],a[2],0,-n(l,t),-n(c,t),-n(a,t),1])},compose(t,e,r){const[o,n,i,s]=e,a=o+o,l=n+n,c=i+i,f=o*a,u=o*l,m=o*c,d=n*l,h=n*c,y=i*c,p=s*a,w=s*l,g=s*c;return new Float32Array([(1-(d+y))*r[0],(u+g)*r[0],(m-w)*r[0],0,(u-g)*r[1],(1-(f+y))*r[1],(h+p)*r[1],0,(m+w)*r[2],(h-p)*r[2],(1-(f+d))*r[2],0,t[0],t[1],t[2],1])},invert(t){const e=new Float32Array(16),[r,o,n,i,s,a,l,c,f,u,m,d,h,y,p,w]=t,g=r*a-o*s,b=r*l-n*s,A=r*c-i*s,v=o*l-n*a,E=o*c-i*a,U=n*c-i*l,M=f*y-u*h,x=f*p-m*h,T=f*w-d*h,O=u*p-m*y,R=u*w-d*y,F=m*w-d*p;let _=g*F-b*R+A*O+v*T-E*x+U*M;return _?(_=1/_,e[0]=(a*F-l*R+c*O)*_,e[1]=(n*R-o*F-i*O)*_,e[2]=(y*U-p*E+w*v)*_,e[3]=(m*E-u*U-d*v)*_,e[4]=(l*T-s*F-c*x)*_,e[5]=(r*F-n*T+i*x)*_,e[6]=(p*A-h*U-w*b)*_,e[7]=(f*U-m*A+d*b)*_,e[8]=(s*R-a*T+c*M)*_,e[9]=(o*T-r*R-i*M)*_,e[10]=(h*E-y*A+w*g)*_,e[11]=(u*A-f*E-d*g)*_,e[12]=(a*x-s*O-l*M)*_,e[13]=(r*O-o*x+n*M)*_,e[14]=(y*b-h*v-p*g)*_,e[15]=(f*v-u*b+m*g)*_,e):null},normal(t){const e=r.invert(t)||r.identity();return new Float32Array([e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]])},transformPoint(t,e){const r=t[3]*e[0]+t[7]*e[1]+t[11]*e[2]+t[15]||1;return[(t[0]*e[0]+t[4]*e[1]+t[8]*e[2]+t[12])/r,(t[1]*e[0]+t[5]*e[1]+t[9]*e[2]+t[13])/r,(t[2]*e[0]+t[6]*e[1]+t[10]*e[2]+t[14])/r]}},o=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],n=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],i=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],s=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function a(t={}){return{type:"standard",color:[1,1,1,1],metallic:0,roughness:.6,emissive:[0,0,0],...t}}class l{constructor(t="",e=null){this.name="",this.position=[0,0,0],this.rotation=[0,0,0,1],this.scale=[1,1,1],this.matrix=null,this.children=[],this.parent=null,this.mesh=null,this.visible=!0,this.extras={},this.world=r.identity(),this.name=t,this.mesh=e}add(...t){for(const e of t)e.parent?.remove(e),e.parent=this,this.children.push(e);return this}remove(t){const e=this.children.indexOf(t);e>=0&&this.children.splice(e,1),t.parent=null}setEuler(t,e,r){return this.rotation=function(t,e,r){const o=Math.cos(t/2),n=Math.sin(t/2),i=Math.cos(e/2),s=Math.sin(e/2),a=Math.cos(r/2),l=Math.sin(r/2);return[n*i*a+o*s*l,o*s*a-n*i*l,o*i*l+n*s*a,o*i*a-n*s*l]}(t,e,r),this}local(){return this.matrix||r.compose(this.position,this.rotation,this.scale)}updateWorld(t){const e=t?r.multiply(t,this.local()):this.local();this.world.set(e);for(const t of this.children)t.updateWorld(this.world)}traverse(t){t(this);for(const e of this.children)e.traverse(t)}find(t){let e=null;return this.traverse(r=>{e||r.name!==t||(e=r)}),e}}const c=["KHR_materials_emissive_strength","KHR_materials_unlit"];function f(t){const e=t instanceof Uint8Array?t:new Uint8Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(1179937895!==r.getUint32(0,!0))throw new Error("[motionary] format-gltf: not a GLB file");if(2!==r.getUint32(4,!0))throw new Error("[motionary] format-gltf: only glTF 2.0 GLB is supported");const o=Math.min(r.getUint32(8,!0),e.byteLength);let n=12,i=null,s=null;for(;n+8<=o;){const t=r.getUint32(n,!0),o=r.getUint32(n+4,!0),a=e.subarray(n+8,n+8+t);1313821514===o?i=JSON.parse((new TextDecoder).decode(a)):5130562!==o||s||(s=a),n+=8+t}if(!i)throw new Error("[motionary] format-gltf: GLB without a JSON chunk");return{json:i,bin:s}}const u={5120:[1,Int8Array,127],5121:[1,Uint8Array,255],5122:[2,Int16Array,32767],5123:[2,Uint16Array,65535],5125:[4,Uint32Array,0],5126:[4,Float32Array,0]},m={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function d(t,e,r,o=!0){const n=t.accessors?.[r];if(!n)throw new Error(`[motionary] format-gltf: accessor ${r} missing`);const[i,s,a]=u[n.componentType]||[];if(!s)throw new Error(`[motionary] format-gltf: component type ${n.componentType} unsupported`);const l=m[n.type],c=n.count*l,f=s===Float32Array,d=o||f?new Float32Array(c):new s(c);if(void 0===n.bufferView)return d;const h=t.bufferViews[n.bufferView],y=e[h.buffer],p=(h.byteOffset||0)+(n.byteOffset||0),w=h.byteStride||i*l,g=new DataView(y.buffer,y.byteOffset,y.byteLength),b=t=>4===i?f?g.getFloat32(t,!0):g.getUint32(t,!0):2===i?s===Int16Array?g.getInt16(t,!0):g.getUint16(t,!0):s===Int8Array?g.getInt8(t):g.getUint8(t);for(let t=0;t<n.count;t++)for(let e=0;e<l;e++){let r=b(p+t*w+e*i);n.normalized&&a&&(r=Math.max(r/a,-1)),d[t*l+e]=r}return d}function h(t,e){const r=[];if(5===e)for(let e=0;e+2<t.length;e++)r.push(...e%2?[t[e+1],t[e],t[e+2]]:[t[e],t[e+1],t[e+2]]);else for(let e=1;e+1<t.length;e++)r.push(t[0],t[e],t[e+1]);return new Uint32Array(r)}function y(t,e,r={},n){if(!t.asset||!/^2\./.test(t.asset.version))throw new Error("[motionary] format-gltf: only glTF 2.0 is supported");const f=(t.extensionsRequired||[]).filter(t=>!c.includes(t));if(f.length)throw new Error(`[motionary] format-gltf: this file requires ${f.join(", ")}, which motionary/runtime/format-gltf does not implement${f.some(t=>/draco|KHR_texture_basisu|meshopt/i.test(t))?" (compressed geometry / textures need the official decoders — re-export the model without compression, or use the decoder hooks planned for 10.9)":""}`);const u=(t.materials||[]).map(e=>{const o=e.pbrMetallicRoughness||{},n=o.baseColorFactor||[1,1,1,1],i=t=>Math.pow(Math.max(0,t),1/2.2),s=e.extensions?.KHR_materials_emissive_strength?.emissiveStrength??1,l=a({color:[i(n[0]),i(n[1]),i(n[2]),n[3]??1],metallic:o.metallicFactor??1,roughness:o.roughnessFactor??1,emissive:(e.emissiveFactor||[0,0,0]).map(t=>t*s),doubleSided:!!e.doubleSided,transparent:"BLEND"===e.alphaMode});e.extensions?.KHR_materials_unlit&&(l.type="unlit");const c=o.baseColorTexture?.index,f=void 0!==c?t.textures?.[c]?.source:void 0;return void 0!==f&&r[f]&&(l.map=function(t,e={}){return{source:t,srgb:!0,repeat:!0,flipY:!1,video:"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,needsUpdate:!0,...e}}(r[f])),l}),m=(t.meshes||[]).map(r=>r.primitives.map(r=>{const n=r.mode??4;let l={positions:d(t,e,r.attributes.POSITION),normals:void 0!==r.attributes.NORMAL?d(t,e,r.attributes.NORMAL):void 0,uvs:void 0!==r.attributes.TEXCOORD_0?d(t,e,r.attributes.TEXCOORD_0):void 0,mode:0===n?"points":n>=1&&n<=3?"lines":"triangles"};if(void 0!==r.indices){let o=d(t,e,r.indices,!1);5!==n&&6!==n||(o=h(Uint32Array.from(o),n)),l.indices=o instanceof Uint8Array||o instanceof Uint32Array&&l.positions.length/3<=65535?Uint16Array.from(o):o}else 5!==n&&6!==n||(l.indices=h(Uint32Array.from({length:l.positions.length/3},(t,e)=>e),n));return l.normals||"triangles"!==l.mode||(l=function(t){const e=t.positions,r=t.indices,n=r?r.length:e.length/3,a=new Float32Array(3*n),l=new Float32Array(3*n),c=t.uvs?new Float32Array(2*n):void 0;for(let f=0;f<n;f+=3){const n=[0,1,2].map(t=>r?r[f+t]:f+t),u=[e[3*n[0]],e[3*n[0]+1],e[3*n[0]+2]],m=[e[3*n[1]],e[3*n[1]+1],e[3*n[1]+2]],d=[e[3*n[2]],e[3*n[2]+1],e[3*n[2]+2]],h=s(i(o(m,u),o(d,u)));n.forEach((r,o)=>{a.set(e.subarray(3*r,3*r+3),3*(f+o)),l.set(h,3*(f+o)),c&&t.uvs&&c.set(t.uvs.subarray(2*r,2*r+2),2*(f+o))})}return{positions:a,normals:l,uvs:c,mode:t.mode}}(l)),{geometry:l,material:void 0!==r.material?u[r.material]:a({metallic:0,roughness:.6})}})),y=(t.nodes||[]).map((t,e)=>{const r=new l(t.name||`node${e}`,void 0!==t.mesh?m[t.mesh]:null);return t.matrix&&(r.matrix=new Float32Array(t.matrix)),t.translation&&(r.position=t.translation.slice(0,3)),t.rotation&&(r.rotation=t.rotation.slice(0,4)),t.scale&&(r.scale=t.scale.slice(0,3)),r.extras.gltfIndex=e,r});(t.nodes||[]).forEach((t,e)=>(t.children||[]).forEach(t=>y[e].add(y[t])));const p=new l("gltf"),w=t.scenes?.[n??t.scene??0];return(w?.nodes??y.map((t,e)=>e).filter(t=>!y[t].parent)).forEach(t=>p.add(y[t])),p.extras={gltf:t,nodes:y},p}async function p(t,e={}){const r=e.baseUrl||("string"==typeof t?new URL(t,"undefined"!=typeof location?location.href:"file:///").href:"undefined"!=typeof location?location.href:"file:///"),o=async t=>{if(t.startsWith("data:"))return(t=>{const[,e,r]=/^data:([^,]*),(.*)$/s.exec(t)||[];if(void 0===e)throw new Error("[motionary] format-gltf: bad data URI");if(/;base64/.test(e)){const t=atob(r);return Uint8Array.from(t,t=>t.charCodeAt(0))}return(new TextEncoder).encode(decodeURIComponent(r))})(t);const e=await fetch(new URL(t,r).href);if(!e.ok)throw new Error(`[motionary] format-gltf: could not load ${t} (${e.status})`);return new Uint8Array(await e.arrayBuffer())},n="string"==typeof t?await o(t):t instanceof Uint8Array?t:new Uint8Array(t);let i,s=null;103===n[0]&&108===n[1]&&84===n[2]&&70===n[3]?({json:i,bin:s}=f(n)):i=JSON.parse((new TextDecoder).decode(n));const a=await Promise.all((i.buffers||[]).map((t,e)=>t.uri?o(t.uri):0===e&&s?Promise.resolve(s):Promise.reject(new Error("[motionary] format-gltf: buffer without data")))),l={};return await Promise.all((i.images||[]).map(async(t,e)=>{let r;if(void 0!==t.bufferView){const e=i.bufferViews[t.bufferView];r=a[e.buffer].subarray(e.byteOffset||0,(e.byteOffset||0)+e.byteLength)}else{if(!t.uri)return;r=await o(t.uri)}l[e]=await createImageBitmap(new Blob([r],{type:t.mimeType||(t.uri&&/\.jpe?g$/i.test(t.uri)?"image/jpeg":"image/png")}))})),y(i,a,l,e.scene)}const w={id:"format-gltf",version:e.RUNTIME_VERSION,requires:["core","gl"],api:{parseGlb:f,readAccessor:d,gltfToNode:y,loadGltf:p,SUPPORTED_EXTENSIONS:c}};e.register(w),t.SUPPORTED_EXTENSIONS=c,t.formatGltf=w,t.gltfToNode=y,t.loadGltf=p,t.parseGlb=f,t.readAccessor=d}(this.MotionaryRuntime=this.MotionaryRuntime||{},MotionaryRuntime);
2
+ //# sourceMappingURL=format-gltf.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format-gltf.iife.js","sources":["../../src/runtime/gl.ts","../../src/runtime/format-gltf.ts","../../src/runtime/iife/format-gltf.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 /** 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 if (g._gpu) return g._gpu as { vao: WebGLVertexArrayObject; count: number; type: number; indexed: boolean };\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 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 });\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/format-gltf` (10.5) — glTF 2.0 / GLB loader for\n * `motionary/runtime/gl` (own implementation):\n *\n * - `.gltf` (JSON + external or `data:` buffers / images) and `.glb`\n * (binary container: JSON + BIN chunks);\n * - scenes and the node hierarchy (TRS or `matrix`), meshes with several\n * primitives (POSITION, NORMAL, TEXCOORD_0, indices; any component type,\n * normalised integers, interleaved `byteStride`; modes points, lines,\n * triangles, strips, fans);\n * - PBR metallic-roughness materials (base colour factor + texture,\n * metallic / roughness factors, emissive factor, alpha modes, double-sided);\n * images from buffer views or URIs (decoded with `createImageBitmap`);\n * - files that *require* an extension we do not implement (e.g. Draco /\n * KTX2 compression) fail with a clear error naming it.\n *\n * Skins, morph targets and animations arrive in 10.8. `parseGlb()` /\n * `gltfToNode()` with an `images` override are pure (SSR / workers).\n */\nimport { RUNTIME_VERSION, type RuntimeModule } from './registry';\nimport { GlNode, standardMaterial, computeNormals, texture, type Geometry, type Material, type Mesh, type Quat, type Vec3 } from './gl';\n\nexport interface GltfJson {\n asset: { version: string; generator?: string };\n scene?: number;\n scenes?: { nodes?: number[]; name?: string }[];\n nodes?: { name?: string; children?: number[]; mesh?: number; matrix?: number[]; translation?: number[]; rotation?: number[]; scale?: number[]; skin?: number; camera?: number }[];\n meshes?: { name?: string; primitives: { attributes: Record<string, number>; indices?: number; material?: number; mode?: number; targets?: Record<string, number>[] }[]; weights?: number[] }[];\n accessors?: { bufferView?: number; byteOffset?: number; componentType: number; normalized?: boolean; count: number; type: string; min?: number[]; max?: number[]; sparse?: unknown }[];\n bufferViews?: { buffer: number; byteOffset?: number; byteLength: number; byteStride?: number }[];\n buffers?: { uri?: string; byteLength: number }[];\n materials?: { name?: string; pbrMetallicRoughness?: { baseColorFactor?: number[]; baseColorTexture?: { index: number }; metallicFactor?: number; roughnessFactor?: number }; emissiveFactor?: number[]; alphaMode?: string; doubleSided?: boolean; extensions?: Record<string, any> }[];\n textures?: { source?: number; sampler?: number }[];\n images?: { uri?: string; bufferView?: number; mimeType?: string }[];\n extensionsUsed?: string[];\n extensionsRequired?: string[];\n animations?: unknown[];\n skins?: unknown[];\n}\n\n/** Extensions this loader understands (others that a file *requires* make it fail clearly). */\nexport const SUPPORTED_EXTENSIONS = ['KHR_materials_emissive_strength', 'KHR_materials_unlit'];\n\n/** Split a GLB container into its JSON and BIN chunk (pure). */\nexport function parseGlb(input: ArrayBuffer | Uint8Array): { json: GltfJson; bin: Uint8Array | null } {\n const b = input instanceof Uint8Array ? input : new Uint8Array(input);\n const v = new DataView(b.buffer, b.byteOffset, b.byteLength);\n if (v.getUint32(0, true) !== 0x46546c67) throw new Error('[motionary] format-gltf: not a GLB file');\n if (v.getUint32(4, true) !== 2) throw new Error('[motionary] format-gltf: only glTF 2.0 GLB is supported');\n const len = Math.min(v.getUint32(8, true), b.byteLength);\n let p = 12, json: GltfJson | null = null, bin: Uint8Array | null = null;\n while (p + 8 <= len) {\n const cl = v.getUint32(p, true), ct = v.getUint32(p + 4, true);\n const data = b.subarray(p + 8, p + 8 + cl);\n if (ct === 0x4e4f534a) json = JSON.parse(new TextDecoder().decode(data));\n else if (ct === 0x004e4942 && !bin) bin = data;\n p += 8 + cl;\n }\n if (!json) throw new Error('[motionary] format-gltf: GLB without a JSON chunk');\n return { json, bin };\n}\n\nconst COMP: Record<number, [number, any, number]> = {\n 5120: [1, Int8Array, 127], 5121: [1, Uint8Array, 255], 5122: [2, Int16Array, 32767], 5123: [2, Uint16Array, 65535], 5125: [4, Uint32Array, 0], 5126: [4, Float32Array, 0],\n};\nconst SIZE: Record<string, number> = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };\n\n/** Read an accessor into a flat typed array (floats are de-interleaved; normalised ints become floats). */\nexport function readAccessor(json: GltfJson, buffers: Uint8Array[], index: number, asFloat = true): Float32Array | Uint16Array | Uint32Array | Uint8Array {\n const a = json.accessors?.[index];\n if (!a) throw new Error(`[motionary] format-gltf: accessor ${index} missing`);\n const [bytes, Ctor, max] = COMP[a.componentType] || [];\n if (!Ctor) throw new Error(`[motionary] format-gltf: component type ${a.componentType} unsupported`);\n const n = SIZE[a.type], count = a.count * n;\n const isFloat = Ctor === Float32Array;\n const out = asFloat || isFloat ? new Float32Array(count) : new Ctor(count);\n if (a.bufferView === undefined) return out; // all zeros (sparse-only accessors)\n const bv = json.bufferViews![a.bufferView];\n const buf = buffers[bv.buffer];\n const base = (bv.byteOffset || 0) + (a.byteOffset || 0);\n const stride = bv.byteStride || bytes * n;\n const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n const get = (o: number): number => (bytes === 4 ? (isFloat ? dv.getFloat32(o, true) : dv.getUint32(o, true)) : bytes === 2 ? (Ctor === Int16Array ? dv.getInt16(o, true) : dv.getUint16(o, true)) : Ctor === Int8Array ? dv.getInt8(o) : dv.getUint8(o));\n for (let i = 0; i < a.count; i++)\n for (let k = 0; k < n; k++) {\n let x = get(base + i * stride + k * bytes);\n if (a.normalized && max) x = Math.max(x / max, -1);\n out[i * n + k] = x;\n }\n return out;\n}\n\nfunction toTriangles(idx: Uint32Array, mode: number): Uint32Array {\n const out: number[] = [];\n if (mode === 5) for (let i = 0; i + 2 < idx.length; i++) out.push(...(i % 2 ? [idx[i + 1], idx[i], idx[i + 2]] : [idx[i], idx[i + 1], idx[i + 2]]));\n else for (let i = 1; i + 1 < idx.length; i++) out.push(idx[0], idx[i], idx[i + 1]);\n return new Uint32Array(out);\n}\n\nexport interface GltfImages {\n /** Decoded images by glTF image index (pass your own for SSR / tests). */\n [index: number]: TexImageSource | undefined;\n}\n\n/** Build a runtime/gl node tree from parsed glTF (pure, given buffers and decoded images). */\nexport function gltfToNode(json: GltfJson, buffers: Uint8Array[], images: GltfImages = {}, sceneIndex?: number): GlNode {\n if (!json.asset || !/^2\\./.test(json.asset.version)) throw new Error('[motionary] format-gltf: only glTF 2.0 is supported');\n const missing = (json.extensionsRequired || []).filter((e) => !SUPPORTED_EXTENSIONS.includes(e));\n if (missing.length) throw new Error(`[motionary] format-gltf: this file requires ${missing.join(', ')}, which motionary/runtime/format-gltf does not implement${missing.some((e) => /draco|KHR_texture_basisu|meshopt/i.test(e)) ? ' (compressed geometry / textures need the official decoders — re-export the model without compression, or use the decoder hooks planned for 10.9)' : ''}`);\n const mats: Material[] = (json.materials || []).map((m) => {\n const pbr = m.pbrMetallicRoughness || {};\n const cf = pbr.baseColorFactor || [1, 1, 1, 1];\n // glTF factors are linear; the shader linearises colour input → convert the factor to sRGB space\n const toS = (x: number) => Math.pow(Math.max(0, x), 1 / 2.2);\n const strength = m.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1;\n const mat = standardMaterial({ color: [toS(cf[0]), toS(cf[1]), toS(cf[2]), cf[3] ?? 1], metallic: pbr.metallicFactor ?? 1, roughness: pbr.roughnessFactor ?? 1, emissive: ((m.emissiveFactor || [0, 0, 0]).map((x) => x * strength) as Vec3), doubleSided: !!m.doubleSided, transparent: m.alphaMode === 'BLEND' });\n if (m.extensions?.KHR_materials_unlit) mat.type = 'unlit';\n const ti = pbr.baseColorTexture?.index;\n const src = ti !== undefined ? json.textures?.[ti]?.source : undefined;\n if (src !== undefined && images[src]) mat.map = texture(images[src]!);\n return mat;\n });\n const meshes: Mesh[][] = (json.meshes || []).map((m) =>\n m.primitives.map((p) => {\n const mode = p.mode ?? 4;\n let g: Geometry = {\n positions: readAccessor(json, buffers, p.attributes.POSITION) as Float32Array,\n normals: p.attributes.NORMAL !== undefined ? (readAccessor(json, buffers, p.attributes.NORMAL) as Float32Array) : undefined,\n uvs: p.attributes.TEXCOORD_0 !== undefined ? (readAccessor(json, buffers, p.attributes.TEXCOORD_0) as Float32Array) : undefined,\n mode: mode === 0 ? 'points' : mode >= 1 && mode <= 3 ? 'lines' : 'triangles',\n };\n if (p.indices !== undefined) {\n let idx = readAccessor(json, buffers, p.indices, false) as Uint32Array | Uint16Array | Uint8Array;\n if (mode === 5 || mode === 6) idx = toTriangles(Uint32Array.from(idx), mode);\n g.indices = idx instanceof Uint8Array || (idx instanceof Uint32Array && g.positions.length / 3 <= 65535) ? Uint16Array.from(idx) : (idx as Uint16Array | Uint32Array);\n } else if (mode === 5 || mode === 6) g.indices = toTriangles(Uint32Array.from({ length: g.positions.length / 3 }, (_, i) => i), mode);\n if (!g.normals && g.mode === 'triangles') g = computeNormals(g);\n return { geometry: g, material: p.material !== undefined ? mats[p.material] : standardMaterial({ metallic: 0, roughness: 0.6 }) };\n })\n );\n const nodes = (json.nodes || []).map((n, i) => {\n const node = new GlNode(n.name || `node${i}`, n.mesh !== undefined ? meshes[n.mesh] : null);\n if (n.matrix) node.matrix = new Float32Array(n.matrix);\n if (n.translation) node.position = n.translation.slice(0, 3) as Vec3;\n if (n.rotation) node.rotation = n.rotation.slice(0, 4) as Quat;\n if (n.scale) node.scale = n.scale.slice(0, 3) as Vec3;\n node.extras.gltfIndex = i;\n return node;\n });\n (json.nodes || []).forEach((n, i) => (n.children || []).forEach((c) => nodes[i].add(nodes[c])));\n const root = new GlNode('gltf');\n const sc = json.scenes?.[sceneIndex ?? json.scene ?? 0];\n const tops = sc?.nodes ?? nodes.map((_, i) => i).filter((i) => !nodes[i].parent);\n tops.forEach((i) => root.add(nodes[i]));\n root.extras = { gltf: json, nodes };\n return root;\n}\n\nconst dataUri = (u: string): Uint8Array => {\n const [, meta, data] = /^data:([^,]*),(.*)$/s.exec(u) || [];\n if (meta === undefined) throw new Error('[motionary] format-gltf: bad data URI');\n if (/;base64/.test(meta)) {\n const s = atob(data);\n return Uint8Array.from(s, (c) => c.charCodeAt(0));\n }\n return new TextEncoder().encode(decodeURIComponent(data));\n};\n\n/** Load a `.gltf` / `.glb` (URL or bytes) with its buffers and images and build a node tree. */\nexport async function loadGltf(src: string | ArrayBuffer | Uint8Array, o: { baseUrl?: string; scene?: number } = {}): Promise<GlNode> {\n const base = o.baseUrl || (typeof src === 'string' ? new URL(src, typeof location !== 'undefined' ? location.href : 'file:///').href : typeof location !== 'undefined' ? location.href : 'file:///');\n const get = async (u: string) => {\n if (u.startsWith('data:')) return dataUri(u);\n const r = await fetch(new URL(u, base).href);\n if (!r.ok) throw new Error(`[motionary] format-gltf: could not load ${u} (${r.status})`);\n return new Uint8Array(await r.arrayBuffer());\n };\n const bytes = typeof src === 'string' ? await get(src) : src instanceof Uint8Array ? src : new Uint8Array(src);\n let json: GltfJson, bin: Uint8Array | null = null;\n if (bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46) ({ json, bin } = parseGlb(bytes));\n else json = JSON.parse(new TextDecoder().decode(bytes));\n const buffers = await Promise.all((json.buffers || []).map((b, i) => (b.uri ? get(b.uri) : i === 0 && bin ? Promise.resolve(bin) : Promise.reject(new Error('[motionary] format-gltf: buffer without data')))));\n const images: GltfImages = {};\n await Promise.all((json.images || []).map(async (im, i) => {\n let data: Uint8Array;\n if (im.bufferView !== undefined) {\n const bv = json.bufferViews![im.bufferView];\n data = buffers[bv.buffer].subarray(bv.byteOffset || 0, (bv.byteOffset || 0) + bv.byteLength);\n } else if (im.uri) data = await get(im.uri);\n else return;\n images[i] = await createImageBitmap(new Blob([data as BlobPart], { type: im.mimeType || (im.uri && /\\.jpe?g$/i.test(im.uri) ? 'image/jpeg' : 'image/png') }));\n }));\n return gltfToNode(json, buffers, images, o.scene);\n}\n\nexport interface FormatGltfApi {\n parseGlb: typeof parseGlb;\n readAccessor: typeof readAccessor;\n gltfToNode: typeof gltfToNode;\n loadGltf: typeof loadGltf;\n SUPPORTED_EXTENSIONS: typeof SUPPORTED_EXTENSIONS;\n}\n\n/** The module object for `use(formatGltf)` (needs `gl`). */\nexport const formatGltf: RuntimeModule<FormatGltfApi> = { id: 'format-gltf', version: RUNTIME_VERSION, requires: ['core', 'gl'], api: { parseGlb, readAccessor, gltfToNode, loadGltf, SUPPORTED_EXTENSIONS } };\n","// CDN build: load runtime.iife.js first, then this file → registers motionary/runtime/format-gltf and adds its API to window.MotionaryRuntime.\nimport { register } from '../registry';\nimport { formatGltf } from '../format-gltf';\nexport * from '../format-gltf';\nregister(formatGltf);\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","standardMaterial","type","color","metallic","roughness","emissive","GlNode","constructor","name","mesh","this","position","rotation","scale","matrix","children","parent","visible","extras","world","add","nodes","n","remove","push","indexOf","splice","setEuler","cx","cos","sx","sin","cy","sy","cz","sz","quatFromEuler","local","updateWorld","set","traverse","fn","find","hit","SUPPORTED_EXTENSIONS","parseGlb","input","Uint8Array","DataView","buffer","byteOffset","byteLength","getUint32","Error","len","min","json","bin","cl","ct","data","subarray","JSON","parse","TextDecoder","decode","COMP","Int8Array","Int16Array","Uint16Array","Uint32Array","SIZE","SCALAR","VEC2","VEC3","VEC4","MAT2","MAT3","MAT4","readAccessor","buffers","index","asFloat","accessors","bytes","Ctor","max","componentType","count","isFloat","undefined","bufferView","bv","bufferViews","buf","base","stride","byteStride","dv","get","getFloat32","getInt16","getUint16","getInt8","getUint8","k","normalized","toTriangles","idx","mode","length","gltfToNode","images","sceneIndex","asset","test","version","missing","extensionsRequired","filter","e","includes","join","mats","materials","map","pbr","pbrMetallicRoughness","cf","baseColorFactor","toS","pow","strength","extensions","KHR_materials_emissive_strength","emissiveStrength","mat","metallicFactor","roughnessFactor","emissiveFactor","doubleSided","transparent","alphaMode","KHR_materials_unlit","ti","baseColorTexture","src","textures","source","srgb","repeat","flipY","video","HTMLVideoElement","needsUpdate","texture","meshes","primitives","g","positions","attributes","POSITION","normals","NORMAL","uvs","TEXCOORD_0","indices","from","_","P","I","pos","nrm","nn","forEach","vi","computeNormals","geometry","material","node","translation","slice","gltfIndex","root","sc","scenes","scene","gltf","async","loadGltf","baseUrl","URL","location","href","u","startsWith","meta","exec","atob","charCodeAt","TextEncoder","encode","decodeURIComponent","dataUri","fetch","ok","status","arrayBuffer","Promise","all","uri","resolve","reject","im","createImageBitmap","Blob","mimeType","formatGltf","id","RUNTIME_VERSION","requires","api","register"],"mappings":"4BA+BO,MAAMA,EAAO,CAClBC,SAAU,IAAY,IAAIC,aAAa,CAAC,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,IACrF,QAAAC,CAASC,EAASC,EAASC,EAAY,IAAIJ,aAAa,KACtD,IAAK,IAAIK,EAAI,EAAGA,EAAI,EAAGA,IACrB,IAAK,IAAIC,EAAI,EAAGA,EAAI,EAAGA,IAAKF,EAAQ,EAAJC,EAAQC,GAAKJ,EAAEI,GAAKH,EAAM,EAAJE,GAASH,EAAE,EAAII,GAAKH,EAAM,EAAJE,EAAQ,GAAKH,EAAE,EAAII,GAAKH,EAAM,EAAJE,EAAQ,GAAKH,EAAE,GAAKI,GAAKH,EAAM,EAAJE,EAAQ,GAC3I,OAAOD,CACT,EACA,WAAAG,CAAYC,EAAcC,EAAgBC,EAAcC,GACtD,MAAMC,EAAI,EAAIC,KAAKC,IAAIN,EAAO,GAAIO,EAAK,GAAKL,EAAOC,GACnD,OAAO,IAAIX,aAAa,CAACY,EAAIH,EAAQ,EAAG,EAAG,EAAG,EAAGG,EAAG,EAAG,EAAG,EAAG,GAAID,EAAMD,GAAQK,GAAI,EAAI,EAAG,EAAG,EAAIJ,EAAMD,EAAOK,EAAI,GACpH,E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RUNTIME_VERSION } from '../chunks/registry-DXdFb2fJ.js';
2
+ import { standardMaterial, texture, computeNormals, GlNode } from './gl.js';
3
+
4
+ /**
5
+ * `motionary/runtime/format-gltf` (10.5) — glTF 2.0 / GLB loader for
6
+ * `motionary/runtime/gl` (own implementation):
7
+ *
8
+ * - `.gltf` (JSON + external or `data:` buffers / images) and `.glb`
9
+ * (binary container: JSON + BIN chunks);
10
+ * - scenes and the node hierarchy (TRS or `matrix`), meshes with several
11
+ * primitives (POSITION, NORMAL, TEXCOORD_0, indices; any component type,
12
+ * normalised integers, interleaved `byteStride`; modes points, lines,
13
+ * triangles, strips, fans);
14
+ * - PBR metallic-roughness materials (base colour factor + texture,
15
+ * metallic / roughness factors, emissive factor, alpha modes, double-sided);
16
+ * images from buffer views or URIs (decoded with `createImageBitmap`);
17
+ * - files that *require* an extension we do not implement (e.g. Draco /
18
+ * KTX2 compression) fail with a clear error naming it.
19
+ *
20
+ * Skins, morph targets and animations arrive in 10.8. `parseGlb()` /
21
+ * `gltfToNode()` with an `images` override are pure (SSR / workers).
22
+ */
23
+ /** Extensions this loader understands (others that a file *requires* make it fail clearly). */
24
+ const SUPPORTED_EXTENSIONS = ['KHR_materials_emissive_strength', 'KHR_materials_unlit'];
25
+ /** Split a GLB container into its JSON and BIN chunk (pure). */
26
+ function parseGlb(input) {
27
+ const b = input instanceof Uint8Array ? input : new Uint8Array(input);
28
+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
29
+ if (v.getUint32(0, true) !== 0x46546c67)
30
+ throw new Error('[motionary] format-gltf: not a GLB file');
31
+ if (v.getUint32(4, true) !== 2)
32
+ throw new Error('[motionary] format-gltf: only glTF 2.0 GLB is supported');
33
+ const len = Math.min(v.getUint32(8, true), b.byteLength);
34
+ let p = 12, json = null, bin = null;
35
+ while (p + 8 <= len) {
36
+ const cl = v.getUint32(p, true), ct = v.getUint32(p + 4, true);
37
+ const data = b.subarray(p + 8, p + 8 + cl);
38
+ if (ct === 0x4e4f534a)
39
+ json = JSON.parse(new TextDecoder().decode(data));
40
+ else if (ct === 0x004e4942 && !bin)
41
+ bin = data;
42
+ p += 8 + cl;
43
+ }
44
+ if (!json)
45
+ throw new Error('[motionary] format-gltf: GLB without a JSON chunk');
46
+ return { json, bin };
47
+ }
48
+ const COMP = {
49
+ 5120: [1, Int8Array, 127], 5121: [1, Uint8Array, 255], 5122: [2, Int16Array, 32767], 5123: [2, Uint16Array, 65535], 5125: [4, Uint32Array, 0], 5126: [4, Float32Array, 0],
50
+ };
51
+ const SIZE = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };
52
+ /** Read an accessor into a flat typed array (floats are de-interleaved; normalised ints become floats). */
53
+ function readAccessor(json, buffers, index, asFloat = true) {
54
+ const a = json.accessors?.[index];
55
+ if (!a)
56
+ throw new Error(`[motionary] format-gltf: accessor ${index} missing`);
57
+ const [bytes, Ctor, max] = COMP[a.componentType] || [];
58
+ if (!Ctor)
59
+ throw new Error(`[motionary] format-gltf: component type ${a.componentType} unsupported`);
60
+ const n = SIZE[a.type], count = a.count * n;
61
+ const isFloat = Ctor === Float32Array;
62
+ const out = asFloat || isFloat ? new Float32Array(count) : new Ctor(count);
63
+ if (a.bufferView === undefined)
64
+ return out; // all zeros (sparse-only accessors)
65
+ const bv = json.bufferViews[a.bufferView];
66
+ const buf = buffers[bv.buffer];
67
+ const base = (bv.byteOffset || 0) + (a.byteOffset || 0);
68
+ const stride = bv.byteStride || bytes * n;
69
+ const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
70
+ const get = (o) => (bytes === 4 ? (isFloat ? dv.getFloat32(o, true) : dv.getUint32(o, true)) : bytes === 2 ? (Ctor === Int16Array ? dv.getInt16(o, true) : dv.getUint16(o, true)) : Ctor === Int8Array ? dv.getInt8(o) : dv.getUint8(o));
71
+ for (let i = 0; i < a.count; i++)
72
+ for (let k = 0; k < n; k++) {
73
+ let x = get(base + i * stride + k * bytes);
74
+ if (a.normalized && max)
75
+ x = Math.max(x / max, -1);
76
+ out[i * n + k] = x;
77
+ }
78
+ return out;
79
+ }
80
+ function toTriangles(idx, mode) {
81
+ const out = [];
82
+ if (mode === 5)
83
+ for (let i = 0; i + 2 < idx.length; i++)
84
+ out.push(...(i % 2 ? [idx[i + 1], idx[i], idx[i + 2]] : [idx[i], idx[i + 1], idx[i + 2]]));
85
+ else
86
+ for (let i = 1; i + 1 < idx.length; i++)
87
+ out.push(idx[0], idx[i], idx[i + 1]);
88
+ return new Uint32Array(out);
89
+ }
90
+ /** Build a runtime/gl node tree from parsed glTF (pure, given buffers and decoded images). */
91
+ function gltfToNode(json, buffers, images = {}, sceneIndex) {
92
+ if (!json.asset || !/^2\./.test(json.asset.version))
93
+ throw new Error('[motionary] format-gltf: only glTF 2.0 is supported');
94
+ const missing = (json.extensionsRequired || []).filter((e) => !SUPPORTED_EXTENSIONS.includes(e));
95
+ if (missing.length)
96
+ throw new Error(`[motionary] format-gltf: this file requires ${missing.join(', ')}, which motionary/runtime/format-gltf does not implement${missing.some((e) => /draco|KHR_texture_basisu|meshopt/i.test(e)) ? ' (compressed geometry / textures need the official decoders — re-export the model without compression, or use the decoder hooks planned for 10.9)' : ''}`);
97
+ const mats = (json.materials || []).map((m) => {
98
+ const pbr = m.pbrMetallicRoughness || {};
99
+ const cf = pbr.baseColorFactor || [1, 1, 1, 1];
100
+ // glTF factors are linear; the shader linearises colour input → convert the factor to sRGB space
101
+ const toS = (x) => Math.pow(Math.max(0, x), 1 / 2.2);
102
+ const strength = m.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1;
103
+ const mat = standardMaterial({ color: [toS(cf[0]), toS(cf[1]), toS(cf[2]), cf[3] ?? 1], metallic: pbr.metallicFactor ?? 1, roughness: pbr.roughnessFactor ?? 1, emissive: (m.emissiveFactor || [0, 0, 0]).map((x) => x * strength), doubleSided: !!m.doubleSided, transparent: m.alphaMode === 'BLEND' });
104
+ if (m.extensions?.KHR_materials_unlit)
105
+ mat.type = 'unlit';
106
+ const ti = pbr.baseColorTexture?.index;
107
+ const src = ti !== undefined ? json.textures?.[ti]?.source : undefined;
108
+ if (src !== undefined && images[src])
109
+ mat.map = texture(images[src]);
110
+ return mat;
111
+ });
112
+ const meshes = (json.meshes || []).map((m) => m.primitives.map((p) => {
113
+ const mode = p.mode ?? 4;
114
+ let g = {
115
+ positions: readAccessor(json, buffers, p.attributes.POSITION),
116
+ normals: p.attributes.NORMAL !== undefined ? readAccessor(json, buffers, p.attributes.NORMAL) : undefined,
117
+ uvs: p.attributes.TEXCOORD_0 !== undefined ? readAccessor(json, buffers, p.attributes.TEXCOORD_0) : undefined,
118
+ mode: mode === 0 ? 'points' : mode >= 1 && mode <= 3 ? 'lines' : 'triangles',
119
+ };
120
+ if (p.indices !== undefined) {
121
+ let idx = readAccessor(json, buffers, p.indices, false);
122
+ if (mode === 5 || mode === 6)
123
+ idx = toTriangles(Uint32Array.from(idx), mode);
124
+ g.indices = idx instanceof Uint8Array || (idx instanceof Uint32Array && g.positions.length / 3 <= 65535) ? Uint16Array.from(idx) : idx;
125
+ }
126
+ else if (mode === 5 || mode === 6)
127
+ g.indices = toTriangles(Uint32Array.from({ length: g.positions.length / 3 }, (_, i) => i), mode);
128
+ if (!g.normals && g.mode === 'triangles')
129
+ g = computeNormals(g);
130
+ return { geometry: g, material: p.material !== undefined ? mats[p.material] : standardMaterial({ metallic: 0, roughness: 0.6 }) };
131
+ }));
132
+ const nodes = (json.nodes || []).map((n, i) => {
133
+ const node = new GlNode(n.name || `node${i}`, n.mesh !== undefined ? meshes[n.mesh] : null);
134
+ if (n.matrix)
135
+ node.matrix = new Float32Array(n.matrix);
136
+ if (n.translation)
137
+ node.position = n.translation.slice(0, 3);
138
+ if (n.rotation)
139
+ node.rotation = n.rotation.slice(0, 4);
140
+ if (n.scale)
141
+ node.scale = n.scale.slice(0, 3);
142
+ node.extras.gltfIndex = i;
143
+ return node;
144
+ });
145
+ (json.nodes || []).forEach((n, i) => (n.children || []).forEach((c) => nodes[i].add(nodes[c])));
146
+ const root = new GlNode('gltf');
147
+ const sc = json.scenes?.[sceneIndex ?? json.scene ?? 0];
148
+ const tops = sc?.nodes ?? nodes.map((_, i) => i).filter((i) => !nodes[i].parent);
149
+ tops.forEach((i) => root.add(nodes[i]));
150
+ root.extras = { gltf: json, nodes };
151
+ return root;
152
+ }
153
+ const dataUri = (u) => {
154
+ const [, meta, data] = /^data:([^,]*),(.*)$/s.exec(u) || [];
155
+ if (meta === undefined)
156
+ throw new Error('[motionary] format-gltf: bad data URI');
157
+ if (/;base64/.test(meta)) {
158
+ const s = atob(data);
159
+ return Uint8Array.from(s, (c) => c.charCodeAt(0));
160
+ }
161
+ return new TextEncoder().encode(decodeURIComponent(data));
162
+ };
163
+ /** Load a `.gltf` / `.glb` (URL or bytes) with its buffers and images and build a node tree. */
164
+ async function loadGltf(src, o = {}) {
165
+ const base = o.baseUrl || (typeof src === 'string' ? new URL(src, typeof location !== 'undefined' ? location.href : 'file:///').href : typeof location !== 'undefined' ? location.href : 'file:///');
166
+ const get = async (u) => {
167
+ if (u.startsWith('data:'))
168
+ return dataUri(u);
169
+ const r = await fetch(new URL(u, base).href);
170
+ if (!r.ok)
171
+ throw new Error(`[motionary] format-gltf: could not load ${u} (${r.status})`);
172
+ return new Uint8Array(await r.arrayBuffer());
173
+ };
174
+ const bytes = typeof src === 'string' ? await get(src) : src instanceof Uint8Array ? src : new Uint8Array(src);
175
+ let json, bin = null;
176
+ if (bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46)
177
+ ({ json, bin } = parseGlb(bytes));
178
+ else
179
+ json = JSON.parse(new TextDecoder().decode(bytes));
180
+ const buffers = await Promise.all((json.buffers || []).map((b, i) => (b.uri ? get(b.uri) : i === 0 && bin ? Promise.resolve(bin) : Promise.reject(new Error('[motionary] format-gltf: buffer without data')))));
181
+ const images = {};
182
+ await Promise.all((json.images || []).map(async (im, i) => {
183
+ let data;
184
+ if (im.bufferView !== undefined) {
185
+ const bv = json.bufferViews[im.bufferView];
186
+ data = buffers[bv.buffer].subarray(bv.byteOffset || 0, (bv.byteOffset || 0) + bv.byteLength);
187
+ }
188
+ else if (im.uri)
189
+ data = await get(im.uri);
190
+ else
191
+ return;
192
+ images[i] = await createImageBitmap(new Blob([data], { type: im.mimeType || (im.uri && /\.jpe?g$/i.test(im.uri) ? 'image/jpeg' : 'image/png') }));
193
+ }));
194
+ return gltfToNode(json, buffers, images, o.scene);
195
+ }
196
+ /** The module object for `use(formatGltf)` (needs `gl`). */
197
+ const formatGltf = { id: 'format-gltf', version: RUNTIME_VERSION, requires: ['core', 'gl'], api: { parseGlb, readAccessor, gltfToNode, loadGltf, SUPPORTED_EXTENSIONS } };
198
+
199
+ export { SUPPORTED_EXTENSIONS, formatGltf, gltfToNode, loadGltf, parseGlb, readAccessor };
200
+ //# sourceMappingURL=format-gltf.js.map