3d-spinner 0.9.1 → 0.9.3

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 (101) hide show
  1. package/README.md +96 -11
  2. package/dist/animation-label.d.ts +8 -0
  3. package/dist/animation-label.js +47 -0
  4. package/dist/animation.d.ts +2 -0
  5. package/dist/animations/charged-orb.d.ts +55 -0
  6. package/dist/animations/charged-orb.js +229 -0
  7. package/dist/animations/grid-assembly.d.ts +67 -0
  8. package/dist/animations/grid-assembly.js +268 -0
  9. package/dist/animations/object-motion.d.ts +19 -7
  10. package/dist/animations/object-motion.js +38 -32
  11. package/dist/animations/particles.d.ts +110 -0
  12. package/dist/animations/particles.js +209 -0
  13. package/dist/cjs/animations/charged-orb.cjs +1334 -0
  14. package/dist/cjs/animations/grid-assembly.cjs +1498 -0
  15. package/dist/cjs/animations/object-motion.cjs +1449 -0
  16. package/dist/cjs/animations/particles.cjs +1940 -0
  17. package/dist/cjs/animations/spin.cjs +1300 -0
  18. package/dist/cjs/composite-animation.cjs +58 -0
  19. package/dist/cjs/engines/little-3d-engine/little-3d-engine.cjs +1433 -0
  20. package/dist/cjs/engines/little-3d-engine/loaders/obj.cjs +87 -0
  21. package/dist/cjs/engines/little-3d-engine/renderers/canvas2d-textured.cjs +345 -0
  22. package/dist/cjs/engines/little-3d-engine/renderers/webgl-textured.cjs +528 -0
  23. package/dist/cjs/engines/little-3d-engine/renderers/webgpu-textured.cjs +712 -0
  24. package/dist/cjs/engines/little-tween-engine/little-tween-engine.cjs +279 -0
  25. package/dist/cjs/index.cjs +120 -0
  26. package/dist/cjs/motion/motion.cjs +140 -0
  27. package/dist/cjs/motion/transitions.cjs +80 -0
  28. package/dist/cjs/prefabs/prefabs.cjs +3450 -0
  29. package/dist/composite-animation.d.ts +18 -0
  30. package/dist/composite-animation.js +39 -0
  31. package/dist/engines/little-3d-engine/little-3d-engine.d.ts +17 -12
  32. package/dist/engines/little-3d-engine/little-3d-engine.js +13 -8
  33. package/dist/engines/little-3d-engine/loaders/obj.d.ts +12 -4
  34. package/dist/engines/little-3d-engine/loaders/obj.js +44 -5
  35. package/dist/engines/little-3d-engine/renderer.d.ts +7 -1
  36. package/dist/engines/little-3d-engine/renderer.js +2 -0
  37. package/dist/engines/little-3d-engine/renderers/canvas2d-textured.d.ts +20 -0
  38. package/dist/engines/little-3d-engine/renderers/canvas2d-textured.js +135 -0
  39. package/dist/engines/little-3d-engine/renderers/textured-helpers.d.ts +9 -0
  40. package/dist/engines/little-3d-engine/renderers/textured-helpers.js +35 -0
  41. package/dist/engines/little-3d-engine/renderers/webgl-textured.d.ts +43 -0
  42. package/dist/engines/little-3d-engine/renderers/webgl-textured.js +211 -0
  43. package/dist/engines/little-3d-engine/renderers/webgpu-textured.d.ts +45 -0
  44. package/dist/engines/little-3d-engine/renderers/webgpu-textured.js +300 -0
  45. package/dist/engines/little-3d-engine/renderers/webgpu.d.ts +11 -6
  46. package/dist/engines/little-3d-engine/shapes/complex/plane.d.ts +3 -0
  47. package/dist/engines/little-3d-engine/shapes/complex/plane.js +33 -0
  48. package/dist/engines/little-3d-engine/shapes/{cube.d.ts → primitives/cube.d.ts} +1 -1
  49. package/dist/engines/little-3d-engine/shapes/{octahedron.d.ts → primitives/octahedron.d.ts} +1 -1
  50. package/dist/engines/little-3d-engine/shapes/{pyramid.d.ts → primitives/pyramid.d.ts} +1 -1
  51. package/dist/engines/little-3d-engine/shapes/primitives/quad.d.ts +9 -0
  52. package/dist/engines/little-3d-engine/shapes/primitives/quad.js +18 -0
  53. package/dist/engines/little-3d-engine/shapes/{cube-sphere.d.ts → primitives/spheres/cube-sphere.d.ts} +1 -1
  54. package/dist/engines/little-3d-engine/shapes/{icosphere.d.ts → primitives/spheres/icosphere.d.ts} +1 -1
  55. package/dist/engines/little-3d-engine/shapes/{icosphere.js → primitives/spheres/icosphere.js} +1 -1
  56. package/dist/engines/little-3d-engine/shapes/{octa-sphere.d.ts → primitives/spheres/octa-sphere.d.ts} +1 -1
  57. package/dist/engines/little-3d-engine/shapes/{octa-sphere.js → primitives/spheres/octa-sphere.js} +1 -1
  58. package/dist/engines/little-3d-engine/shapes/{uv-sphere.d.ts → primitives/spheres/uv-sphere.d.ts} +1 -1
  59. package/dist/engines/little-3d-engine/shapes/{tetrahedron.d.ts → primitives/tetrahedron.d.ts} +1 -1
  60. package/dist/engines/little-3d-engine/textures/dynamic/canvas-texture.d.ts +1 -0
  61. package/dist/engines/little-3d-engine/textures/dynamic/canvas-texture.js +8 -0
  62. package/dist/engines/little-3d-engine/textures/dynamic/shine.d.ts +2 -0
  63. package/dist/engines/little-3d-engine/textures/dynamic/shine.js +14 -0
  64. package/dist/engines/little-3d-engine/textures/dynamic/star.d.ts +2 -0
  65. package/dist/engines/little-3d-engine/textures/dynamic/star.js +16 -0
  66. package/dist/engines/little-3d-engine/textures/dynamic/streak.d.ts +5 -0
  67. package/dist/engines/little-3d-engine/textures/dynamic/streak.js +20 -0
  68. package/dist/index.d.ts +2 -1
  69. package/dist/prefabs/charged-orb.d.ts +17 -0
  70. package/dist/prefabs/charged-orb.js +37 -0
  71. package/dist/prefabs/crystal-comet.d.ts +4 -0
  72. package/dist/prefabs/crystal-comet.js +41 -0
  73. package/dist/prefabs/ghost-train.d.ts +9 -0
  74. package/dist/prefabs/ghost-train.js +44 -0
  75. package/dist/prefabs/grid-assembly.d.ts +13 -0
  76. package/dist/prefabs/grid-assembly.js +15 -0
  77. package/dist/prefabs/monochrome-streak.d.ts +4 -0
  78. package/dist/prefabs/monochrome-streak.js +25 -0
  79. package/dist/prefabs/plane-star-trail.d.ts +4 -0
  80. package/dist/prefabs/plane-star-trail.js +40 -0
  81. package/dist/prefabs/prefabs.d.ts +10 -0
  82. package/dist/prefabs/prefabs.js +9 -0
  83. package/dist/prefabs/pulsing-starfield.d.ts +4 -0
  84. package/dist/prefabs/pulsing-starfield.js +27 -0
  85. package/dist/prefabs/rocket-launch.d.ts +8 -0
  86. package/dist/prefabs/rocket-launch.js +59 -0
  87. package/dist/prefabs/spinner.d.ts +7 -0
  88. package/dist/prefabs/spinner.js +17 -0
  89. package/dist/prefabs/star-swarm.d.ts +4 -0
  90. package/dist/prefabs/star-swarm.js +27 -0
  91. package/dist/prefabs/types.d.ts +46 -0
  92. package/dist/prefabs/types.js +1 -0
  93. package/dist/umd/spinner.global.js +4212 -0
  94. package/dist/umd/spinner.global.min.js +113 -0
  95. package/package.json +67 -11
  96. /package/dist/engines/little-3d-engine/shapes/{cube.js → primitives/cube.js} +0 -0
  97. /package/dist/engines/little-3d-engine/shapes/{octahedron.js → primitives/octahedron.js} +0 -0
  98. /package/dist/engines/little-3d-engine/shapes/{pyramid.js → primitives/pyramid.js} +0 -0
  99. /package/dist/engines/little-3d-engine/shapes/{cube-sphere.js → primitives/spheres/cube-sphere.js} +0 -0
  100. /package/dist/engines/little-3d-engine/shapes/{uv-sphere.js → primitives/spheres/uv-sphere.js} +0 -0
  101. /package/dist/engines/little-3d-engine/shapes/{tetrahedron.js → primitives/tetrahedron.js} +0 -0
