@ikijs/mcp 0.23.2 → 0.25.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.
@@ -0,0 +1,1266 @@
1
+ "use strict";
2
+ (() => {
3
+ // ../engine/src/math.ts
4
+ function clamp(value, min, max) {
5
+ return Math.max(min, Math.min(max, value));
6
+ }
7
+ function lerp(a, b, t) {
8
+ return a + (b - a) * t;
9
+ }
10
+
11
+ // ../engine/src/parameter-store.ts
12
+ var ParameterStore = class {
13
+ params = /* @__PURE__ */ new Map();
14
+ values = /* @__PURE__ */ new Map();
15
+ /**
16
+ * Resting value per id: the declared default clamped into range, resolved
17
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
18
+ * reported once rather than on every reset.
19
+ */
20
+ defaults = /* @__PURE__ */ new Map();
21
+ constructor(parameters) {
22
+ for (const param of parameters) {
23
+ this.params.set(param.id, param);
24
+ if (!Number.isFinite(param.default)) {
25
+ console.error(
26
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
27
+ );
28
+ }
29
+ const base = Number.isFinite(param.default) ? param.default : 0;
30
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
31
+ }
32
+ for (const [id, value] of this.defaults) this.values.set(id, value);
33
+ }
34
+ /**
35
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
36
+ * are non-finite values: this is the boundary a host drives with live signals,
37
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
38
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
39
+ * reads the parameter. A dropped write holds the last good pose.
40
+ */
41
+ set(id, value) {
42
+ const param = this.params.get(id);
43
+ if (!param) return;
44
+ if (!Number.isFinite(value)) return;
45
+ this.values.set(id, clamp(value, param.min, param.max));
46
+ }
47
+ /** Current value, or 0 if the id is unknown. */
48
+ get(id) {
49
+ return this.values.get(id) ?? 0;
50
+ }
51
+ /** Position of a parameter within its range, 0..1. */
52
+ normalized(id) {
53
+ const param = this.params.get(id);
54
+ if (!param || param.max === param.min) return 0;
55
+ return (this.get(id) - param.min) / (param.max - param.min);
56
+ }
57
+ /** Reset every parameter to its resting value (see `defaults`). */
58
+ reset() {
59
+ for (const [id, value] of this.defaults) this.values.set(id, value);
60
+ }
61
+ list() {
62
+ return [...this.params.values()];
63
+ }
64
+ };
65
+
66
+ // ../engine/src/affine.ts
67
+ function translate(tx, ty) {
68
+ return [1, 0, 0, 1, tx, ty];
69
+ }
70
+ function scale(sx, sy) {
71
+ return [sx, 0, 0, sy, 0, 0];
72
+ }
73
+ function rotate(degrees) {
74
+ const r = degrees * Math.PI / 180;
75
+ const c = Math.cos(r);
76
+ const s = Math.sin(r);
77
+ return [c, s, -s, c, 0, 0];
78
+ }
79
+ function multiply(a, b) {
80
+ return [
81
+ a[0] * b[0] + a[2] * b[1],
82
+ a[1] * b[0] + a[3] * b[1],
83
+ a[0] * b[2] + a[2] * b[3],
84
+ a[1] * b[2] + a[3] * b[3],
85
+ a[0] * b[4] + a[2] * b[5] + a[4],
86
+ a[1] * b[4] + a[3] * b[5] + a[5]
87
+ ];
88
+ }
89
+ function toMat3(a) {
90
+ return new Float32Array([a[0], a[1], 0, a[2], a[3], 0, a[4], a[5], 1]);
91
+ }
92
+
93
+ // ../engine/src/warp.ts
94
+ function accumulateKeyformOffsets(keyforms, value, out) {
95
+ const ks = keyforms;
96
+ if (value <= ks[0].value) {
97
+ const { offsets } = ks[0];
98
+ for (let i = 0; i < offsets.length; i++) {
99
+ out[i] += offsets[i];
100
+ }
101
+ } else if (value >= ks[ks.length - 1].value) {
102
+ const { offsets } = ks[ks.length - 1];
103
+ for (let i = 0; i < offsets.length; i++) {
104
+ out[i] += offsets[i];
105
+ }
106
+ } else {
107
+ let lo = ks[0];
108
+ let hi = ks[1];
109
+ for (let k = 1; k < ks.length - 1; k++) {
110
+ if (ks[k].value <= value) {
111
+ lo = ks[k];
112
+ hi = ks[k + 1];
113
+ }
114
+ }
115
+ const t = (value - lo.value) / (hi.value - lo.value);
116
+ const loOff = lo.offsets;
117
+ const hiOff = hi.offsets;
118
+ for (let i = 0; i < loOff.length; i++) {
119
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
120
+ }
121
+ }
122
+ }
123
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
124
+ const lastX = valuesX.length - 1;
125
+ const lastY = valuesY.length - 1;
126
+ let ix;
127
+ let tx;
128
+ if (vx <= valuesX[0]) {
129
+ ix = 0;
130
+ tx = 0;
131
+ } else if (vx >= valuesX[lastX]) {
132
+ ix = lastX - 1;
133
+ tx = 1;
134
+ } else {
135
+ ix = 0;
136
+ for (let k = 0; k < lastX - 1; k++) {
137
+ if (valuesX[k + 1] <= vx) ix = k + 1;
138
+ }
139
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
140
+ }
141
+ let iy;
142
+ let ty;
143
+ if (vy <= valuesY[0]) {
144
+ iy = 0;
145
+ ty = 0;
146
+ } else if (vy >= valuesY[lastY]) {
147
+ iy = lastY - 1;
148
+ ty = 1;
149
+ } else {
150
+ iy = 0;
151
+ for (let k = 0; k < lastY - 1; k++) {
152
+ if (valuesY[k + 1] <= vy) iy = k + 1;
153
+ }
154
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
155
+ }
156
+ const W = valuesX.length;
157
+ const c00 = keyforms2d[iy * W + ix];
158
+ const c10 = keyforms2d[iy * W + ix + 1];
159
+ const c01 = keyforms2d[(iy + 1) * W + ix];
160
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
161
+ const o00 = c00.offsets;
162
+ const o10 = c10.offsets;
163
+ const o01 = c01.offsets;
164
+ const o11 = c11.offsets;
165
+ for (let n = 0; n < o00.length; n++) {
166
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
167
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
168
+ out[n] += top + (bot - top) * ty;
169
+ }
170
+ }
171
+ function applyWarps(rest, warps, params, out) {
172
+ out.set(rest);
173
+ if (!warps || warps.length === 0) return;
174
+ for (const warp of warps) {
175
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
176
+ }
177
+ }
178
+
179
+ // ../engine/src/warp-grid.ts
180
+ function deformWarpGrid(d, params) {
181
+ const points = Float32Array.from(d.grid.points);
182
+ for (const warp of d.warps ?? []) {
183
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
184
+ }
185
+ if (d.warp2d !== void 0) {
186
+ accumulate2DKeyformOffsets(
187
+ d.warp2d.valuesX,
188
+ d.warp2d.valuesY,
189
+ d.warp2d.keyforms2d,
190
+ params.get(d.warp2d.parameter),
191
+ params.get(d.warp2d.parameterY),
192
+ points
193
+ );
194
+ }
195
+ return points;
196
+ }
197
+ function transformGridPoints(points, affine, out = new Float32Array(points.length)) {
198
+ for (let i = 0; i < points.length; i += 2) {
199
+ const x = points[i];
200
+ const y = points[i + 1];
201
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
202
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
203
+ }
204
+ return out;
205
+ }
206
+ function bindPointToRestGrid(x, y, restGrid) {
207
+ const { cols, rows, points } = restGrid;
208
+ const stride = cols + 1;
209
+ let col = cols - 1;
210
+ for (let c = 0; c < cols; c++) {
211
+ const xRight2 = points[(c + 1) * 2];
212
+ if (x < xRight2) {
213
+ col = c;
214
+ break;
215
+ }
216
+ }
217
+ const xLeft = points[col * 2];
218
+ const xRight = points[(col + 1) * 2];
219
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
220
+ let row = rows - 1;
221
+ for (let r = 0; r < rows; r++) {
222
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
223
+ if (y > yBottom2) {
224
+ row = r;
225
+ break;
226
+ }
227
+ }
228
+ const yTop = points[row * stride * 2 + 1];
229
+ const yBottom = points[(row + 1) * stride * 2 + 1];
230
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
231
+ return { cell: row * cols + col, s, t };
232
+ }
233
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
234
+ const n = localVerts.length / 2;
235
+ for (let v = 0; v < n; v++) {
236
+ const lx = localVerts[v * 2];
237
+ const ly = localVerts[v * 2 + 1];
238
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
239
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
240
+ const binding = bindPointToRestGrid(mx, my, restGrid);
241
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
242
+ out[v * 2] = sx;
243
+ out[v * 2 + 1] = sy;
244
+ }
245
+ }
246
+ function sampleWarpGrid(grid, binding) {
247
+ const { cols, points } = grid;
248
+ const stride = cols + 1;
249
+ const row = Math.floor(binding.cell / cols);
250
+ const col = binding.cell % cols;
251
+ const { s, t } = binding;
252
+ const i00 = (row * stride + col) * 2;
253
+ const i10 = (row * stride + col + 1) * 2;
254
+ const i01 = ((row + 1) * stride + col) * 2;
255
+ const i11 = ((row + 1) * stride + col + 1) * 2;
256
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
257
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
258
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
259
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
260
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
261
+ }
262
+ function warpRigidFrame(pivot, restGrid, localPoints) {
263
+ const { cols, rows } = restGrid;
264
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
265
+ const [px, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
266
+ const stride = cols + 1;
267
+ const row = Math.floor(binding.cell / cols);
268
+ const col = binding.cell % cols;
269
+ const { s, t } = binding;
270
+ const i00 = (row * stride + col) * 2;
271
+ const i10 = (row * stride + col + 1) * 2;
272
+ const i01 = ((row + 1) * stride + col) * 2;
273
+ const i11 = ((row + 1) * stride + col + 1) * 2;
274
+ const rest = restGrid.points;
275
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
276
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
277
+ const q = localPoints;
278
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
279
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
280
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
281
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
282
+ const theta = Math.atan2(exY - eyX, exX + eyY);
283
+ const c = Math.cos(theta);
284
+ const sn = Math.sin(theta);
285
+ return [
286
+ c,
287
+ sn,
288
+ -sn,
289
+ c,
290
+ px - (c * pivot.x - sn * pivot.y),
291
+ py - (sn * pivot.x + c * pivot.y)
292
+ ];
293
+ }
294
+
295
+ // ../engine/src/deform.ts
296
+ var IDENTITY_TRANSFORM = {
297
+ x: 0,
298
+ y: 0,
299
+ rotation: 0,
300
+ scaleX: 1,
301
+ scaleY: 1,
302
+ opacity: 1
303
+ };
304
+ function evaluateTransform(transform, bindings, params) {
305
+ const base = transform ?? IDENTITY_TRANSFORM;
306
+ const result = {
307
+ x: base.x,
308
+ y: base.y,
309
+ rotation: base.rotation ?? 0,
310
+ scaleX: base.scaleX ?? 1,
311
+ scaleY: base.scaleY ?? 1,
312
+ opacity: base.opacity ?? 1
313
+ };
314
+ for (const binding of bindings ?? []) {
315
+ const t = params.normalized(binding.parameter);
316
+ const value = binding.from + (binding.to - binding.from) * t;
317
+ switch (binding.channel) {
318
+ case "translateX":
319
+ result.x += value;
320
+ break;
321
+ case "translateY":
322
+ result.y += value;
323
+ break;
324
+ case "rotate":
325
+ result.rotation += value;
326
+ break;
327
+ case "scaleX":
328
+ result.scaleX += value;
329
+ break;
330
+ case "scaleY":
331
+ result.scaleY += value;
332
+ break;
333
+ case "opacity":
334
+ result.opacity *= value;
335
+ break;
336
+ }
337
+ }
338
+ return result;
339
+ }
340
+ function deformerLocalMatrix(d, params) {
341
+ const t = evaluateTransform(d.transform, d.bindings, params);
342
+ const trs = multiply(
343
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
344
+ scale(t.scaleX, t.scaleY)
345
+ );
346
+ return multiply(
347
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
348
+ translate(-d.pivot.x, -d.pivot.y)
349
+ );
350
+ }
351
+ function resolveDeformers(deformers, params) {
352
+ const byId = new Map(deformers.map((d) => [d.id, d]));
353
+ const worlds = /* @__PURE__ */ new Map();
354
+ const grids = /* @__PURE__ */ new Map();
355
+ const localWarps = /* @__PURE__ */ new Map();
356
+ function parentOf(d) {
357
+ if (d.parent === void 0) return void 0;
358
+ const parent = byId.get(d.parent);
359
+ if (!parent) {
360
+ throw new Error(
361
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
362
+ );
363
+ }
364
+ return parent;
365
+ }
366
+ function resolveWorld(d) {
367
+ const cached = worlds.get(d.id);
368
+ if (cached) return cached;
369
+ const local = deformerLocalMatrix(d, params);
370
+ const parent = parentOf(d);
371
+ let world;
372
+ if (parent === void 0) {
373
+ world = local;
374
+ } else if (parent.kind === "warp") {
375
+ const warp = resolveWarp(parent);
376
+ const ridden = multiply(
377
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
378
+ local
379
+ );
380
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
381
+ } else {
382
+ world = multiply(resolveWorld(parent), local);
383
+ }
384
+ worlds.set(d.id, world);
385
+ return world;
386
+ }
387
+ function resolveWarp(d) {
388
+ const cached = localWarps.get(d.id);
389
+ if (cached) return cached;
390
+ const parent = parentOf(d);
391
+ if (parent?.kind === "warp") {
392
+ throw new Error(
393
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
394
+ );
395
+ }
396
+ const parentWorld = parent && resolveWorld(parent);
397
+ const localGrid = deformWarpGrid(d, params);
398
+ grids.set(d.id, {
399
+ cols: d.grid.cols,
400
+ rows: d.grid.rows,
401
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
402
+ });
403
+ const resolved = { localGrid, parentWorld };
404
+ localWarps.set(d.id, resolved);
405
+ return resolved;
406
+ }
407
+ for (const d of deformers) {
408
+ if (d.kind === "warp") resolveWarp(d);
409
+ else resolveWorld(d);
410
+ }
411
+ return { worlds, grids };
412
+ }
413
+
414
+ // ../engine/src/view.ts
415
+ function checkedView(view) {
416
+ const { x, y, width, height } = view;
417
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
418
+ throw new Error(`Iki: setView() needs a finite x and y, got ${x}, ${y}`);
419
+ }
420
+ if (!(Number.isFinite(width) && width > 0)) {
421
+ throw new Error(
422
+ `Iki: setView() needs a positive finite width, got ${width}`
423
+ );
424
+ }
425
+ if (!(Number.isFinite(height) && height > 0)) {
426
+ throw new Error(
427
+ `Iki: setView() needs a positive finite height, got ${height}`
428
+ );
429
+ }
430
+ return { x, y, width, height };
431
+ }
432
+ function projectView(viewportWidth, viewportHeight, view) {
433
+ const fit = Math.min(
434
+ viewportWidth / view.width,
435
+ viewportHeight / view.height
436
+ );
437
+ return multiply(
438
+ scale(fit * 2 / viewportWidth, fit * 2 / viewportHeight),
439
+ translate(-view.x, -view.y)
440
+ );
441
+ }
442
+
443
+ // ../engine/src/player.ts
444
+ var MASK_ALPHA_CUTOFF = 0.5;
445
+ var IkiPlayer = class {
446
+ constructor(canvas2) {
447
+ this.canvas = canvas2;
448
+ const gl = canvas2.getContext("webgl2", {
449
+ alpha: true,
450
+ // The whole pipeline is premultiplied-alpha: textures are uploaded
451
+ // premultiplied, the fragment shader keeps them so, the blend function
452
+ // is ONE / ONE_MINUS_SRC_ALPHA, and the page compositor reads the
453
+ // framebuffer as premultiplied. Straight-alpha (`premultipliedAlpha: false`) cannot
454
+ // be made consistent with SRC_ALPHA-style blending: semi-transparent
455
+ // pixels over a transparent background come out premultiplied anyway
456
+ // and composite too dark.
457
+ premultipliedAlpha: true,
458
+ // Stencil buffer backs clip masks (a part rendered only inside its masks'
459
+ // coverage). Granted by every modern browser; the load() guard reports if not.
460
+ stencil: true
461
+ });
462
+ if (!gl) throw new Error("WebGL2 is not available in this browser");
463
+ this.gl = gl;
464
+ this.stencilAvailable = gl.getContextAttributes()?.stencil ?? false;
465
+ this.program = createProgram(gl, VERTEX_SHADER, FRAGMENT_SHADER);
466
+ this.uMatrix = getUniform(gl, this.program, "u_matrix");
467
+ this.uColor = getUniform(gl, this.program, "u_color");
468
+ this.uUseTexture = getUniform(gl, this.program, "u_useTexture");
469
+ this.uTex = getUniform(gl, this.program, "u_tex");
470
+ this.uUvOffset = getUniform(gl, this.program, "u_uvOffset");
471
+ this.uUvScale = getUniform(gl, this.program, "u_uvScale");
472
+ this.uUseMeshUv = getUniform(gl, this.program, "u_useMeshUv");
473
+ this.uAlphaCutoff = getUniform(gl, this.program, "u_alphaCutoff");
474
+ this.aPos = gl.getAttribLocation(this.program, "a_pos");
475
+ this.aUv = gl.getAttribLocation(this.program, "a_uv");
476
+ this.quad = createUnitQuad(gl);
477
+ gl.enable(gl.BLEND);
478
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
479
+ }
480
+ canvas;
481
+ gl;
482
+ program;
483
+ quad;
484
+ uMatrix;
485
+ uColor;
486
+ uUseTexture;
487
+ uTex;
488
+ uUvOffset;
489
+ uUvScale;
490
+ uUseMeshUv;
491
+ uAlphaCutoff;
492
+ aPos;
493
+ aUv;
494
+ /** True when the context granted a stencil buffer; clipping needs it. */
495
+ stencilAvailable;
496
+ model;
497
+ view;
498
+ parts = [];
499
+ params = new ParameterStore([]);
500
+ rafId;
501
+ /** Uploaded textures, index-aligned with `model.textures`; `null` = unusable. */
502
+ textures = [];
503
+ /** Bumped by every `load` and by `destroy`; lets a stale async load bail. */
504
+ loadGeneration = 0;
505
+ /** True from the moment `load()` is entered until it resolves or throws. */
506
+ loadPending = false;
507
+ /** Latches the un-awaited-load report, so a repeat caller says it once. */
508
+ warnedLoadUnfinished = false;
509
+ destroyed = false;
510
+ /**
511
+ * Engine-internal mesh buffers, keyed by the part's INDEX in `this.parts`
512
+ * (NOT by part id — duplicate ids must not swap buffers).
513
+ */
514
+ partMeshes = /* @__PURE__ */ new Map();
515
+ /**
516
+ * Clip groups resolved once per `load()`: consumer part index (into `this.parts`)
517
+ * → its mask part indices. A part absent from this map is unclipped.
518
+ */
519
+ partClipGroups = /* @__PURE__ */ new Map();
520
+ /**
521
+ * Load a model and reset parameters to their defaults. All textures are
522
+ * decoded and uploaded before the model is swapped in — the swap is atomic,
523
+ * so you never see a partially-textured frame. `start()` may be called any
524
+ * time, but nothing renders until the first `load()` resolves. For an
525
+ * embedded `data:` atlas this is near-instant.
526
+ *
527
+ * Individual texture decode/upload failures are non-fatal: they are logged
528
+ * via `console.error`, the affected parts are skipped, and `load()` still
529
+ * resolves — the returned {@link IkiLoadResult} lists the indices of any
530
+ * textures that failed, so a host can detect and report a partial load. The
531
+ * model is assumed already validated by `@ikijs/format`.
532
+ *
533
+ * Mesh buffer allocation failure IS fatal (unlike per-texture skip) because
534
+ * textures have an `IkiLoadResult.failedTextures` reporting surface and mesh
535
+ * buffers have none — there is no partial-mesh concept in the format.
536
+ *
537
+ * AWAIT THIS before reading {@link getParameters}. The swap happens after
538
+ * texture decoding, so an un-awaited `load()` leaves the parameter store
539
+ * empty for the rest of the tick; `getParameters` reports that case rather
540
+ * than letting a host conclude the model drives nothing.
541
+ */
542
+ async load(model) {
543
+ this.loadPending = true;
544
+ try {
545
+ return await this.adoptModel(model);
546
+ } finally {
547
+ this.loadPending = false;
548
+ }
549
+ }
550
+ async adoptModel(model) {
551
+ const { gl } = this;
552
+ const generation = ++this.loadGeneration;
553
+ const sources = model.textures ?? [];
554
+ const decoded = await Promise.allSettled(
555
+ sources.map((tex) => decodeTexture(tex.source))
556
+ );
557
+ if (generation !== this.loadGeneration || this.destroyed) {
558
+ for (const result of decoded) {
559
+ if (result.status === "fulfilled" && result.value) result.value.close();
560
+ }
561
+ return { failedTextures: [], superseded: true };
562
+ }
563
+ const maxTextureSizeRaw = gl.getParameter(gl.MAX_TEXTURE_SIZE);
564
+ const maxTextureSize = typeof maxTextureSizeRaw === "number" ? maxTextureSizeRaw : void 0;
565
+ if (maxTextureSize === void 0) {
566
+ console.error("Iki: WebGL context lost during load()");
567
+ }
568
+ drainGlErrors(gl);
569
+ const uploaded = decoded.map((result, i) => {
570
+ if (result.status === "rejected") {
571
+ console.error(`Iki: failed to decode textures[${i}]`, result.reason);
572
+ return null;
573
+ }
574
+ const bitmap = result.value;
575
+ if (!bitmap) return null;
576
+ if (maxTextureSize !== void 0 && (bitmap.width > maxTextureSize || bitmap.height > maxTextureSize)) {
577
+ console.error(
578
+ `Iki: textures[${i}] is ${bitmap.width}x${bitmap.height}, over this device's ${maxTextureSize}px limit`
579
+ );
580
+ bitmap.close();
581
+ return null;
582
+ }
583
+ const texture = gl.createTexture();
584
+ if (!texture) {
585
+ bitmap.close();
586
+ console.error(`Iki: failed to allocate GL texture for textures[${i}]`);
587
+ return null;
588
+ }
589
+ gl.bindTexture(gl.TEXTURE_2D, texture);
590
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
591
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
592
+ drainGlErrors(gl);
593
+ gl.texImage2D(
594
+ gl.TEXTURE_2D,
595
+ 0,
596
+ gl.RGBA,
597
+ gl.RGBA,
598
+ gl.UNSIGNED_BYTE,
599
+ bitmap
600
+ );
601
+ bitmap.close();
602
+ const uploadError = gl.getError();
603
+ if (uploadError !== gl.NO_ERROR) {
604
+ gl.deleteTexture(texture);
605
+ console.error(
606
+ `Iki: failed to upload textures[${i}] (GL error 0x${uploadError.toString(16)})`
607
+ );
608
+ return null;
609
+ }
610
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
611
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
612
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
613
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
614
+ return texture;
615
+ });
616
+ const nextParts = [...model.parts].sort((a, b) => a.order - b.order);
617
+ const nextPartMeshes = /* @__PURE__ */ new Map();
618
+ for (let i = 0; i < nextParts.length; i++) {
619
+ const part = nextParts[i];
620
+ if (!part.mesh) continue;
621
+ const { mesh } = part;
622
+ const currentPartBuffers = [];
623
+ const positionBuf = gl.createBuffer();
624
+ if (!positionBuf) {
625
+ deletePartMeshBuffers(gl, nextPartMeshes);
626
+ deleteUploadedTextures(gl, uploaded);
627
+ throw new Error("Iki: failed to allocate mesh buffer");
628
+ }
629
+ currentPartBuffers.push(positionBuf);
630
+ const uvBuf = gl.createBuffer();
631
+ if (!uvBuf) {
632
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
633
+ deletePartMeshBuffers(gl, nextPartMeshes);
634
+ deleteUploadedTextures(gl, uploaded);
635
+ throw new Error("Iki: failed to allocate mesh buffer");
636
+ }
637
+ currentPartBuffers.push(uvBuf);
638
+ const indexBuf = gl.createBuffer();
639
+ if (!indexBuf) {
640
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
641
+ deletePartMeshBuffers(gl, nextPartMeshes);
642
+ deleteUploadedTextures(gl, uploaded);
643
+ throw new Error("Iki: failed to allocate mesh buffer");
644
+ }
645
+ const rest = new Float32Array(mesh.vertices);
646
+ const warpDeformer = part.deformer !== void 0 ? model.deformers?.find(
647
+ (d) => d.kind === "warp" && d.id === part.deformer
648
+ ) : void 0;
649
+ const isWarpChild = warpDeformer !== void 0;
650
+ const hasWarps = (part.warps?.length ?? 0) > 0;
651
+ const dynamic = hasWarps || isWarpChild;
652
+ const scratch = dynamic ? new Float32Array(mesh.vertices.length) : void 0;
653
+ const local = isWarpChild ? new Float32Array(mesh.vertices.length) : void 0;
654
+ drainGlErrors(gl);
655
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuf);
656
+ gl.bufferData(
657
+ gl.ARRAY_BUFFER,
658
+ rest,
659
+ dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW
660
+ );
661
+ gl.bindBuffer(gl.ARRAY_BUFFER, uvBuf);
662
+ gl.bufferData(
663
+ gl.ARRAY_BUFFER,
664
+ new Float32Array(mesh.uvs),
665
+ gl.STATIC_DRAW
666
+ );
667
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuf);
668
+ gl.bufferData(
669
+ gl.ELEMENT_ARRAY_BUFFER,
670
+ new Uint16Array(mesh.indices),
671
+ gl.STATIC_DRAW
672
+ );
673
+ const meshUploadError = gl.getError();
674
+ if (meshUploadError !== gl.NO_ERROR) {
675
+ for (const b of currentPartBuffers) gl.deleteBuffer(b);
676
+ gl.deleteBuffer(indexBuf);
677
+ deletePartMeshBuffers(gl, nextPartMeshes);
678
+ deleteUploadedTextures(gl, uploaded);
679
+ throw new Error(
680
+ `Iki: failed to upload mesh buffers for part "${part.id}" (GL error 0x${meshUploadError.toString(16)})`
681
+ );
682
+ }
683
+ nextPartMeshes.set(i, {
684
+ position: positionBuf,
685
+ uv: uvBuf,
686
+ index: indexBuf,
687
+ indexCount: mesh.indices.length,
688
+ rest,
689
+ scratch,
690
+ warps: part.warps,
691
+ warpDeformer,
692
+ local
693
+ });
694
+ }
695
+ const nextClipGroups = /* @__PURE__ */ new Map();
696
+ const indexById = /* @__PURE__ */ new Map();
697
+ for (let i = 0; i < nextParts.length; i++) {
698
+ indexById.set(nextParts[i].id, i);
699
+ }
700
+ for (let i = 0; i < nextParts.length; i++) {
701
+ const clip = nextParts[i].clip;
702
+ if (!clip) continue;
703
+ const maskIndices = clip.masks.map((maskId) => indexById.get(maskId)).filter((mi) => mi !== void 0);
704
+ if (maskIndices.length > 0) nextClipGroups.set(i, maskIndices);
705
+ }
706
+ if (nextClipGroups.size > 0 && !this.stencilAvailable) {
707
+ console.error(
708
+ "Iki: model uses clip masks but this WebGL2 context has no stencil buffer; rendering unclipped"
709
+ );
710
+ }
711
+ deletePartMeshBuffers(gl, this.partMeshes);
712
+ for (const texture of this.textures) {
713
+ if (texture) gl.deleteTexture(texture);
714
+ }
715
+ this.model = model;
716
+ this.params = new ParameterStore(model.parameters);
717
+ this.parts = nextParts;
718
+ this.partMeshes = nextPartMeshes;
719
+ this.partClipGroups = nextClipGroups;
720
+ this.textures = uploaded;
721
+ return {
722
+ failedTextures: uploaded.flatMap((t, i) => t === null ? [i] : []),
723
+ superseded: false
724
+ };
725
+ }
726
+ /**
727
+ * Start the render loop. Safe to call more than once, and a no-op after
728
+ * {@link destroy} — the program and buffers the loop draws with are gone, so
729
+ * restarting would only spray GL errors.
730
+ */
731
+ start() {
732
+ if (this.rafId !== void 0 || this.destroyed) return;
733
+ const loop = () => {
734
+ this.renderFrame();
735
+ this.rafId = requestAnimationFrame(loop);
736
+ };
737
+ this.rafId = requestAnimationFrame(loop);
738
+ }
739
+ stop() {
740
+ if (this.rafId === void 0) return;
741
+ cancelAnimationFrame(this.rafId);
742
+ this.rafId = void 0;
743
+ }
744
+ /**
745
+ * Set a parameter value (clamped to its range). Unknown ids and non-finite
746
+ * values are ignored — see {@link ParameterStore.set}.
747
+ */
748
+ setParameter(id, value) {
749
+ this.params.set(id, value);
750
+ }
751
+ /**
752
+ * Frame the canvas on `view` (centre and size in model units) instead of the
753
+ * model's box, which is the default. Pass a wider view for a full body whose
754
+ * raised arms leave the box (how much room is the host's call: a combined
755
+ * pose sets the reach), or a smaller one for a face crop. Parts clip at the
756
+ * canvas's edge, never at the view. The view survives `load()`; `setView()`
757
+ * with no argument restores the default. Throws on a non-finite centre or a
758
+ * non-positive size.
759
+ */
760
+ setView(view) {
761
+ this.view = view ? checkedView(view) : void 0;
762
+ }
763
+ /**
764
+ * Current value of a parameter, or 0 for an unknown id.
765
+ *
766
+ * Hosts need this to avoid shadowing the engine's state: the motion drivers
767
+ * read the live pose to compute the next one, and without a read accessor
768
+ * every host has to keep its own mirror of what it last wrote — and keep that
769
+ * mirror's clamping in step with {@link ParameterStore} by hand.
770
+ */
771
+ getParameter(id) {
772
+ return this.params.get(id);
773
+ }
774
+ /**
775
+ * The model's parameter descriptors, for building UI or host wiring.
776
+ *
777
+ * Empty until the first {@link load} resolves. Reaching it through an
778
+ * un-awaited `load()` is the one mistake in this class that produces no
779
+ * error and no motion: the caller gets `[]`, concludes the model has no
780
+ * parameters, and drives nothing — so that case is reported instead of
781
+ * being indistinguishable from a model that really declares none. A
782
+ * reload is deliberately NOT reported: those parameters are stale rather
783
+ * than absent, and warning there would fire on legitimate concurrent reads.
784
+ */
785
+ getParameters() {
786
+ if (this.loadPending && this.model === void 0 && !this.warnedLoadUnfinished) {
787
+ this.warnedLoadUnfinished = true;
788
+ console.error(
789
+ "Iki: getParameters() ran before load() finished, so it returned an empty list \u2014 await load() before reading parameters."
790
+ );
791
+ }
792
+ return this.params.list();
793
+ }
794
+ destroy() {
795
+ this.stop();
796
+ this.destroyed = true;
797
+ ++this.loadGeneration;
798
+ const { gl } = this;
799
+ for (const texture of this.textures) {
800
+ if (texture) gl.deleteTexture(texture);
801
+ }
802
+ this.textures = [];
803
+ deletePartMeshBuffers(gl, this.partMeshes);
804
+ this.partMeshes = /* @__PURE__ */ new Map();
805
+ gl.deleteBuffer(this.quad);
806
+ gl.deleteProgram(this.program);
807
+ }
808
+ renderFrame() {
809
+ const { gl, canvas: canvas2 } = this;
810
+ const dpr = window.devicePixelRatio || 1;
811
+ const width = Math.max(1, Math.floor(canvas2.clientWidth * dpr));
812
+ const height = Math.max(1, Math.floor(canvas2.clientHeight * dpr));
813
+ if (canvas2.width !== width || canvas2.height !== height) {
814
+ canvas2.width = width;
815
+ canvas2.height = height;
816
+ }
817
+ gl.viewport(0, 0, width, height);
818
+ gl.clearColor(0, 0, 0, 0);
819
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
820
+ if (!this.model) return;
821
+ const { width: modelW, height: modelH } = this.model.canvas;
822
+ const project = projectView(
823
+ width,
824
+ height,
825
+ this.view ?? { x: 0, y: 0, width: modelW, height: modelH }
826
+ );
827
+ gl.useProgram(this.program);
828
+ const resolved = this.model.deformers && this.model.deformers.length > 0 ? resolveDeformers(this.model.deformers, this.params) : void 0;
829
+ const deformerWorlds = resolved?.worlds;
830
+ const warpGrids = resolved?.grids;
831
+ gl.uniform1f(this.uAlphaCutoff, 0);
832
+ for (let index = 0; index < this.parts.length; index++) {
833
+ const maskIndices = this.partClipGroups.get(index);
834
+ if (maskIndices && this.stencilAvailable) {
835
+ this.drawClipped(
836
+ index,
837
+ maskIndices,
838
+ project,
839
+ deformerWorlds,
840
+ warpGrids
841
+ );
842
+ } else {
843
+ this.drawPart(index, project, deformerWorlds, warpGrids);
844
+ }
845
+ }
846
+ }
847
+ /**
848
+ * Draw a clipped part: stencil the union of its masks' alpha coverage, then
849
+ * draw the part only where the stencil was written. The mask parts also draw
850
+ * normally in their own `order` slot — this is an EXTRA, color-free pass over
851
+ * the same per-frame deformed geometry. All stencil/colorMask state the pass
852
+ * touches is restored before returning so later parts are unaffected.
853
+ */
854
+ drawClipped(index, maskIndices, project, deformerWorlds, warpGrids) {
855
+ const { gl } = this;
856
+ gl.clear(gl.STENCIL_BUFFER_BIT);
857
+ gl.enable(gl.STENCIL_TEST);
858
+ gl.colorMask(false, false, false, false);
859
+ gl.stencilMask(255);
860
+ gl.stencilFunc(gl.ALWAYS, 1, 255);
861
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
862
+ gl.uniform1f(this.uAlphaCutoff, MASK_ALPHA_CUTOFF);
863
+ for (const maskIndex of maskIndices) {
864
+ this.drawPart(maskIndex, project, deformerWorlds, warpGrids);
865
+ }
866
+ gl.uniform1f(this.uAlphaCutoff, 0);
867
+ gl.colorMask(true, true, true, true);
868
+ gl.stencilMask(0);
869
+ gl.stencilFunc(gl.EQUAL, 1, 255);
870
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
871
+ this.drawPart(index, project, deformerWorlds, warpGrids);
872
+ gl.disable(gl.STENCIL_TEST);
873
+ gl.stencilMask(255);
874
+ gl.stencilFunc(gl.ALWAYS, 0, 255);
875
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
876
+ }
877
+ /**
878
+ * Draw a single part with its full per-part material + geometry state. Shared
879
+ * by the normal pass, the stencil mask-write pass, and the masked consumer
880
+ * draw — so every path prepares the SAME complete uniform/texture/VBO state
881
+ * (the caller only sets stencil/colorMask/u_alphaCutoff around it).
882
+ */
883
+ drawPart(index, project, deformerWorlds, warpGrids) {
884
+ const { gl } = this;
885
+ const part = this.parts[index];
886
+ const texture = part.texture ? this.textures[part.texture.index] : void 0;
887
+ if (part.texture && !texture) return;
888
+ const t = this.evaluate(part);
889
+ const warpChild = this.partMeshes.get(index)?.warpDeformer;
890
+ let m;
891
+ if (warpChild) {
892
+ m = project;
893
+ } else if (part.deformer !== void 0) {
894
+ const dWorld = deformerWorlds.get(part.deformer);
895
+ if (!dWorld) {
896
+ throw new Error(
897
+ `part "${part.id}" references unknown deformer "${part.deformer}"`
898
+ );
899
+ }
900
+ m = multiply(multiply(project, dWorld), translate(t.x, t.y));
901
+ m = multiply(m, rotate(t.rotation));
902
+ m = multiply(m, scale(part.width * t.scaleX, part.height * t.scaleY));
903
+ } else {
904
+ m = multiply(project, translate(t.x, t.y));
905
+ m = multiply(m, rotate(t.rotation));
906
+ m = multiply(m, scale(part.width * t.scaleX, part.height * t.scaleY));
907
+ }
908
+ const [r, g, b, a] = part.color;
909
+ gl.uniformMatrix3fv(this.uMatrix, false, toMat3(m));
910
+ gl.uniform4f(this.uColor, r, g, b, a * t.opacity);
911
+ if (part.texture && texture) {
912
+ const { uv } = part.texture;
913
+ gl.uniform1i(this.uUseTexture, 1);
914
+ gl.activeTexture(gl.TEXTURE0);
915
+ gl.bindTexture(gl.TEXTURE_2D, texture);
916
+ gl.uniform1i(this.uTex, 0);
917
+ gl.uniform2f(this.uUvOffset, uv.x, uv.y);
918
+ gl.uniform2f(this.uUvScale, uv.width, uv.height);
919
+ } else {
920
+ gl.uniform1i(this.uUseTexture, 0);
921
+ }
922
+ if (part.mesh) {
923
+ const pm = this.partMeshes.get(index);
924
+ if (!pm) {
925
+ throw new Error(`Iki: mesh buffers missing for part "${part.id}"`);
926
+ }
927
+ gl.uniform1i(this.uUseMeshUv, 1);
928
+ if (pm.warpDeformer) {
929
+ const warpDef = pm.warpDeformer;
930
+ const grid = warpGrids.get(warpDef.id);
931
+ applyWarps(pm.rest, pm.warps, this.params, pm.local);
932
+ const trs = evaluateTransform(
933
+ part.transform,
934
+ part.bindings,
935
+ this.params
936
+ );
937
+ const partAffine = multiply(
938
+ multiply(translate(trs.x, trs.y), rotate(trs.rotation)),
939
+ scale(part.width * trs.scaleX, part.height * trs.scaleY)
940
+ );
941
+ applyWarpToChild(
942
+ pm.local,
943
+ partAffine,
944
+ warpDef.grid,
945
+ grid,
946
+ pm.scratch
947
+ );
948
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
949
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, pm.scratch);
950
+ } else if (pm.warps && pm.warps.length > 0) {
951
+ applyWarps(pm.rest, pm.warps, this.params, pm.scratch);
952
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
953
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, pm.scratch);
954
+ }
955
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.position);
956
+ gl.enableVertexAttribArray(this.aPos);
957
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
958
+ gl.bindBuffer(gl.ARRAY_BUFFER, pm.uv);
959
+ gl.enableVertexAttribArray(this.aUv);
960
+ gl.vertexAttribPointer(this.aUv, 2, gl.FLOAT, false, 0, 0);
961
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, pm.index);
962
+ gl.drawElements(gl.TRIANGLES, pm.indexCount, gl.UNSIGNED_SHORT, 0);
963
+ } else {
964
+ gl.uniform1i(this.uUseMeshUv, 0);
965
+ gl.disableVertexAttribArray(this.aUv);
966
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quad);
967
+ gl.enableVertexAttribArray(this.aPos);
968
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
969
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
970
+ }
971
+ }
972
+ /** Resolve a part's effective transform from its base plus active bindings. */
973
+ evaluate(part) {
974
+ return evaluateTransform(part.transform, part.bindings, this.params);
975
+ }
976
+ };
977
+ var VERTEX_SHADER = `#version 300 es
978
+ in vec2 a_pos;
979
+ in vec2 a_uv;
980
+ uniform mat3 u_matrix;
981
+ uniform vec2 u_uvOffset;
982
+ uniform vec2 u_uvScale;
983
+ uniform bool u_useMeshUv;
984
+ // centroid: the context is multisampled (antialias defaults on), and a pixel
985
+ // that a triangle only partly covers is otherwise shaded at its centre even
986
+ // when that lies outside the triangle \u2014 v_uv then extrapolates past the
987
+ // part's inset atlas rect into the neighbouring region's gutter, which holds
988
+ // ANOTHER part's extruded edge. One real model drew a 1 px cream line along
989
+ // its back hair's top edge from the body packed above it. Centroid moves the
990
+ // evaluation inside the covered samples, so v_uv stays inside the rect.
991
+ centroid out vec2 v_uv;
992
+ void main() {
993
+ if (u_useMeshUv) {
994
+ // Mesh path: UVs are already top-left atlas-space; pass straight through,
995
+ // no flip (the only flip in the pipeline lives in the quad branch below).
996
+ v_uv = a_uv;
997
+ } else {
998
+ // Quad path: a_pos corners are +/-0.5; lift to 0..1 (y-up), then map into
999
+ // the atlas sub-rect with a single V flip so the result is top-left UVs.
1000
+ vec2 uvLocal = a_pos + 0.5;
1001
+ v_uv = vec2(
1002
+ u_uvOffset.x + uvLocal.x * u_uvScale.x,
1003
+ u_uvOffset.y + (1.0 - uvLocal.y) * u_uvScale.y
1004
+ );
1005
+ }
1006
+ vec3 p = u_matrix * vec3(a_pos, 1.0);
1007
+ gl_Position = vec4(p.xy, 0.0, 1.0);
1008
+ }`;
1009
+ var FRAGMENT_SHADER = `#version 300 es
1010
+ precision mediump float;
1011
+ uniform vec4 u_color;
1012
+ uniform bool u_useTexture;
1013
+ uniform sampler2D u_tex;
1014
+ uniform float u_alphaCutoff;
1015
+ centroid in vec2 v_uv;
1016
+ out vec4 outColor;
1017
+ void main() {
1018
+ // Texels are premultiplied (see the upload); the untextured fill is opaque
1019
+ // white, premultiplied or not.
1020
+ vec4 base = u_useTexture ? texture(u_tex, v_uv) : vec4(1.0);
1021
+ vec4 tinted = base * u_color;
1022
+ // 0 for normal draws (no-op); raised during the stencil mask-write pass so
1023
+ // only opaque mask coverage marks the stencil (the transparent fringe is cut).
1024
+ if (tinted.a < u_alphaCutoff) discard;
1025
+ // The blend function and the canvas compositing contract (premultipliedAlpha:
1026
+ // true) both expect rgb already scaled by alpha. base.rgb is; the tint's own
1027
+ // alpha still has to scale it (base.a is already folded into base.rgb).
1028
+ outColor = vec4(tinted.rgb * u_color.a, tinted.a);
1029
+ }`;
1030
+ async function decodeTexture(source) {
1031
+ if (!source.startsWith("data:")) {
1032
+ console.warn(
1033
+ "Iki: external texture sources are unsupported in v1; skipping",
1034
+ source.slice(0, 32)
1035
+ );
1036
+ return null;
1037
+ }
1038
+ const blob = await (await fetch(source)).blob();
1039
+ return createImageBitmap(blob, {
1040
+ imageOrientation: "none",
1041
+ premultiplyAlpha: "premultiply"
1042
+ });
1043
+ }
1044
+ function createUnitQuad(gl) {
1045
+ const buffer = gl.createBuffer();
1046
+ if (!buffer) throw new Error("failed to allocate quad buffer");
1047
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
1048
+ gl.bufferData(
1049
+ gl.ARRAY_BUFFER,
1050
+ new Float32Array([-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5]),
1051
+ gl.STATIC_DRAW
1052
+ );
1053
+ return buffer;
1054
+ }
1055
+ function drainGlErrors(gl) {
1056
+ for (let i = 0; i < 32 && gl.getError() !== gl.NO_ERROR; i++) {
1057
+ }
1058
+ }
1059
+ function deletePartMeshBuffers(gl, meshes) {
1060
+ for (const pm of meshes.values()) {
1061
+ gl.deleteBuffer(pm.position);
1062
+ gl.deleteBuffer(pm.uv);
1063
+ gl.deleteBuffer(pm.index);
1064
+ }
1065
+ }
1066
+ function deleteUploadedTextures(gl, textures) {
1067
+ for (const texture of textures) {
1068
+ if (texture) gl.deleteTexture(texture);
1069
+ }
1070
+ }
1071
+ function createProgram(gl, vertexSrc, fragmentSrc) {
1072
+ const program = gl.createProgram();
1073
+ if (!program) throw new Error("failed to allocate WebGL program");
1074
+ gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, vertexSrc));
1075
+ gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc));
1076
+ gl.linkProgram(program);
1077
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
1078
+ const log = gl.getProgramInfoLog(program);
1079
+ gl.deleteProgram(program);
1080
+ throw new Error(`program link failed: ${log}`);
1081
+ }
1082
+ return program;
1083
+ }
1084
+ function compileShader(gl, type, source) {
1085
+ const shader = gl.createShader(type);
1086
+ if (!shader) throw new Error("failed to allocate shader");
1087
+ gl.shaderSource(shader, source);
1088
+ gl.compileShader(shader);
1089
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
1090
+ const log = gl.getShaderInfoLog(shader);
1091
+ gl.deleteShader(shader);
1092
+ throw new Error(`shader compile failed: ${log}`);
1093
+ }
1094
+ return shader;
1095
+ }
1096
+ function getUniform(gl, program, name) {
1097
+ const loc = gl.getUniformLocation(program, name);
1098
+ if (!loc) throw new Error(`uniform not found: ${name}`);
1099
+ return loc;
1100
+ }
1101
+
1102
+ // ../format/src/parameters.ts
1103
+ var StandardParameter = {
1104
+ /** Mouth open amount for lip-sync (0 closed .. 1 open). */
1105
+ MouthOpen: "ParamMouthOpenY",
1106
+ /** Mouth form / smile (-1 .. 1). */
1107
+ MouthForm: "ParamMouthForm",
1108
+ /** Left eye open (0 closed .. 1 open). Drive with the right eye for a blink. */
1109
+ EyeOpenLeft: "ParamEyeLOpen",
1110
+ /** Right eye open (0 closed .. 1 open). */
1111
+ EyeOpenRight: "ParamEyeROpen",
1112
+ /** Eyeball gaze, horizontal (-1 .. 1). */
1113
+ EyeballX: "ParamEyeBallX",
1114
+ /** Eyeball gaze, vertical (-1 .. 1). */
1115
+ EyeballY: "ParamEyeBallY",
1116
+ /** Head angle, horizontal degrees. */
1117
+ AngleX: "ParamAngleX",
1118
+ /** Head angle, vertical degrees. */
1119
+ AngleY: "ParamAngleY",
1120
+ /** Head tilt / roll degrees. Positive tilts the top of the head toward the
1121
+ * viewer's right (clockwise on screen), matching Live2D's ParamAngleZ so a
1122
+ * host's head-tracking maps 1:1; note this is the opposite sense from the
1123
+ * CCW-positive brow angles below. */
1124
+ AngleZ: "ParamAngleZ",
1125
+ /** Body turn, degrees (-10 .. 10). Positive turns the body toward the
1126
+ * viewer's right, as AngleX does the head. */
1127
+ BodyAngleX: "ParamBodyAngleX",
1128
+ /** Body lean, degrees (-10 .. 10). Positive moves the upper body up, negative bows. */
1129
+ BodyAngleY: "ParamBodyAngleY",
1130
+ /** Body tilt, degrees (-10 .. 10). Positive tilts the top toward the viewer's
1131
+ * right (clockwise on screen), as AngleZ does the head. */
1132
+ BodyAngleZ: "ParamBodyAngleZ",
1133
+ /** Idle breath (0 .. 1), cycled by the host. */
1134
+ Breath: "ParamBreath",
1135
+ /** Left brow vertical raise/lower (-1 down .. 1 up). */
1136
+ BrowLeftY: "ParamBrowLY",
1137
+ /** Right brow vertical raise/lower (-1 down .. 1 up). */
1138
+ BrowRightY: "ParamBrowRY",
1139
+ /** Left brow tilt (-1 .. 1, CCW-positive). */
1140
+ BrowLeftAngle: "ParamBrowLAngle",
1141
+ /** Right brow tilt (-1 .. 1, CCW-positive). */
1142
+ BrowRightAngle: "ParamBrowRAngle",
1143
+ /** Cheek blush strength (0 .. 1), raised by an expression. */
1144
+ Cheek: "ParamCheek",
1145
+ /** Horizontal hair sway. Physics OUTPUT — driven by the spring, not set by the host. */
1146
+ HairSwayX: "ParamHairSwayX",
1147
+ /** Hair sway behind a head tilt. Physics OUTPUT — driven by the spring, not set by the host. */
1148
+ HairSwayZ: "ParamHairSwayZ",
1149
+ /** Left shoulder, degrees. Positive raises the arm outward (mirrored on the right). */
1150
+ ArmLeft: "ParamArmL",
1151
+ /** Right shoulder, degrees. Positive raises the arm outward (mirrored on the left). */
1152
+ ArmRight: "ParamArmR",
1153
+ /** Left elbow, degrees. Positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right). */
1154
+ ElbowLeft: "ParamElbowL",
1155
+ /** Right elbow, degrees. Positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left). */
1156
+ ElbowRight: "ParamElbowR",
1157
+ /** Left pose-forearm switch (0 .. 1): 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm. */
1158
+ ArmPoseLeft: "ParamArmPoseL",
1159
+ /** Right pose-forearm switch (0 .. 1): 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm. */
1160
+ ArmPoseRight: "ParamArmPoseR",
1161
+ /** Left pose forearm's own small rotation about the elbow, degrees. Positive tips the raised hand outward, away from the body (mirrored on the right). */
1162
+ ArmPoseAngleLeft: "ParamArmPoseAngleL",
1163
+ /** Right pose forearm's own small rotation about the elbow, degrees. Positive tips the raised hand outward, away from the body (mirrored on the left). */
1164
+ ArmPoseAngleRight: "ParamArmPoseAngleR"
1165
+ };
1166
+
1167
+ // ../format/src/validate-animations.ts
1168
+ var IDLE_PROCEDURAL = /* @__PURE__ */ new Set([
1169
+ StandardParameter.EyeOpenLeft,
1170
+ StandardParameter.EyeOpenRight,
1171
+ StandardParameter.Breath
1172
+ ]);
1173
+
1174
+ // ../engine/src/frame-clock.ts
1175
+ var FIXED_DT_S = 1 / 60;
1176
+
1177
+ // ../engine/src/idle-motion.ts
1178
+ var BLINK_CLOSE_MS = 60;
1179
+ var BLINK_HOLD_MS = 20;
1180
+ var BLINK_OPEN_MS = 100;
1181
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
1182
+
1183
+ // ../engine/src/hair-chain-motion.ts
1184
+ var DEG2RAD = Math.PI / 180;
1185
+ var RAD2DEG = 180 / Math.PI;
1186
+
1187
+ // ../engine/src/iki-motion.ts
1188
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
1189
+ StandardParameter.AngleX,
1190
+ StandardParameter.AngleY,
1191
+ StandardParameter.AngleZ,
1192
+ StandardParameter.EyeballX,
1193
+ StandardParameter.EyeballY
1194
+ ]);
1195
+
1196
+ // ../engine/src/folds.ts
1197
+ var ANGLES = [
1198
+ StandardParameter.AngleX,
1199
+ StandardParameter.AngleY,
1200
+ StandardParameter.AngleZ,
1201
+ StandardParameter.BodyAngleX,
1202
+ StandardParameter.BodyAngleY,
1203
+ StandardParameter.BodyAngleZ
1204
+ ];
1205
+ var CROSSES = [
1206
+ [StandardParameter.EyeOpenLeft],
1207
+ [StandardParameter.EyeOpenRight],
1208
+ [StandardParameter.MouthOpen],
1209
+ [StandardParameter.ArmLeft, StandardParameter.ArmRight],
1210
+ [StandardParameter.ElbowLeft, StandardParameter.ElbowRight]
1211
+ ];
1212
+
1213
+ // src/render-page.ts
1214
+ var nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
1215
+ var settle = async () => {
1216
+ await nextFrame();
1217
+ await nextFrame();
1218
+ };
1219
+ var player;
1220
+ var canvas;
1221
+ window.__ikiRender = {
1222
+ async load(model, { canvas: size, view }) {
1223
+ canvas = document.createElement("canvas");
1224
+ canvas.style.width = `${size.width}px`;
1225
+ canvas.style.height = `${size.height}px`;
1226
+ document.body.appendChild(canvas);
1227
+ player = new IkiPlayer(canvas);
1228
+ player.start();
1229
+ const { failedTextures } = await player.load(model);
1230
+ if (view) player.setView(view);
1231
+ await settle();
1232
+ if (canvas.width !== size.width || canvas.height !== size.height) {
1233
+ throw new Error(
1234
+ `canvas is ${canvas.width}x${canvas.height}, expected ${size.width}x${size.height} (device pixel ratio?)`
1235
+ );
1236
+ }
1237
+ return { failedTextures };
1238
+ },
1239
+ async capture(values, crop) {
1240
+ if (!player || !canvas) throw new Error("capture() called before load()");
1241
+ for (const p of player.getParameters()) {
1242
+ player.setParameter(p.id, p.default);
1243
+ }
1244
+ for (const [id, value] of Object.entries(values)) {
1245
+ player.setParameter(id, value);
1246
+ }
1247
+ await settle();
1248
+ if (!crop) return canvas.toDataURL("image/png");
1249
+ const out = document.createElement("canvas");
1250
+ out.width = crop.dw;
1251
+ out.height = crop.dh;
1252
+ out.getContext("2d").drawImage(
1253
+ canvas,
1254
+ crop.sx,
1255
+ crop.sy,
1256
+ crop.sw,
1257
+ crop.sh,
1258
+ 0,
1259
+ 0,
1260
+ crop.dw,
1261
+ crop.dh
1262
+ );
1263
+ return out.toDataURL("image/png");
1264
+ }
1265
+ };
1266
+ })();