@@ -0,0 +1,1449 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esm = (fn, res, err) => function __init() {
7
+ if (err) throw err[0];
8
+ try {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ } catch (e) {
11
+ throw err = [e], e;
12
+ }
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+
28
+ // src/engines/little-3d-engine/core/math.ts
29
+ function subtract(a, b) {
30
+ return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };
31
+ }
32
+ function cross(a, b) {
33
+ return {
34
+ x: a.y * b.z - a.z * b.y,
35
+ y: a.z * b.x - a.x * b.z,
36
+ z: a.x * b.y - a.y * b.x
37
+ };
38
+ }
39
+ function dot(a, b) {
40
+ return a.x * b.x + a.y * b.y + a.z * b.z;
41
+ }
42
+ function scale(v, s) {
43
+ return { x: v.x * s, y: v.y * s, z: v.z * s };
44
+ }
45
+ function normalize(v) {
46
+ const length = Math.hypot(v.x, v.y, v.z);
47
+ if (length === 0) return { x: 0, y: 0, z: 0 };
48
+ return { x: v.x / length, y: v.y / length, z: v.z / length };
49
+ }
50
+ function multiply(a, b) {
51
+ const out = new Array(16);
52
+ for (let col = 0; col < 4; col++) {
53
+ for (let row = 0; row < 4; row++) {
54
+ let sum = 0;
55
+ for (let k = 0; k < 4; k++) {
56
+ sum += a[k * 4 + row] * b[col * 4 + k];
57
+ }
58
+ out[col * 4 + row] = sum;
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+ function translation(x, y, z) {
64
+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
65
+ }
66
+ function scaleMatrix(s) {
67
+ return [s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1];
68
+ }
69
+ function rotationX(rad) {
70
+ const c = Math.cos(rad);
71
+ const s = Math.sin(rad);
72
+ return [1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1];
73
+ }
74
+ function rotationY(rad) {
75
+ const c = Math.cos(rad);
76
+ const s = Math.sin(rad);
77
+ return [c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1];
78
+ }
79
+ function rotationZ(rad) {
80
+ const c = Math.cos(rad);
81
+ const s = Math.sin(rad);
82
+ return [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
83
+ }
84
+ function perspective(fovY, aspect, near, far) {
85
+ const f = 1 / Math.tan(fovY / 2);
86
+ const nf = 1 / (near - far);
87
+ return [
88
+ f / aspect,
89
+ 0,
90
+ 0,
91
+ 0,
92
+ 0,
93
+ f,
94
+ 0,
95
+ 0,
96
+ 0,
97
+ 0,
98
+ (far + near) * nf,
99
+ -1,
100
+ 0,
101
+ 0,
102
+ 2 * far * near * nf,
103
+ 0
104
+ ];
105
+ }
106
+ function transformPoint(m, p) {
107
+ const x = m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12];
108
+ const y = m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13];
109
+ const z = m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14];
110
+ const w = m[3] * p.x + m[7] * p.y + m[11] * p.z + m[15] || 1;
111
+ return { x: x / w, y: y / w, z: z / w };
112
+ }
113
+ function transformAffine(m, p) {
114
+ return {
115
+ x: m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12],
116
+ y: m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13],
117
+ z: m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14]
118
+ };
119
+ }
120
+ var init_math = __esm({
121
+ "src/engines/little-3d-engine/core/math.ts"() {
122
+ "use strict";
123
+ }
124
+ });
125
+
126
+ // src/engines/little-3d-engine/core/geometry.ts
127
+ function parseColor(color) {
128
+ const hex = color.trim().replace("#", "");
129
+ const full = hex.length === 3 ? hex.split("").map((c) => c + c).join("") : hex;
130
+ const n = parseInt(full, 16);
131
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
132
+ }
133
+ function expandToTriangles(mesh) {
134
+ let triangles = 0;
135
+ for (const face of mesh.faces) triangles += Math.max(0, face.indices.length - 2);
136
+ const positions = new Float32Array(triangles * 9);
137
+ const normals = new Float32Array(triangles * 9);
138
+ const colors = new Float32Array(triangles * 9);
139
+ let o = 0;
140
+ for (const face of mesh.faces) {
141
+ const v0 = mesh.vertices[face.indices[0]];
142
+ const v1 = mesh.vertices[face.indices[1]];
143
+ const v2 = mesh.vertices[face.indices[2]];
144
+ const normal = normalize(cross(subtract(v1, v0), subtract(v2, v0)));
145
+ const [r, g, b] = parseColor(face.color);
146
+ const cr = r / 255;
147
+ const cg = g / 255;
148
+ const cb = b / 255;
149
+ for (let k = 1; k < face.indices.length - 1; k++) {
150
+ const tri = [face.indices[0], face.indices[k], face.indices[k + 1]];
151
+ for (const index of tri) {
152
+ const v = mesh.vertices[index];
153
+ positions[o] = v.x;
154
+ positions[o + 1] = v.y;
155
+ positions[o + 2] = v.z;
156
+ normals[o] = normal.x;
157
+ normals[o + 1] = normal.y;
158
+ normals[o + 2] = normal.z;
159
+ colors[o] = cr;
160
+ colors[o + 1] = cg;
161
+ colors[o + 2] = cb;
162
+ o += 3;
163
+ }
164
+ }
165
+ }
166
+ return { positions, normals, colors, count: positions.length / 3 };
167
+ }
168
+ var init_geometry = __esm({
169
+ "src/engines/little-3d-engine/core/geometry.ts"() {
170
+ "use strict";
171
+ init_math();
172
+ }
173
+ });
174
+
175
+ // src/engines/little-3d-engine/core/light.ts
176
+ function clamp01(value) {
177
+ return Math.min(1, Math.max(0, value));
178
+ }
179
+ function shadeColor(normal, color, light) {
180
+ const lambert = Math.max(0, dot(normal, light.toLight));
181
+ const brightness = clamp01(light.ambient + light.intensity * lambert);
182
+ const [r, g, b] = parseColor(color);
183
+ return `rgb(${Math.round(r * brightness)}, ${Math.round(g * brightness)}, ${Math.round(
184
+ b * brightness
185
+ )})`;
186
+ }
187
+ var DEFAULTS2, Light;
188
+ var init_light = __esm({
189
+ "src/engines/little-3d-engine/core/light.ts"() {
190
+ "use strict";
191
+ init_math();
192
+ init_geometry();
193
+ DEFAULTS2 = {
194
+ direction: { x: -0.4, y: -0.7, z: -0.6 },
195
+ intensity: 0.85,
196
+ ambient: 0.25
197
+ };
198
+ Light = class {
199
+ constructor(options) {
200
+ this.options = { ...DEFAULTS2, ...options };
201
+ this.params = {
202
+ toLight: normalize(scale(this.options.direction, -1)),
203
+ intensity: this.options.intensity,
204
+ ambient: this.options.ambient
205
+ };
206
+ }
207
+ /** Convenience wrapper around {@link shadeColor} using this light. */
208
+ shade(normal, color) {
209
+ return shadeColor(normal, color, this.params);
210
+ }
211
+ };
212
+ }
213
+ });
214
+
215
+ // src/engines/little-3d-engine/renderers/webgl.ts
216
+ var webgl_exports = {};
217
+ __export(webgl_exports, {
218
+ WebGLRenderer: () => WebGLRenderer
219
+ });
220
+ function compile(gl, type, source) {
221
+ const shader = gl.createShader(type);
222
+ gl.shaderSource(shader, source);
223
+ gl.compileShader(shader);
224
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
225
+ throw new Error(`3d-spinner: shader compile failed: ${gl.getShaderInfoLog(shader)}`);
226
+ }
227
+ return shader;
228
+ }
229
+ function link(gl) {
230
+ const program = gl.createProgram();
231
+ gl.attachShader(program, compile(gl, gl.VERTEX_SHADER, VERTEX_SHADER));
232
+ gl.attachShader(program, compile(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER));
233
+ gl.linkProgram(program);
234
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
235
+ throw new Error(`3d-spinner: program link failed: ${gl.getProgramInfoLog(program)}`);
236
+ }
237
+ return program;
238
+ }
239
+ var VERTEX_SHADER, FRAGMENT_SHADER, WebGLRenderer;
240
+ var init_webgl = __esm({
241
+ "src/engines/little-3d-engine/renderers/webgl.ts"() {
242
+ "use strict";
243
+ init_geometry();
244
+ init_renderer();
245
+ VERTEX_SHADER = `#version 300 es
246
+ in vec3 aPos;
247
+ in vec3 aNormal;
248
+ in vec3 aColor;
249
+ uniform mat4 uViewProj;
250
+ uniform mat4 uModel;
251
+ out vec3 vNormal;
252
+ out vec3 vColor;
253
+ void main() {
254
+ vNormal = mat3(uModel) * aNormal;
255
+ vColor = aColor;
256
+ gl_Position = uViewProj * uModel * vec4(aPos, 1.0);
257
+ }`;
258
+ FRAGMENT_SHADER = `#version 300 es
259
+ precision mediump float;
260
+ in vec3 vNormal;
261
+ in vec3 vColor;
262
+ uniform vec3 uToLight;
263
+ uniform float uIntensity;
264
+ uniform float uAmbient;
265
+ uniform float uOpacity;
266
+ out vec4 fragColor;
267
+ void main() {
268
+ float lambert = max(dot(normalize(vNormal), normalize(uToLight)), 0.0);
269
+ float brightness = clamp(uAmbient + uIntensity * lambert, 0.0, 1.0);
270
+ fragColor = vec4(vColor * brightness, uOpacity);
271
+ }`;
272
+ WebGLRenderer = class {
273
+ constructor(options = {}) {
274
+ this.cache = /* @__PURE__ */ new Map();
275
+ if (options.background) {
276
+ const [r, g, b] = parseColor(options.background);
277
+ this.clearColor = [r / 255, g / 255, b / 255, 1];
278
+ } else {
279
+ this.clearColor = [0, 0, 0, 0];
280
+ }
281
+ }
282
+ init(canvas) {
283
+ const gl = canvas.getContext("webgl2");
284
+ if (!gl) throw new Error("3d-spinner: WebGL2 is not supported in this browser.");
285
+ this.gl = gl;
286
+ this.program = link(gl);
287
+ this.locations = {
288
+ aPos: gl.getAttribLocation(this.program, "aPos"),
289
+ aNormal: gl.getAttribLocation(this.program, "aNormal"),
290
+ aColor: gl.getAttribLocation(this.program, "aColor"),
291
+ uViewProj: gl.getUniformLocation(this.program, "uViewProj"),
292
+ uModel: gl.getUniformLocation(this.program, "uModel"),
293
+ uToLight: gl.getUniformLocation(this.program, "uToLight"),
294
+ uIntensity: gl.getUniformLocation(this.program, "uIntensity"),
295
+ uAmbient: gl.getUniformLocation(this.program, "uAmbient"),
296
+ uOpacity: gl.getUniformLocation(this.program, "uOpacity")
297
+ };
298
+ gl.enable(gl.DEPTH_TEST);
299
+ gl.enable(gl.CULL_FACE);
300
+ gl.cullFace(gl.BACK);
301
+ gl.frontFace(gl.CCW);
302
+ }
303
+ resize() {
304
+ const gl = this.gl;
305
+ if (!gl) return;
306
+ const canvas = gl.canvas;
307
+ gl.viewport(0, 0, canvas.width, canvas.height);
308
+ }
309
+ buffers(mesh) {
310
+ const cached = this.cache.get(mesh);
311
+ if (cached) return cached;
312
+ const gl = this.gl;
313
+ const loc = this.locations;
314
+ const data = expandToTriangles(mesh);
315
+ const vao = gl.createVertexArray();
316
+ gl.bindVertexArray(vao);
317
+ const attribute = (location, array) => {
318
+ if (location < 0) return;
319
+ const buffer = gl.createBuffer();
320
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
321
+ gl.bufferData(gl.ARRAY_BUFFER, array, gl.STATIC_DRAW);
322
+ gl.enableVertexAttribArray(location);
323
+ gl.vertexAttribPointer(location, 3, gl.FLOAT, false, 0, 0);
324
+ };
325
+ attribute(loc.aPos, data.positions);
326
+ attribute(loc.aNormal, data.normals);
327
+ attribute(loc.aColor, data.colors);
328
+ gl.bindVertexArray(null);
329
+ const result = { vao, count: data.count };
330
+ this.cache.set(mesh, result);
331
+ return result;
332
+ }
333
+ render(frame) {
334
+ const gl = this.gl;
335
+ const loc = this.locations;
336
+ if (!gl || !this.program || !loc) return;
337
+ gl.clearColor(...this.clearColor);
338
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
339
+ gl.useProgram(this.program);
340
+ gl.uniformMatrix4fv(loc.uViewProj, false, new Float32Array(frame.viewProjection));
341
+ gl.uniform3f(loc.uToLight, frame.light.toLight.x, frame.light.toLight.y, frame.light.toLight.z);
342
+ gl.uniform1f(loc.uIntensity, frame.light.intensity);
343
+ gl.uniform1f(loc.uAmbient, frame.light.ambient);
344
+ gl.disable(gl.BLEND);
345
+ gl.depthMask(true);
346
+ gl.cullFace(gl.BACK);
347
+ for (const item of frame.items) {
348
+ if (item.transparency) continue;
349
+ const mesh = this.buffers(item.mesh);
350
+ gl.uniformMatrix4fv(loc.uModel, false, new Float32Array(item.model));
351
+ gl.uniform1f(loc.uOpacity, 1);
352
+ gl.bindVertexArray(mesh.vao);
353
+ gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
354
+ }
355
+ gl.enable(gl.BLEND);
356
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
357
+ gl.depthMask(false);
358
+ for (const item of frame.items) {
359
+ const transparency = item.transparency;
360
+ if (!transparency) continue;
361
+ const mesh = this.buffers(item.mesh);
362
+ gl.uniformMatrix4fv(loc.uModel, false, new Float32Array(item.model));
363
+ gl.bindVertexArray(mesh.vao);
364
+ if (transparency.mode === "two-sided") {
365
+ const resolved = resolveTwoSidedOpacity(transparency);
366
+ gl.cullFace(gl.FRONT);
367
+ gl.uniform1f(loc.uOpacity, resolved.back);
368
+ gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
369
+ gl.cullFace(gl.BACK);
370
+ gl.uniform1f(loc.uOpacity, resolved.front);
371
+ gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
372
+ } else {
373
+ gl.cullFace(gl.BACK);
374
+ gl.uniform1f(loc.uOpacity, opacity(transparency.opacity, DEFAULT_ONE_SIDED_OPACITY));
375
+ gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
376
+ }
377
+ }
378
+ gl.depthMask(true);
379
+ gl.disable(gl.BLEND);
380
+ gl.cullFace(gl.BACK);
381
+ gl.bindVertexArray(null);
382
+ }
383
+ destroy() {
384
+ const gl = this.gl;
385
+ if (gl) {
386
+ for (const mesh of this.cache.values()) gl.deleteVertexArray(mesh.vao);
387
+ if (this.program) gl.deleteProgram(this.program);
388
+ }
389
+ this.cache.clear();
390
+ this.gl = void 0;
391
+ this.program = void 0;
392
+ this.locations = void 0;
393
+ }
394
+ };
395
+ }
396
+ });
397
+
398
+ // src/engines/little-3d-engine/renderers/webgpu.ts
399
+ var webgpu_exports = {};
400
+ __export(webgpu_exports, {
401
+ WebGPURenderer: () => WebGPURenderer
402
+ });
403
+ var WGSL, CLIP_Z_FIX, UNIFORM_STRIDE, WebGPURenderer;
404
+ var init_webgpu = __esm({
405
+ "src/engines/little-3d-engine/renderers/webgpu.ts"() {
406
+ "use strict";
407
+ init_geometry();
408
+ init_math();
409
+ init_renderer();
410
+ WGSL = `
411
+ struct Uniforms {
412
+ viewProj: mat4x4<f32>,
413
+ model: mat4x4<f32>,
414
+ toLight: vec4<f32>,
415
+ params: vec4<f32>,
416
+ };
417
+ @group(0) @binding(0) var<uniform> u: Uniforms;
418
+
419
+ struct VSOut {
420
+ @builtin(position) position: vec4<f32>,
421
+ @location(0) normal: vec3<f32>,
422
+ @location(1) color: vec3<f32>,
423
+ };
424
+
425
+ @vertex
426
+ fn vs(@location(0) pos: vec3<f32>, @location(1) normal: vec3<f32>, @location(2) color: vec3<f32>) -> VSOut {
427
+ var out: VSOut;
428
+ let m = mat3x3<f32>(u.model[0].xyz, u.model[1].xyz, u.model[2].xyz);
429
+ out.normal = m * normal;
430
+ out.color = color;
431
+ out.position = u.viewProj * u.model * vec4<f32>(pos, 1.0);
432
+ return out;
433
+ }
434
+
435
+ @fragment
436
+ fn fs(in: VSOut) -> @location(0) vec4<f32> {
437
+ let lambert = max(dot(normalize(in.normal), normalize(u.toLight.xyz)), 0.0);
438
+ let brightness = clamp(u.params.y + u.params.x * lambert, 0.0, 1.0);
439
+ return vec4<f32>(in.color * brightness, u.params.z);
440
+ }
441
+ `;
442
+ CLIP_Z_FIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1];
443
+ UNIFORM_STRIDE = 256;
444
+ WebGPURenderer = class {
445
+ constructor(options = {}) {
446
+ this.uniformCapacity = 0;
447
+ this.depthSize = "";
448
+ this.destroyed = false;
449
+ this.cache = /* @__PURE__ */ new Map();
450
+ if (options.background) {
451
+ const [r, g, b] = parseColor(options.background);
452
+ this.clearValue = { r: r / 255, g: g / 255, b: b / 255, a: 1 };
453
+ this.alphaMode = "opaque";
454
+ } else {
455
+ this.clearValue = { r: 0, g: 0, b: 0, a: 0 };
456
+ this.alphaMode = "premultiplied";
457
+ }
458
+ }
459
+ async init(canvas) {
460
+ const gpu = navigator.gpu;
461
+ if (!gpu) throw new Error("3d-spinner: WebGPU is not supported in this browser.");
462
+ const adapter = await gpu.requestAdapter();
463
+ if (!adapter) throw new Error("3d-spinner: no WebGPU adapter is available.");
464
+ const device = await adapter.requestDevice();
465
+ if (this.destroyed) {
466
+ device.destroy?.();
467
+ return;
468
+ }
469
+ const context = canvas.getContext("webgpu");
470
+ if (!context) throw new Error("3d-spinner: could not get a WebGPU canvas context.");
471
+ const format = gpu.getPreferredCanvasFormat();
472
+ context.configure({ device, format, alphaMode: this.alphaMode });
473
+ const module2 = device.createShaderModule({ code: WGSL });
474
+ const stage = globalThis.GPUShaderStage;
475
+ const layout = device.createBindGroupLayout({
476
+ entries: [
477
+ {
478
+ binding: 0,
479
+ visibility: stage.VERTEX | stage.FRAGMENT,
480
+ buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 160 }
481
+ }
482
+ ]
483
+ });
484
+ const vertexBuffer = (location) => ({
485
+ arrayStride: 12,
486
+ attributes: [{ shaderLocation: location, offset: 0, format: "float32x3" }]
487
+ });
488
+ const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [layout] });
489
+ const blend = {
490
+ color: {
491
+ srcFactor: "src-alpha",
492
+ dstFactor: "one-minus-src-alpha",
493
+ operation: "add"
494
+ },
495
+ alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" }
496
+ };
497
+ const pipeline = (cullMode, transparent) => device.createRenderPipeline({
498
+ layout: pipelineLayout,
499
+ vertex: {
500
+ module: module2,
501
+ entryPoint: "vs",
502
+ buffers: [vertexBuffer(0), vertexBuffer(1), vertexBuffer(2)]
503
+ },
504
+ fragment: {
505
+ module: module2,
506
+ entryPoint: "fs",
507
+ targets: [{ format, ...transparent ? { blend } : {} }]
508
+ },
509
+ primitive: { topology: "triangle-list", cullMode, frontFace: "ccw" },
510
+ depthStencil: {
511
+ format: "depth24plus",
512
+ depthWriteEnabled: !transparent,
513
+ depthCompare: "less"
514
+ }
515
+ });
516
+ this.pipeline = pipeline("back", false);
517
+ this.transparentBackPipeline = pipeline("front", true);
518
+ this.transparentFrontPipeline = pipeline("back", true);
519
+ this.canvas = canvas;
520
+ this.device = device;
521
+ this.context = context;
522
+ }
523
+ resize() {
524
+ this.ensureDepth();
525
+ }
526
+ ensureDepth() {
527
+ const canvas = this.canvas;
528
+ if (!this.device || !canvas) return;
529
+ const width = Math.max(1, canvas.width);
530
+ const height = Math.max(1, canvas.height);
531
+ const key = `${width}x${height}`;
532
+ if (key === this.depthSize && this.depthTexture) return;
533
+ this.depthTexture?.destroy?.();
534
+ this.depthTexture = this.device.createTexture({
535
+ size: { width, height },
536
+ format: "depth24plus",
537
+ usage: globalThis.GPUTextureUsage.RENDER_ATTACHMENT
538
+ });
539
+ this.depthSize = key;
540
+ }
541
+ buffers(mesh) {
542
+ const cached = this.cache.get(mesh);
543
+ if (cached) return cached;
544
+ const data = expandToTriangles(mesh);
545
+ const usage = globalThis.GPUBufferUsage.VERTEX | globalThis.GPUBufferUsage.COPY_DST;
546
+ const upload = (array) => {
547
+ const buffer = this.device.createBuffer({ size: array.byteLength, usage });
548
+ this.device.queue.writeBuffer(buffer, 0, array);
549
+ return buffer;
550
+ };
551
+ const result = {
552
+ position: upload(data.positions),
553
+ normal: upload(data.normals),
554
+ color: upload(data.colors),
555
+ count: data.count
556
+ };
557
+ this.cache.set(mesh, result);
558
+ return result;
559
+ }
560
+ ensureUniformCapacity(draws) {
561
+ if (draws <= this.uniformCapacity && this.uniformBuffer) return;
562
+ this.uniformBuffer?.destroy?.();
563
+ this.uniformBuffer = this.device.createBuffer({
564
+ size: Math.max(1, draws) * UNIFORM_STRIDE,
565
+ usage: globalThis.GPUBufferUsage.UNIFORM | globalThis.GPUBufferUsage.COPY_DST
566
+ });
567
+ this.uniformCapacity = draws;
568
+ }
569
+ render(frame) {
570
+ if (this.destroyed || !this.device || !this.context || !this.pipeline) return;
571
+ if (frame.width === 0 || frame.height === 0 || frame.items.length === 0) return;
572
+ this.ensureDepth();
573
+ const draws = [];
574
+ for (const item of frame.items) {
575
+ if (!item.transparency) draws.push({ item, opacity: 1, pipeline: this.pipeline });
576
+ }
577
+ for (const item of frame.items) {
578
+ const transparency = item.transparency;
579
+ if (!transparency) continue;
580
+ if (transparency.mode === "two-sided") {
581
+ const resolved = resolveTwoSidedOpacity(transparency);
582
+ draws.push({
583
+ item,
584
+ opacity: resolved.back,
585
+ pipeline: this.transparentBackPipeline
586
+ });
587
+ draws.push({
588
+ item,
589
+ opacity: resolved.front,
590
+ pipeline: this.transparentFrontPipeline
591
+ });
592
+ } else {
593
+ draws.push({
594
+ item,
595
+ opacity: opacity(transparency.opacity, DEFAULT_ONE_SIDED_OPACITY),
596
+ pipeline: this.transparentFrontPipeline
597
+ });
598
+ }
599
+ }
600
+ this.ensureUniformCapacity(draws.length);
601
+ const viewProj = multiply(CLIP_Z_FIX, frame.viewProjection);
602
+ const layout = this.pipeline.getBindGroupLayout(0);
603
+ const bindGroup = this.device.createBindGroup({
604
+ layout,
605
+ entries: [
606
+ { binding: 0, resource: { buffer: this.uniformBuffer, offset: 0, size: 160 } }
607
+ ]
608
+ });
609
+ draws.forEach((draw, i) => {
610
+ const data = new Float32Array(UNIFORM_STRIDE / 4);
611
+ data.set(viewProj, 0);
612
+ data.set(draw.item.model, 16);
613
+ data.set([frame.light.toLight.x, frame.light.toLight.y, frame.light.toLight.z, 0], 32);
614
+ data.set([frame.light.intensity, frame.light.ambient, draw.opacity, 0], 36);
615
+ this.device.queue.writeBuffer(this.uniformBuffer, i * UNIFORM_STRIDE, data);
616
+ });
617
+ const encoder = this.device.createCommandEncoder();
618
+ const pass = encoder.beginRenderPass({
619
+ colorAttachments: [
620
+ {
621
+ view: this.context.getCurrentTexture().createView(),
622
+ clearValue: this.clearValue,
623
+ loadOp: "clear",
624
+ storeOp: "store"
625
+ }
626
+ ],
627
+ depthStencilAttachment: {
628
+ view: this.depthTexture.createView(),
629
+ depthClearValue: 1,
630
+ depthLoadOp: "clear",
631
+ depthStoreOp: "store"
632
+ }
633
+ });
634
+ draws.forEach((draw, i) => {
635
+ const mesh = this.buffers(draw.item.mesh);
636
+ pass.setPipeline(draw.pipeline);
637
+ pass.setBindGroup(0, bindGroup, [i * UNIFORM_STRIDE]);
638
+ pass.setVertexBuffer(0, mesh.position);
639
+ pass.setVertexBuffer(1, mesh.normal);
640
+ pass.setVertexBuffer(2, mesh.color);
641
+ pass.draw(mesh.count);
642
+ });
643
+ pass.end();
644
+ this.device.queue.submit([encoder.finish()]);
645
+ }
646
+ destroy() {
647
+ this.destroyed = true;
648
+ for (const mesh of this.cache.values()) {
649
+ mesh.position.destroy?.();
650
+ mesh.normal.destroy?.();
651
+ mesh.color.destroy?.();
652
+ }
653
+ this.cache.clear();
654
+ this.uniformBuffer?.destroy?.();
655
+ this.depthTexture?.destroy?.();
656
+ this.device?.destroy?.();
657
+ this.device = void 0;
658
+ this.context = void 0;
659
+ this.pipeline = void 0;
660
+ this.transparentBackPipeline = void 0;
661
+ this.transparentFrontPipeline = void 0;
662
+ this.uniformBuffer = void 0;
663
+ this.depthTexture = void 0;
664
+ this.canvas = void 0;
665
+ }
666
+ };
667
+ }
668
+ });
669
+
670
+ // src/engines/little-3d-engine/renderers/canvas2d.ts
671
+ var canvas2d_exports = {};
672
+ __export(canvas2d_exports, {
673
+ Canvas2DRenderer: () => Canvas2DRenderer
674
+ });
675
+ var Canvas2DRenderer;
676
+ var init_canvas2d = __esm({
677
+ "src/engines/little-3d-engine/renderers/canvas2d.ts"() {
678
+ "use strict";
679
+ init_light();
680
+ init_math();
681
+ init_renderer();
682
+ Canvas2DRenderer = class {
683
+ constructor(options = {}) {
684
+ this.options = options;
685
+ this.dpr = 1;
686
+ }
687
+ init(canvas) {
688
+ this.ctx = canvas.getContext("2d") ?? void 0;
689
+ }
690
+ resize(_cssWidth, _cssHeight, dpr) {
691
+ this.dpr = dpr;
692
+ this.ctx?.setTransform(dpr, 0, 0, dpr, 0, 0);
693
+ }
694
+ render(frame) {
695
+ const ctx = this.ctx;
696
+ if (!ctx) return;
697
+ if (this.options.background) {
698
+ ctx.fillStyle = this.options.background;
699
+ ctx.fillRect(0, 0, frame.width, frame.height);
700
+ } else {
701
+ ctx.clearRect(0, 0, frame.width, frame.height);
702
+ }
703
+ const polygons = [];
704
+ for (const item of frame.items) {
705
+ const world = item.mesh.vertices.map((v) => transformAffine(item.model, v));
706
+ const twoSidedOpacity = item.transparency?.mode === "two-sided" ? resolveTwoSidedOpacity(item.transparency) : void 0;
707
+ for (const face of item.mesh.faces) {
708
+ const a = world[face.indices[0]];
709
+ const b = world[face.indices[1]];
710
+ const c = world[face.indices[2]];
711
+ const normal = normalize(cross(subtract(b, a), subtract(c, a)));
712
+ const frontFacing = dot(normal, subtract(frame.eye, a)) > 0;
713
+ const transparency = item.transparency;
714
+ if (!frontFacing && transparency?.mode !== "two-sided") continue;
715
+ let faceOpacity = 1;
716
+ if (transparency?.mode === "one-sided") {
717
+ faceOpacity = opacity(transparency.opacity, DEFAULT_ONE_SIDED_OPACITY);
718
+ } else if (twoSidedOpacity) {
719
+ faceOpacity = frontFacing ? twoSidedOpacity.front : twoSidedOpacity.back;
720
+ }
721
+ const points = face.indices.map((i) => {
722
+ const ndc = transformPoint(frame.viewProjection, world[i]);
723
+ return {
724
+ x: (ndc.x * 0.5 + 0.5) * frame.width,
725
+ y: (1 - (ndc.y * 0.5 + 0.5)) * frame.height
726
+ };
727
+ });
728
+ let depth = 0;
729
+ for (const i of face.indices) {
730
+ const d = subtract(world[i], frame.eye);
731
+ depth += dot(d, d);
732
+ }
733
+ depth /= face.indices.length;
734
+ polygons.push({
735
+ points,
736
+ color: shadeColor(normal, face.color, frame.light),
737
+ depth,
738
+ opacity: faceOpacity
739
+ });
740
+ }
741
+ }
742
+ polygons.sort((p, q) => q.depth - p.depth);
743
+ for (const poly of polygons) {
744
+ if (poly.points.length < 3) continue;
745
+ ctx.beginPath();
746
+ ctx.moveTo(poly.points[0].x, poly.points[0].y);
747
+ for (let i = 1; i < poly.points.length; i++) {
748
+ ctx.lineTo(poly.points[i].x, poly.points[i].y);
749
+ }
750
+ ctx.closePath();
751
+ ctx.fillStyle = poly.color;
752
+ ctx.strokeStyle = poly.color;
753
+ ctx.lineWidth = 1;
754
+ ctx.globalAlpha = poly.opacity;
755
+ ctx.fill();
756
+ ctx.stroke();
757
+ }
758
+ ctx.globalAlpha = 1;
759
+ }
760
+ destroy() {
761
+ this.ctx = void 0;
762
+ }
763
+ };
764
+ }
765
+ });
766
+
767
+ // src/engines/little-3d-engine/renderer.ts
768
+ function opacity(value, fallback) {
769
+ return Math.max(0, Math.min(1, value ?? fallback));
770
+ }
771
+ function resolveTwoSidedOpacity(transparency) {
772
+ const front = opacity(
773
+ transparency.frontOpacity ?? transparency.opacity,
774
+ DEFAULT_FRONT_OPACITY
775
+ );
776
+ const backFallback = transparency.opacity === void 0 ? DEFAULT_BACK_OPACITY : front * (2 / 3);
777
+ return {
778
+ front,
779
+ back: opacity(transparency.backOpacity, backFallback)
780
+ };
781
+ }
782
+ function orderRenderItems(items, eye) {
783
+ const opaque = [];
784
+ const transparent = [];
785
+ for (const item of items) {
786
+ (item.transparency ? transparent : opaque).push(item);
787
+ }
788
+ transparent.sort((a, b) => {
789
+ const ax = a.model[12] - eye.x;
790
+ const ay = a.model[13] - eye.y;
791
+ const az = a.model[14] - eye.z;
792
+ const bx = b.model[12] - eye.x;
793
+ const by = b.model[13] - eye.y;
794
+ const bz = b.model[14] - eye.z;
795
+ return bx * bx + by * by + bz * bz - (ax * ax + ay * ay + az * az);
796
+ });
797
+ return opaque.concat(transparent);
798
+ }
799
+ async function createRenderer(backend, options = {}) {
800
+ if (typeof backend === "function") return backend(options);
801
+ switch (backend) {
802
+ case "webgl":
803
+ return new (await Promise.resolve().then(() => (init_webgl(), webgl_exports))).WebGLRenderer(options);
804
+ case "webgpu":
805
+ return new (await Promise.resolve().then(() => (init_webgpu(), webgpu_exports))).WebGPURenderer(options);
806
+ case "canvas2d":
807
+ default:
808
+ return new (await Promise.resolve().then(() => (init_canvas2d(), canvas2d_exports))).Canvas2DRenderer(options);
809
+ }
810
+ }
811
+ var DEFAULT_ONE_SIDED_OPACITY, DEFAULT_BACK_OPACITY, DEFAULT_FRONT_OPACITY;
812
+ var init_renderer = __esm({
813
+ "src/engines/little-3d-engine/renderer.ts"() {
814
+ "use strict";
815
+ DEFAULT_ONE_SIDED_OPACITY = 0.35;
816
+ DEFAULT_BACK_OPACITY = 0.84;
817
+ DEFAULT_FRONT_OPACITY = 0.56;
818
+ }
819
+ });
820
+
821
+ // src/animations/object-motion.ts
822
+ var object_motion_exports = {};
823
+ __export(object_motion_exports, {
824
+ ObjectMotionAnimation: () => ObjectMotionAnimation,
825
+ centerAndScaleMesh: () => centerAndScaleMesh
826
+ });
827
+ module.exports = __toCommonJS(object_motion_exports);
828
+
829
+ // src/animation-label.ts
830
+ var LABEL_STYLE = [
831
+ "position:absolute",
832
+ "inset:0",
833
+ "display:flex",
834
+ "align-items:center",
835
+ "justify-content:center",
836
+ "pointer-events:none",
837
+ "font:700 1.6rem/1 system-ui,sans-serif",
838
+ "letter-spacing:0.02em",
839
+ "color:rgba(255,255,255,0.9)",
840
+ "text-shadow:0 1px 10px rgba(0,0,0,0.6)",
841
+ "z-index:1"
842
+ ].join(";");
843
+ function animationLabelOpacity(now, enterAt, introDurationMs, exitAt, outroDurationMs) {
844
+ if (enterAt === Infinity) return 0;
845
+ const intro = introDurationMs <= 0 ? 1 : Math.max(0, Math.min(1, (now - enterAt) / introDurationMs));
846
+ const outro = exitAt === Infinity ? 1 : outroDurationMs <= 0 ? 0 : Math.max(0, Math.min(1, 1 - (now - exitAt) / outroDurationMs));
847
+ return Math.min(intro, outro);
848
+ }
849
+ function mountAnimationLabel(target, content) {
850
+ var _a;
851
+ const container = document.createElement("div");
852
+ container.style.cssText = LABEL_STYLE;
853
+ container.setAttribute("role", "status");
854
+ if (typeof content === "string") container.textContent = content;
855
+ else if (content) {
856
+ (_a = content.style).pointerEvents || (_a.pointerEvents = "auto");
857
+ container.appendChild(content);
858
+ }
859
+ target.appendChild(container);
860
+ return {
861
+ container,
862
+ setText(value) {
863
+ if (typeof content !== "object") container.textContent = value;
864
+ },
865
+ setOpacity(value) {
866
+ container.style.opacity = String(value);
867
+ }
868
+ };
869
+ }
870
+
871
+ // src/engines/little-3d-engine/core/camera.ts
872
+ init_math();
873
+ var DEFAULTS = {
874
+ position: { x: 0, y: 0, z: 4 },
875
+ fov: 55 * Math.PI / 180,
876
+ near: 0.1,
877
+ far: 100
878
+ };
879
+ var Camera = class {
880
+ constructor(options) {
881
+ this.options = { ...DEFAULTS, ...options };
882
+ }
883
+ /** Transform a world-space point into view (camera) space. */
884
+ toView(p) {
885
+ const { position } = this.options;
886
+ return transformAffine(translation(-position.x, -position.y, -position.z), p);
887
+ }
888
+ /** Combined view-projection matrix for the given viewport aspect ratio. */
889
+ viewProjection(aspect) {
890
+ const { position, fov, near, far } = this.options;
891
+ const view = translation(-position.x, -position.y, -position.z);
892
+ const projection = perspective(fov, aspect, near, far);
893
+ return multiply(projection, view);
894
+ }
895
+ /** Convert a normalized device coordinate (-1..1) to a pixel position. */
896
+ toScreen(ndc, width, height) {
897
+ return {
898
+ x: (ndc.x * 0.5 + 0.5) * width,
899
+ y: (1 - (ndc.y * 0.5 + 0.5)) * height
900
+ };
901
+ }
902
+ };
903
+
904
+ // src/engines/little-3d-engine/little-3d-engine.ts
905
+ init_light();
906
+ init_math();
907
+
908
+ // src/engines/little-3d-engine/core/mesh.ts
909
+ function transform(init) {
910
+ return {
911
+ position: init?.position ?? { x: 0, y: 0, z: 0 },
912
+ rotation: init?.rotation ?? { x: 0, y: 0, z: 0 },
913
+ scale: init?.scale ?? 1
914
+ };
915
+ }
916
+
917
+ // src/engines/little-3d-engine/little-3d-engine.ts
918
+ init_renderer();
919
+ init_light();
920
+
921
+ // src/engines/little-3d-engine/shapes/primitives/spheres/icosphere.ts
922
+ init_geometry();
923
+ var T = (1 + Math.sqrt(5)) / 2;
924
+ var SEED_VERTICES = [
925
+ { x: -1, y: T, z: 0 },
926
+ { x: 1, y: T, z: 0 },
927
+ { x: -1, y: -T, z: 0 },
928
+ { x: 1, y: -T, z: 0 },
929
+ { x: 0, y: -1, z: T },
930
+ { x: 0, y: 1, z: T },
931
+ { x: 0, y: -1, z: -T },
932
+ { x: 0, y: 1, z: -T },
933
+ { x: T, y: 0, z: -1 },
934
+ { x: T, y: 0, z: 1 },
935
+ { x: -T, y: 0, z: -1 },
936
+ { x: -T, y: 0, z: 1 }
937
+ ];
938
+
939
+ // src/engines/little-3d-engine/shapes/primitives/spheres/octa-sphere.ts
940
+ init_geometry();
941
+
942
+ // src/engines/little-3d-engine/little-3d-engine.ts
943
+ init_geometry();
944
+ init_renderer();
945
+ init_math();
946
+ function modelMatrix(t) {
947
+ const rotation = multiply(
948
+ rotationZ(t.rotation.z),
949
+ multiply(rotationY(t.rotation.y), rotationX(t.rotation.x))
950
+ );
951
+ return multiply(
952
+ translation(t.position.x, t.position.y, t.position.z),
953
+ multiply(rotation, scaleMatrix(t.scale))
954
+ );
955
+ }
956
+ var Little3dEngine = class {
957
+ constructor(options = {}) {
958
+ this.scene = [];
959
+ this.cssWidth = 0;
960
+ this.cssHeight = 0;
961
+ this.ready = false;
962
+ this.generation = 0;
963
+ this.rafId = 0;
964
+ this.running = false;
965
+ this.camera = new Camera(options.camera);
966
+ this.light = new Light(options.light);
967
+ this.backend = options.backend ?? "canvas2d";
968
+ this.background = options.background;
969
+ }
970
+ /**
971
+ * Create the canvas inside `target`, load the selected backend, and start
972
+ * tracking size. Resolves once the renderer is ready; rejects if the backend
973
+ * is unavailable. Drawing is a no-op until it resolves.
974
+ */
975
+ async mount(target) {
976
+ const canvas = document.createElement("canvas");
977
+ canvas.style.display = "block";
978
+ canvas.style.width = "100%";
979
+ canvas.style.height = "100%";
980
+ target.appendChild(canvas);
981
+ this.canvas = canvas;
982
+ this.observer = new ResizeObserver(() => this.resize());
983
+ this.observer.observe(canvas);
984
+ this.resize();
985
+ const generation = this.generation;
986
+ const dropCanvas = () => {
987
+ if (this.canvas !== canvas) return;
988
+ this.observer?.disconnect();
989
+ this.observer = void 0;
990
+ canvas.remove();
991
+ this.canvas = void 0;
992
+ };
993
+ try {
994
+ const renderer = await createRenderer(this.backend, { background: this.background });
995
+ if (generation !== this.generation) {
996
+ renderer.destroy();
997
+ dropCanvas();
998
+ return;
999
+ }
1000
+ await renderer.init(canvas);
1001
+ if (generation !== this.generation) {
1002
+ renderer.destroy();
1003
+ dropCanvas();
1004
+ return;
1005
+ }
1006
+ this.renderer = renderer;
1007
+ this.resize();
1008
+ this.ready = true;
1009
+ } catch (error) {
1010
+ dropCanvas();
1011
+ throw error;
1012
+ }
1013
+ }
1014
+ /** Add a mesh to the scene and return a handle for animating it. */
1015
+ add(mesh, init) {
1016
+ const entry = {
1017
+ mesh,
1018
+ transform: transform(init),
1019
+ transparency: init?.transparency,
1020
+ remove: () => {
1021
+ const i = this.scene.indexOf(entry);
1022
+ if (i >= 0) this.scene.splice(i, 1);
1023
+ }
1024
+ };
1025
+ this.scene.push(entry);
1026
+ return entry;
1027
+ }
1028
+ resize() {
1029
+ const canvas = this.canvas;
1030
+ if (!canvas) return;
1031
+ const dpr = window.devicePixelRatio || 1;
1032
+ this.cssWidth = canvas.clientWidth || canvas.parentElement?.clientWidth || 0;
1033
+ this.cssHeight = canvas.clientHeight || canvas.parentElement?.clientHeight || 0;
1034
+ canvas.width = Math.max(1, Math.round(this.cssWidth * dpr));
1035
+ canvas.height = Math.max(1, Math.round(this.cssHeight * dpr));
1036
+ this.renderer?.resize(this.cssWidth, this.cssHeight, dpr);
1037
+ }
1038
+ /** Draw a single frame from the current scene state. */
1039
+ render() {
1040
+ if (!this.ready || !this.renderer) return;
1041
+ const width = this.cssWidth;
1042
+ const height = this.cssHeight;
1043
+ if (width === 0 || height === 0) return;
1044
+ const items = this.scene.map((entry) => ({
1045
+ mesh: entry.mesh,
1046
+ model: modelMatrix(entry.transform),
1047
+ transparency: entry.transparency
1048
+ }));
1049
+ const eye = this.camera.options.position;
1050
+ this.renderer.render({
1051
+ items: orderRenderItems(items, eye),
1052
+ viewProjection: this.camera.viewProjection(width / height),
1053
+ eye,
1054
+ light: this.light.params,
1055
+ width,
1056
+ height
1057
+ });
1058
+ }
1059
+ /** Start an internal animation loop that calls {@link render} each frame. */
1060
+ start() {
1061
+ if (this.running) return;
1062
+ this.running = true;
1063
+ const loop = () => {
1064
+ if (!this.running) return;
1065
+ this.render();
1066
+ this.rafId = requestAnimationFrame(loop);
1067
+ };
1068
+ this.rafId = requestAnimationFrame(loop);
1069
+ }
1070
+ /** Stop the internal animation loop started by {@link start}. */
1071
+ stop() {
1072
+ this.running = false;
1073
+ if (this.rafId) cancelAnimationFrame(this.rafId);
1074
+ this.rafId = 0;
1075
+ }
1076
+ /** Stop animating, release the renderer, and remove the canvas. */
1077
+ destroy() {
1078
+ this.generation++;
1079
+ this.ready = false;
1080
+ this.stop();
1081
+ this.observer?.disconnect();
1082
+ this.observer = void 0;
1083
+ this.renderer?.destroy();
1084
+ this.renderer = void 0;
1085
+ this.canvas?.remove();
1086
+ this.canvas = void 0;
1087
+ }
1088
+ };
1089
+
1090
+ // src/animations/object-motion.ts
1091
+ init_math();
1092
+
1093
+ // src/motion/transitions.ts
1094
+ var DEFAULT_DISTANCE = 3.5;
1095
+ function add(a, b) {
1096
+ return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };
1097
+ }
1098
+ function scaleVector(v, factor) {
1099
+ return { x: v.x * factor, y: v.y * factor, z: v.z * factor };
1100
+ }
1101
+ function vectorLength(v) {
1102
+ return Math.hypot(v.x, v.y, v.z);
1103
+ }
1104
+ function normalizeVector(v) {
1105
+ const length = vectorLength(v);
1106
+ if (length < 1e-6) return { x: 1, y: 0, z: 0 };
1107
+ return scaleVector(v, 1 / length);
1108
+ }
1109
+ function resolveDirection(input, fallback) {
1110
+ return normalizeVector(fallback ?? input.direction ?? input.velocity ?? { x: 1, y: 0, z: 0 });
1111
+ }
1112
+ function joinVelocity(input, options, durationMs) {
1113
+ const inputSpeed = input.velocity ? vectorLength(input.velocity) : 0;
1114
+ if (input.velocity && inputSpeed > 1e-6 && !options.direction) {
1115
+ return input.velocity;
1116
+ }
1117
+ const distance = options.distance ?? DEFAULT_DISTANCE;
1118
+ return scaleVector(resolveDirection(input, options.direction), distance / durationMs);
1119
+ }
1120
+ function enterFromObjectDirection(options = {}) {
1121
+ return (input) => {
1122
+ const durationMs = Math.max(1, input.durationMs);
1123
+ const velocity = joinVelocity(input, options, durationMs);
1124
+ const remaining = durationMs - input.elapsedMs;
1125
+ return { position: add(input.position, scaleVector(velocity, -remaining)) };
1126
+ };
1127
+ }
1128
+ function leaveInObjectDirection(options = {}) {
1129
+ return (input) => {
1130
+ const durationMs = Math.max(1, input.durationMs);
1131
+ const velocity = joinVelocity(input, options, durationMs);
1132
+ return { position: add(input.position, scaleVector(velocity, input.elapsedMs)) };
1133
+ };
1134
+ }
1135
+
1136
+ // src/animations/object-motion.ts
1137
+ var WORLD_UP = { x: 0, y: 1, z: 0 };
1138
+ var DEFAULT_INTRO_MS = 2100;
1139
+ var DEFAULT_OUTRO_MS = 2100;
1140
+ var BANK_GAIN = 26;
1141
+ var BANK_LIMIT = 0.7;
1142
+ var BANK_SMOOTH = 0.12;
1143
+ var SAMPLE_MS = 8;
1144
+ var FACE_FORWARD = {
1145
+ "+x": (v) => v,
1146
+ "-x": (v) => ({ x: -v.x, y: v.y, z: -v.z }),
1147
+ "+z": (v) => ({ x: v.z, y: v.y, z: -v.x }),
1148
+ "-z": (v) => ({ x: -v.z, y: v.y, z: v.x }),
1149
+ "+y": (v) => ({ x: v.y, y: -v.x, z: v.z }),
1150
+ "-y": (v) => ({ x: -v.y, y: v.x, z: v.z })
1151
+ };
1152
+ function add2(a, b) {
1153
+ return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };
1154
+ }
1155
+ function resolveMesh(mesh) {
1156
+ return typeof mesh === "function" ? mesh() : mesh;
1157
+ }
1158
+ function applyColor(mesh, color) {
1159
+ if (color === void 0) return mesh;
1160
+ return { vertices: mesh.vertices, faces: mesh.faces.map((face) => ({ ...face, color })) };
1161
+ }
1162
+ function faceForward(mesh, facing) {
1163
+ if (facing === "+x") return mesh;
1164
+ const turn = FACE_FORWARD[facing];
1165
+ return { vertices: mesh.vertices.map(turn), faces: mesh.faces };
1166
+ }
1167
+ function centerAndScaleMesh(mesh, targetSize) {
1168
+ let minX = Infinity;
1169
+ let minY = Infinity;
1170
+ let minZ = Infinity;
1171
+ let maxX = -Infinity;
1172
+ let maxY = -Infinity;
1173
+ let maxZ = -Infinity;
1174
+ for (const vertex of mesh.vertices) {
1175
+ minX = Math.min(minX, vertex.x);
1176
+ minY = Math.min(minY, vertex.y);
1177
+ minZ = Math.min(minZ, vertex.z);
1178
+ maxX = Math.max(maxX, vertex.x);
1179
+ maxY = Math.max(maxY, vertex.y);
1180
+ maxZ = Math.max(maxZ, vertex.z);
1181
+ }
1182
+ const centerX = (minX + maxX) / 2;
1183
+ const centerY = (minY + maxY) / 2;
1184
+ const centerZ = (minZ + maxZ) / 2;
1185
+ const extent = Math.max(maxX - minX, maxY - minY, maxZ - minZ) || 1;
1186
+ const factor = targetSize / extent;
1187
+ return {
1188
+ vertices: mesh.vertices.map((vertex) => ({
1189
+ x: (vertex.x - centerX) * factor,
1190
+ y: (vertex.y - centerY) * factor,
1191
+ z: (vertex.z - centerZ) * factor
1192
+ })),
1193
+ faces: mesh.faces
1194
+ };
1195
+ }
1196
+ function orientationFor(forward, bank) {
1197
+ const fwd = normalize(forward);
1198
+ let right = cross(fwd, WORLD_UP);
1199
+ if (Math.hypot(right.x, right.y, right.z) < 1e-4) right = { x: 0, y: 0, z: 1 };
1200
+ right = normalize(right);
1201
+ const levelUp = cross(right, fwd);
1202
+ const up = add2(scale(levelUp, Math.cos(bank)), scale(right, Math.sin(bank)));
1203
+ const w = normalize(cross(fwd, up));
1204
+ return {
1205
+ x: Math.atan2(cross(w, fwd).z, w.z),
1206
+ y: Math.asin(Math.max(-1, Math.min(1, -fwd.z))),
1207
+ z: Math.atan2(fwd.y, fwd.x)
1208
+ };
1209
+ }
1210
+ function rotationMatrix(x, y, z) {
1211
+ return multiply(rotationZ(z), multiply(rotationY(y), rotationX(x)));
1212
+ }
1213
+ function eulerFromRotationMatrix(matrix) {
1214
+ const sy = Math.hypot(matrix[0], matrix[1]);
1215
+ if (sy > 1e-6) {
1216
+ return {
1217
+ x: Math.atan2(matrix[9], matrix[10]),
1218
+ y: Math.asin(Math.max(-1, Math.min(1, -matrix[8]))),
1219
+ z: Math.atan2(matrix[4], matrix[0])
1220
+ };
1221
+ }
1222
+ return {
1223
+ x: Math.atan2(-matrix[6], matrix[5]),
1224
+ y: Math.asin(Math.max(-1, Math.min(1, -matrix[8]))),
1225
+ z: 0
1226
+ };
1227
+ }
1228
+ function combineLocalRotation(path, extra) {
1229
+ return eulerFromRotationMatrix(
1230
+ multiply(rotationMatrix(path.x, path.y, path.z), rotationMatrix(extra.x, extra.y, extra.z))
1231
+ );
1232
+ }
1233
+ function clamp012(value) {
1234
+ return Math.max(0, Math.min(1, value));
1235
+ }
1236
+ function motionVectorAt(motion, t) {
1237
+ return scale(subtract(motion.positionAt(t + 1), motion.positionAt(t - 1)), 0.5);
1238
+ }
1239
+ function resolveDirection2(velocity, fallback) {
1240
+ return Math.hypot(velocity.x, velocity.y, velocity.z) > 1e-6 ? normalize(velocity) : fallback;
1241
+ }
1242
+ function resolveTransition(config, fallback, durationMs) {
1243
+ if (!config) return { transition: fallback, durationMs };
1244
+ if (typeof config === "function") return { transition: config, durationMs };
1245
+ return { transition: config.transition, durationMs: Math.max(0, config.durationMs ?? durationMs) };
1246
+ }
1247
+ var ObjectMotionAnimation = class {
1248
+ constructor(options) {
1249
+ this.handles = [];
1250
+ this.banks = [];
1251
+ this.headings = [];
1252
+ this.started = false;
1253
+ this.finished = false;
1254
+ this.introStart = 0;
1255
+ this.outroStart = Infinity;
1256
+ this.outroPosition = { x: 0, y: 0, z: 0 };
1257
+ this.outroVelocity = { x: 0, y: 0, z: 0 };
1258
+ this.outroDirection = { x: 1, y: 0, z: 0 };
1259
+ const centered = centerAndScaleMesh(resolveMesh(options.mesh), options.size ?? 1);
1260
+ const facing = faceForward(centered, options.facing ?? "+x");
1261
+ this.mesh = applyColor(facing, options.color);
1262
+ this.motion = options.motion;
1263
+ this.backend = options.backend;
1264
+ this.transparency = options.transparency;
1265
+ this.labelContent = options.label;
1266
+ this.fadeLabel = options.fadeLabel ?? true;
1267
+ this.tailCount = Math.max(0, Math.floor(options.tail?.count ?? 0));
1268
+ this.tailGap = Math.max(0, options.tail?.gapMs ?? 0);
1269
+ this.intro = resolveTransition(options.intro, enterFromObjectDirection(), DEFAULT_INTRO_MS);
1270
+ this.outro = resolveTransition(options.outro, leaveInObjectDirection(), DEFAULT_OUTRO_MS);
1271
+ const rotation = options.rotation;
1272
+ this.rotationOffset = { x: rotation?.x ?? 0, y: rotation?.y ?? 0, z: rotation?.z ?? 0 };
1273
+ this.rotationSpin = {
1274
+ x: rotation?.spinX ?? 0,
1275
+ y: rotation?.spinY ?? 0,
1276
+ z: rotation?.spinZ ?? 0
1277
+ };
1278
+ this.hasExtraRotation = this.rotationOffset.x !== 0 || this.rotationOffset.y !== 0 || this.rotationOffset.z !== 0 || this.rotationSpin.x !== 0 || this.rotationSpin.y !== 0 || this.rotationSpin.z !== 0;
1279
+ }
1280
+ mount(target) {
1281
+ if (!target.style.position) target.style.position = "relative";
1282
+ const engine = new Little3dEngine({
1283
+ backend: this.backend,
1284
+ camera: { position: { x: 0, y: 0, z: 3 } }
1285
+ });
1286
+ for (let i = 0; i <= this.tailCount; i++) {
1287
+ this.handles.push(engine.add(this.mesh, { transparency: this.transparency }));
1288
+ this.banks.push(0);
1289
+ this.headings.push({ x: 1, y: 0, z: 0 });
1290
+ }
1291
+ this.engine = engine;
1292
+ engine.mount(target).catch((error) => {
1293
+ target.textContent = error instanceof Error ? error.message : String(error);
1294
+ });
1295
+ this.label = mountAnimationLabel(target, this.labelContent);
1296
+ if (this.fadeLabel) this.label.setOpacity(0);
1297
+ }
1298
+ enter(now) {
1299
+ if (this.started) return;
1300
+ this.started = true;
1301
+ this.introStart = now;
1302
+ }
1303
+ exit(now) {
1304
+ if (!this.started || this.outroStart !== Infinity) return;
1305
+ this.outroPosition = this.motion.positionAt(now);
1306
+ this.outroVelocity = motionVectorAt(this.motion, now);
1307
+ this.outroDirection = resolveDirection2(this.outroVelocity, this.headings[0]);
1308
+ this.outroStart = now;
1309
+ }
1310
+ isFinished() {
1311
+ return this.finished;
1312
+ }
1313
+ /** Milliseconds the fly-out takes; used to align a following particle trail's outro. */
1314
+ get outroDurationMs() {
1315
+ return this.outro.durationMs;
1316
+ }
1317
+ /**
1318
+ * A {@link MotionController} that follows the object's *actual* position, including
1319
+ * the intro fly-in and outro fly-out (it falls back to the raw motion path before
1320
+ * {@link enter} and once idle). Feed it to a particle layer's `emitter` so the
1321
+ * particles trail the object through its transitions instead of the bare path.
1322
+ */
1323
+ trailEmitter() {
1324
+ return { positionAt: (t) => this.sampleAt(t)?.position ?? this.motion.positionAt(t) };
1325
+ }
1326
+ render(now, frame) {
1327
+ if (!this.engine || !this.label) return;
1328
+ if (this.outroStart !== Infinity && now >= this.outroStart + this.outro.durationMs + this.tailCount * this.tailGap) {
1329
+ this.finished = true;
1330
+ }
1331
+ for (let k = 0; k < this.handles.length; k++) {
1332
+ const transform2 = this.handles[k].transform;
1333
+ const t = now - k * this.tailGap;
1334
+ const sample = this.sampleAt(t);
1335
+ if (!sample) {
1336
+ transform2.scale = 0;
1337
+ continue;
1338
+ }
1339
+ transform2.scale = sample.size;
1340
+ let euler = sample.orientation;
1341
+ if (!euler) {
1342
+ const heading = subtract(this.positionAt(t + SAMPLE_MS) ?? sample.position, sample.position);
1343
+ if (Math.hypot(heading.x, heading.y, heading.z) > 1e-5) {
1344
+ this.headings[k] = normalize(heading);
1345
+ }
1346
+ const ahead = this.aheadAt(t) ?? this.headings[k];
1347
+ const targetBank = Math.max(
1348
+ -BANK_LIMIT,
1349
+ Math.min(BANK_LIMIT, cross(this.headings[k], ahead).y * BANK_GAIN)
1350
+ );
1351
+ this.banks[k] += (targetBank - this.banks[k]) * BANK_SMOOTH;
1352
+ euler = orientationFor(this.headings[k], this.banks[k]);
1353
+ }
1354
+ if (this.hasExtraRotation) {
1355
+ euler = combineLocalRotation(euler, {
1356
+ x: this.rotationOffset.x + this.rotationSpin.x * t,
1357
+ y: this.rotationOffset.y + this.rotationSpin.y * t,
1358
+ z: this.rotationOffset.z + this.rotationSpin.z * t
1359
+ });
1360
+ }
1361
+ transform2.position.x = sample.position.x;
1362
+ transform2.position.y = sample.position.y;
1363
+ transform2.position.z = sample.position.z;
1364
+ transform2.rotation.x = euler.x;
1365
+ transform2.rotation.y = euler.y;
1366
+ transform2.rotation.z = euler.z;
1367
+ }
1368
+ this.label.setText(frame.indeterminate ? typeof this.labelContent === "string" ? this.labelContent : "" : `${Math.round(frame.progress * 100)}%`);
1369
+ if (this.fadeLabel) {
1370
+ this.label.setOpacity(animationLabelOpacity(
1371
+ now,
1372
+ this.started ? this.introStart : Infinity,
1373
+ this.intro.durationMs,
1374
+ this.outroStart,
1375
+ this.outro.durationMs
1376
+ ));
1377
+ }
1378
+ this.engine.render();
1379
+ }
1380
+ destroy() {
1381
+ this.label?.container.remove();
1382
+ this.label = void 0;
1383
+ this.engine?.destroy();
1384
+ this.engine = void 0;
1385
+ this.handles.length = 0;
1386
+ }
1387
+ aheadAt(t) {
1388
+ const next = this.positionAt(t + SAMPLE_MS);
1389
+ const afterNext = this.positionAt(t + 2 * SAMPLE_MS);
1390
+ if (!next || !afterNext) return void 0;
1391
+ const ahead = subtract(afterNext, next);
1392
+ if (Math.hypot(ahead.x, ahead.y, ahead.z) <= 1e-5) return void 0;
1393
+ return normalize(ahead);
1394
+ }
1395
+ positionAt(t) {
1396
+ return this.sampleAt(t)?.position;
1397
+ }
1398
+ sampleAt(t) {
1399
+ if (!this.started || t < this.introStart) return void 0;
1400
+ if (t < this.introStart + this.intro.durationMs) {
1401
+ return this.transitionSample("intro", t, this.intro, this.introStart);
1402
+ }
1403
+ if (this.outroStart !== Infinity) {
1404
+ if (t > this.outroStart + this.outro.durationMs) return void 0;
1405
+ if (t >= this.outroStart) return this.transitionSample("outro", t, this.outro, this.outroStart);
1406
+ }
1407
+ return { position: this.motion.positionAt(t), size: 1 };
1408
+ }
1409
+ transitionSample(phase, t, transition, start) {
1410
+ const elapsedMs = Math.max(0, t - start);
1411
+ const delta = transition.durationMs === 0 ? 1 : clamp012(elapsedMs / transition.durationMs);
1412
+ const input = this.transitionInput(phase, delta, elapsedMs, transition.durationMs, start);
1413
+ const output = transition.transition(input);
1414
+ return this.applyTransitionOutput(input, output, phase, t);
1415
+ }
1416
+ transitionInput(phase, delta, elapsedMs, durationMs, start) {
1417
+ if (phase === "intro") {
1418
+ const handoff = start + durationMs;
1419
+ const velocity = motionVectorAt(this.motion, handoff);
1420
+ return {
1421
+ delta,
1422
+ position: this.motion.positionAt(handoff),
1423
+ direction: resolveDirection2(velocity, { x: 1, y: 0, z: 0 }),
1424
+ velocity,
1425
+ size: 1,
1426
+ durationMs,
1427
+ elapsedMs,
1428
+ phase
1429
+ };
1430
+ }
1431
+ return {
1432
+ delta,
1433
+ position: this.outroPosition,
1434
+ direction: this.outroDirection,
1435
+ velocity: this.outroVelocity,
1436
+ size: 1,
1437
+ durationMs,
1438
+ elapsedMs,
1439
+ phase
1440
+ };
1441
+ }
1442
+ applyTransitionOutput(input, output, phase, t) {
1443
+ return {
1444
+ position: output.position ?? (phase === "intro" ? this.motion.positionAt(t) : input.position),
1445
+ size: output.size ?? input.size ?? 1,
1446
+ orientation: output.orientation
1447
+ };
1448
+ }
1449
+ };