wireface 1.0.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.
package/wireface.js ADDED
@@ -0,0 +1,1447 @@
1
+ /* ============================================================================
2
+ * wireface.js — minimal embeddable lipsync face renderer
3
+ * ----------------------------------------------------------------------------
4
+ * Repository: https://github.com/styk-tv/wireface
5
+ * npm: https://www.npmjs.com/package/wireface
6
+ * Copyright (c) 2026 Peter Styk
7
+ * Released under the MIT License — see LICENSE in the repository root.
8
+ * ----------------------------------------------------------------------------
9
+ * Each call to createWireface(canvas, options) builds a fully independent
10
+ * instance: its own Babylon engine + scene, its own audio context, its own
11
+ * channel state, its own materials and meshes. Multiple instances can live on
12
+ * the same page side-by-side without sharing state.
13
+ *
14
+ * Requires: BABYLON.js loaded as a global (e.g. from cdn.babylonjs.com) BEFORE
15
+ * this script is loaded.
16
+ *
17
+ * Public API returned by createWireface:
18
+ * loadAudio(file_or_blob) → Promise<void>
19
+ * loadPreset(presetObject) → void (the JSON saved by the v010+ UI)
20
+ * setRenderConfig(partial) → void (apply one or more renderConfig fields)
21
+ * getRenderConfig() → object (snapshot of current config)
22
+ * play(fromOffset?) → void
23
+ * pause() → void
24
+ * stop() → void
25
+ * setMood(name) → void ('neutral','happy','sad','angry','fear','surprise','sleep')
26
+ * setChannel(name, value) → void (manual override, auto-releases ~1.2s)
27
+ * setChannelGain(name, gain) → void (multiplier on channel before render)
28
+ * getChannel(name) → number (current smoothed value)
29
+ * getChannelTarget(name) → number (latest target before smoothing)
30
+ * getChannelGain(name) → number
31
+ * getChannelNames() → string[]
32
+ * getMoodNames() → string[]
33
+ * setLoop(bool) → void
34
+ * setView(view) → void ('front','three-q','profile','orbit')
35
+ * isPlaying() → bool
36
+ * getDuration() → number (seconds, 0 if no audio)
37
+ * getPosition() → number (seconds since start)
38
+ * getActiveMood() → string
39
+ * dispose() → void
40
+ * ========================================================================== */
41
+
42
+ (function (global) {
43
+ 'use strict';
44
+
45
+ /* ─── module-level constants ─────────────────────────────────────────── */
46
+
47
+ const CHANNELS = {
48
+ viseme_sil: { range: [0,1], def: 1.0 }, viseme_PP: { range: [0,1], def: 0 },
49
+ viseme_FF: { range: [0,1], def: 0 }, viseme_TH: { range: [0,1], def: 0 },
50
+ viseme_DD: { range: [0,1], def: 0 }, viseme_kk: { range: [0,1], def: 0 },
51
+ viseme_CH: { range: [0,1], def: 0 }, viseme_SS: { range: [0,1], def: 0 },
52
+ viseme_nn: { range: [0,1], def: 0 }, viseme_RR: { range: [0,1], def: 0 },
53
+ viseme_aa: { range: [0,1], def: 0 }, viseme_E: { range: [0,1], def: 0 },
54
+ viseme_I: { range: [0,1], def: 0 }, viseme_O: { range: [0,1], def: 0 },
55
+ viseme_U: { range: [0,1], def: 0 },
56
+ jawOpen: { range: [0,1], def: 0 },
57
+ mouthSmile: { range: [-1,1], def: 0 },
58
+ mouthPucker: { range: [0,1], def: 0 },
59
+ eyeBlinkLeft: { range: [0,1], def: 0 },
60
+ eyeBlinkRight: { range: [0,1], def: 0 },
61
+ eyeLookH: { range: [-1,1], def: 0 },
62
+ eyeLookV: { range: [-1,1], def: 0 },
63
+ eyeSquint: { range: [0,1], def: 0 },
64
+ browInnerUp: { range: [0,1], def: 0 },
65
+ browOuterUp: { range: [-1,1], def: 0 },
66
+ browDown: { range: [0,1], def: 0 },
67
+ noseSneer: { range: [0,1], def: 0 },
68
+ headRotateX: { range: [-1,1], def: 0 },
69
+ headRotateY: { range: [-1,1], def: 0 },
70
+ headRotateZ: { range: [-1,1], def: 0 },
71
+ };
72
+ const CHANNEL_NAMES = Object.keys(CHANNELS);
73
+
74
+ const VISEME_PARAMS = {
75
+ sil: { open: 0.00, width: 0.00, round: 0.00, smile: 0.00, lipPress: 0.30, jaw: 0.00 },
76
+ PP: { open: 0.00, width: 0.00, round: 0.20, smile: 0.00, lipPress: 0.95, jaw: 0.00 },
77
+ FF: { open: 0.10, width: 0.05, round: 0.00, smile: 0.05, lipPress: 0.55, jaw: 0.10 },
78
+ TH: { open: 0.20, width: 0.15, round: 0.00, smile: 0.00, lipPress: 0.10, jaw: 0.18 },
79
+ DD: { open: 0.28, width: 0.25, round: 0.00, smile: 0.05, lipPress: 0.05, jaw: 0.25 },
80
+ kk: { open: 0.32, width: 0.20, round: 0.00, smile: 0.00, lipPress: 0.05, jaw: 0.30 },
81
+ CH: { open: 0.32, width: 0.00, round: 0.55, smile: 0.00, lipPress: 0.10, jaw: 0.25 },
82
+ SS: { open: 0.18, width: 0.45, round: 0.00, smile: 0.20, lipPress: 0.20, jaw: 0.10 },
83
+ nn: { open: 0.18, width: 0.18, round: 0.00, smile: 0.00, lipPress: 0.30, jaw: 0.18 },
84
+ RR: { open: 0.35, width: 0.00, round: 0.50, smile: 0.00, lipPress: 0.05, jaw: 0.25 },
85
+ aa: { open: 0.85, width: 0.45, round: 0.00, smile: 0.00, lipPress: 0.00, jaw: 0.85 },
86
+ E: { open: 0.50, width: 0.65, round: 0.00, smile: 0.20, lipPress: 0.00, jaw: 0.45 },
87
+ I: { open: 0.28, width: 0.85, round: 0.00, smile: 0.30, lipPress: 0.00, jaw: 0.18 },
88
+ O: { open: 0.55, width: 0.00, round: 0.75, smile: 0.00, lipPress: 0.00, jaw: 0.45 },
89
+ U: { open: 0.35, width: -0.15, round: 0.95, smile: 0.00, lipPress: 0.05, jaw: 0.25 },
90
+ };
91
+
92
+ const MOODS = {
93
+ neutral: { browInnerUp: 0, browOuterUp: 0, browDown: 0, mouthSmile: 0, eyeSquint: 0 },
94
+ happy: { browOuterUp: 0.4, mouthSmile: 0.7, eyeSquint: 0.25 },
95
+ sad: { browInnerUp: 0.7, browDown: 0.2, mouthSmile: -0.5, eyeBlinkLeft: 0.15, eyeBlinkRight: 0.15 },
96
+ angry: { browInnerUp: 0, browOuterUp: -0.4, browDown: 0.7, mouthSmile: -0.4, noseSneer: 0.5, eyeSquint: 0.4 },
97
+ fear: { browInnerUp: 0.7, browOuterUp: 0.5, mouthSmile: -0.3, eyeBlinkLeft: -0.2, eyeBlinkRight: -0.2 },
98
+ surprise:{ browInnerUp: 0.6, browOuterUp: 0.8, jawOpen: 0.5, mouthSmile: 0 },
99
+ sleep: { eyeBlinkLeft: 1, eyeBlinkRight: 1, browDown: 0.3, mouthSmile: 0 },
100
+ };
101
+ const MOOD_NAMES = Object.keys(MOODS);
102
+ const MOOD_CHANNELS = ['browInnerUp','browOuterUp','browDown','mouthSmile',
103
+ 'eyeSquint','noseSneer','eyeBlinkLeft','eyeBlinkRight'];
104
+
105
+ const SMOOTH = {
106
+ default: 0.35,
107
+ eyeBlinkLeft: 0.55, eyeBlinkRight: 0.55,
108
+ ...Object.fromEntries(Object.keys(VISEME_PARAMS).map(v => ['viseme_' + v, 0.45])),
109
+ browInnerUp: 0.18, browOuterUp: 0.18, browDown: 0.18,
110
+ headRotateX: 0.10, headRotateY: 0.10, headRotateZ: 0.10,
111
+ eyeLookH: 0.25, eyeLookV: 0.25,
112
+ };
113
+
114
+ /* SHAPES table — fields use plain arrays for direction so we don't need
115
+ BABYLON at module-init time. They're converted to Vector3 inside the
116
+ factory. */
117
+ const SHAPE_DEFS = {
118
+ mouth_jaw_drop: { uv:[0.50, 0.78], d:[ 0.00,-0.20,-0.02], r: 0.28 },
119
+ mouth_open_lower: { uv:[0.50, 0.71], d:[ 0.00,-0.10, 0.00], r: 0.16 },
120
+ mouth_open_upper: { uv:[0.50, 0.66], d:[ 0.00, 0.04, 0.00], r: 0.13 },
121
+ mouth_smile_L: { uv:[0.32, 0.69], d:[-0.06, 0.07,-0.02], r: 0.13 },
122
+ mouth_smile_R: { uv:[0.68, 0.69], d:[ 0.06, 0.07,-0.02], r: 0.13 },
123
+ mouth_frown_L: { uv:[0.32, 0.69], d:[ 0.02,-0.07, 0.00], r: 0.13 },
124
+ mouth_frown_R: { uv:[0.68, 0.69], d:[-0.02,-0.07, 0.00], r: 0.13 },
125
+ mouth_round_L: { uv:[0.32, 0.69], d:[ 0.07, 0.00, 0.03], r: 0.13 },
126
+ mouth_round_R: { uv:[0.68, 0.69], d:[-0.07, 0.00, 0.03], r: 0.13 },
127
+ mouth_round_top: { uv:[0.50, 0.66], d:[ 0.00,-0.02, 0.04], r: 0.12 },
128
+ mouth_round_bot: { uv:[0.50, 0.71], d:[ 0.00, 0.02, 0.04], r: 0.12 },
129
+ mouth_press_top: { uv:[0.50, 0.66], d:[ 0.00,-0.025,0.00], r: 0.12 },
130
+ mouth_press_bot: { uv:[0.50, 0.71], d:[ 0.00, 0.025,0.00], r: 0.12 },
131
+ mouth_width_L: { uv:[0.32, 0.69], d:[-0.05, 0.00, 0.00], r: 0.13 },
132
+ mouth_width_R: { uv:[0.68, 0.69], d:[ 0.05, 0.00, 0.00], r: 0.13 },
133
+ eye_blink_L_up: { uv:[0.30, 0.36], d:[ 0.00,-0.05,-0.02], r: 0.08 },
134
+ eye_blink_L_lo: { uv:[0.30, 0.45], d:[ 0.00, 0.03, 0.00], r: 0.08 },
135
+ eye_blink_R_up: { uv:[0.70, 0.36], d:[ 0.00,-0.05,-0.02], r: 0.08 },
136
+ eye_blink_R_lo: { uv:[0.70, 0.45], d:[ 0.00, 0.03, 0.00], r: 0.08 },
137
+ eye_squint_L: { uv:[0.30, 0.42], d:[ 0.00,-0.015,0.00], r: 0.10 },
138
+ eye_squint_R: { uv:[0.70, 0.42], d:[ 0.00,-0.015,0.00], r: 0.10 },
139
+ brow_inner_L: { uv:[0.42, 0.25], d:[ 0.00, 0.06, 0.02], r: 0.10 },
140
+ brow_inner_R: { uv:[0.58, 0.25], d:[ 0.00, 0.06, 0.02], r: 0.10 },
141
+ brow_outer_L: { uv:[0.20, 0.27], d:[ 0.00, 0.05, 0.00], r: 0.12 },
142
+ brow_outer_R: { uv:[0.80, 0.27], d:[ 0.00, 0.05, 0.00], r: 0.12 },
143
+ brow_down_L: { uv:[0.30, 0.27], d:[ 0.00,-0.05, 0.00], r: 0.14 },
144
+ brow_down_R: { uv:[0.70, 0.27], d:[ 0.00,-0.05, 0.00], r: 0.14 },
145
+ nose_sneer_L: { uv:[0.42, 0.55], d:[ 0.00, 0.03, 0.02], r: 0.08 },
146
+ nose_sneer_R: { uv:[0.58, 0.55], d:[ 0.00, 0.03, 0.02], r: 0.08 },
147
+ };
148
+
149
+ const DEFAULT_CONFIG = {
150
+ mode: 'wire', // 'wire' | 'edges' | 'shaded'
151
+ meshCols: 17,
152
+ meshRows: 21,
153
+ spread: 1.0,
154
+ reactivity: 0.25,
155
+ scaleNose: 1.0, scaleEyes: 1.0, scaleMouth: 1.0,
156
+ flipFace: true,
157
+ glow: false,
158
+ pupils: true,
159
+ fragment: true,
160
+ minimal: true,
161
+ meshVisible: true,
162
+ loopAudio: true,
163
+ mouthHole: true, mouthHoleSize: 1.0,
164
+ eyeHoles: false, eyeDepth: 1.0,
165
+ mouthAnchor: true, eyeAnchor: false,
166
+ lineThickness: 1.0,
167
+ lipVertAmp: 1.6, lipPressForce: 1.0,
168
+ overlayTracksMesh: true,
169
+ moodTransitionTime: 0.6,
170
+ lineColor: '#ffffff', pupilColor: '#ffffff',
171
+ baseColor: '#ffffff', fadeColor: '#000000', depthFade: 0.0,
172
+ irisColor: '#000000', irisSize: 1.6,
173
+ browColor: '#ffffff',
174
+ jawExtend: 0.0, mouthGrow: 0.0,
175
+ cameraView: 'three-q', // initial view
176
+ };
177
+
178
+ /* ─── module helpers ─────────────────────────────────────────────────── */
179
+
180
+ function hex2rgb(hex) {
181
+ const h = (hex || '#ffffff').replace('#', '');
182
+ return [
183
+ parseInt(h.slice(0, 2), 16) / 255,
184
+ parseInt(h.slice(2, 4), 16) / 255,
185
+ parseInt(h.slice(4, 6), 16) / 255,
186
+ ];
187
+ }
188
+
189
+ /* ──────────────────────────────────────────────────────────────────────
190
+ * F A C T O R Y
191
+ * ────────────────────────────────────────────────────────────────────── */
192
+
193
+ function createWireface(canvas, options) {
194
+ if (typeof BABYLON === 'undefined') {
195
+ throw new Error('wireface: BABYLON.js not loaded — include babylon.js before wireface.js');
196
+ }
197
+
198
+ const config = Object.assign({}, DEFAULT_CONFIG, options || {});
199
+ const V = (x, y, z) => new BABYLON.Vector3(x, y, z);
200
+
201
+ /* convert SHAPE_DEFS → SHAPES with Vector3 directions */
202
+ const SHAPES = {};
203
+ for (const k of Object.keys(SHAPE_DEFS)) {
204
+ const s = SHAPE_DEFS[k];
205
+ SHAPES[k] = { uv: s.uv, dir: V(s.d[0], s.d[1], s.d[2]), radius: s.r };
206
+ }
207
+
208
+ /* ── per-instance state ── */
209
+ const state = {};
210
+ const stateTarget = {};
211
+ const manualLock = {};
212
+ const channelGains = {};
213
+ CHANNEL_NAMES.forEach(n => {
214
+ state[n] = CHANNELS[n].def;
215
+ stateTarget[n] = CHANNELS[n].def;
216
+ channelGains[n] = 1.0;
217
+ });
218
+
219
+ const moodTargetWeights = {};
220
+ const moodCurrentWeights = {};
221
+ for (const m of MOOD_NAMES) {
222
+ moodTargetWeights[m] = 0;
223
+ moodCurrentWeights[m] = 0;
224
+ }
225
+ moodTargetWeights.neutral = 1;
226
+ moodCurrentWeights.neutral = 1;
227
+ let activeMood = 'neutral';
228
+
229
+ /* ── Babylon scene ── */
230
+ const engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: false, stencil: false, antialias: true });
231
+ const scene = new BABYLON.Scene(engine);
232
+ scene.clearColor = new BABYLON.Color4(0, 0, 0, 1);
233
+ // we never pick on pointer-move; saves a per-frame ray test
234
+ scene.skipPointerMovePicking = true;
235
+
236
+ /* glow layer — bloom on the emissive wire/overlay/iris materials. Gated by
237
+ config.glow; intensity 0 disables it. Created once and toggled, not
238
+ added/removed per frame. */
239
+ const glowLayer = new BABYLON.GlowLayer('glow', scene, { mainTextureFixedSize: 1024, blurKernelSize: 32 });
240
+ glowLayer.intensity = 0;
241
+
242
+ const camera = new BABYLON.ArcRotateCamera('cam', -Math.PI/2 - 0.6, Math.PI/2 - 0.15, 4.0, BABYLON.Vector3.Zero(), scene);
243
+ camera.minZ = 0.1; camera.maxZ = 100;
244
+ camera.lowerRadiusLimit = 1.5; camera.upperRadiusLimit = 12;
245
+ camera.wheelDeltaPercentage = 0.01;
246
+ // sandboxed iframes can throw on getGamepads — neutralize
247
+ const _origGet = navigator.getGamepads;
248
+ try { navigator.getGamepads = () => []; } catch (_) {}
249
+ camera.attachControl(canvas, true);
250
+ try { navigator.getGamepads = _origGet; } catch (_) {}
251
+
252
+ const hemi = new BABYLON.HemisphericLight('h', new BABYLON.Vector3(0, 1, 0), scene);
253
+ hemi.intensity = 0.9;
254
+ hemi.groundColor = new BABYLON.Color3(0.10, 0.10, 0.14);
255
+
256
+ const faceRoot = new BABYLON.TransformNode('faceRoot', scene);
257
+
258
+ /* ── materials ── */
259
+ const faceMat = new BABYLON.StandardMaterial('faceMat', scene);
260
+ faceMat.diffuseColor = new BABYLON.Color3(0.05, 0.05, 0.07);
261
+ faceMat.emissiveColor = new BABYLON.Color3(0.012, 0.012, 0.020);
262
+ faceMat.specularColor = new BABYLON.Color3(0.20, 0.22, 0.28);
263
+ faceMat.specularPower = 48;
264
+ faceMat.backFaceCulling = false;
265
+ faceMat.useVertexColor = true;
266
+
267
+ const wireMat = new BABYLON.StandardMaterial('wireMat', scene);
268
+ wireMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
269
+ wireMat.disableLighting = true;
270
+ wireMat.wireframe = true;
271
+ wireMat.backFaceCulling = false;
272
+ wireMat.alpha = 1;
273
+ wireMat.useVertexColor = true;
274
+
275
+ const minimalMat = new BABYLON.StandardMaterial('minimalMat', scene);
276
+ minimalMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
277
+ minimalMat.disableLighting = true;
278
+ minimalMat.specularColor = new BABYLON.Color3(0, 0, 0);
279
+
280
+ const browMat = new BABYLON.StandardMaterial('browMat', scene);
281
+ browMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
282
+ browMat.disableLighting = true;
283
+ browMat.specularColor = new BABYLON.Color3(0, 0, 0);
284
+
285
+ const minimalGroup = new BABYLON.TransformNode('minimal', scene);
286
+ minimalGroup.parent = faceRoot;
287
+
288
+ /* ─── 4a. parametric warp (u,v) → 3D face surface ─── */
289
+ function warpToFace(u, v) {
290
+ const xRel = (u - 0.5) * 2;
291
+ const yRel = (0.5 - v) * 2;
292
+ const yNorm = yRel * 0.95;
293
+ const ovalT = Math.max(0, 1 - yNorm * yNorm);
294
+ const x = xRel * Math.sqrt(ovalT) * 0.80;
295
+ const y = yRel * 0.95;
296
+ let z = (Math.cos(xRel * Math.PI * 0.5)) * (Math.cos(yRel * Math.PI * 0.5)) * 0.18;
297
+ // nose ridge
298
+ const nU = 0.50, nV = 0.50;
299
+ const dn = Math.hypot((u-nU), (v-nV)) / 0.16;
300
+ if (dn < 1.6) z += (1 - Math.min(1, dn)) * 0.085;
301
+ // brow ridge
302
+ const dbL = Math.hypot((u-0.30), (v-0.27)) / 0.10;
303
+ const dbR = Math.hypot((u-0.70), (v-0.27)) / 0.10;
304
+ if (dbL < 1.6) z += (1 - Math.min(1, dbL)) * 0.020;
305
+ if (dbR < 1.6) z += (1 - Math.min(1, dbR)) * 0.020;
306
+ // eye sockets recess
307
+ const deL = Math.hypot((u-0.30)/0.085, (v-0.40)/0.045);
308
+ const deR = Math.hypot((u-0.70)/0.085, (v-0.40)/0.045);
309
+ if (deL < 1.5) z -= (1 - Math.min(1, deL)) * 0.030 * config.eyeDepth;
310
+ if (deR < 1.5) z -= (1 - Math.min(1, deR)) * 0.030 * config.eyeDepth;
311
+ // chin protrusion
312
+ if (v > 0.85) z += (v - 0.85) * 0.6 * 0.10 * Math.max(0, 1 - Math.abs(xRel) * 1.2);
313
+ // cheek bulge
314
+ const cheekL = Math.hypot((u-0.22)/0.10, (v-0.62)/0.08);
315
+ const cheekR = Math.hypot((u-0.78)/0.10, (v-0.62)/0.08);
316
+ if (cheekL < 1.6) z += (1 - Math.min(1, cheekL)) * 0.018;
317
+ if (cheekR < 1.6) z += (1 - Math.min(1, cheekR)) * 0.018;
318
+ return V(x, y, z);
319
+ }
320
+
321
+ /* mouth center constants */
322
+ const mouthCenterUV = warpToFace(0.50, 0.69);
323
+ const mouthBaseHW = 0.27;
324
+
325
+ /* lip target — SAME formula used by both the bezier overlay and the mesh
326
+ anchor pass so they animate identically */
327
+ function lipTarget(xRel, isUpper, p) {
328
+ const cx = mouthCenterUV.x, cy = mouthCenterUV.y, cz = mouthCenterUV.z;
329
+ const hw = mouthBaseHW * (1 + p.width * 0.40) * (1 - p.round * 0.40);
330
+ const vAmp = config.lipVertAmp;
331
+ const closeF = config.lipPressForce;
332
+ const sep = p.open * 0.16 * vAmp;
333
+ const compress = p.lipPress * 0.012 * vAmp * closeF;
334
+ const jawDrop = p.jaw * 0.09 * vAmp;
335
+ const smileLift = p.smile * 0.05;
336
+ const roundFwd = p.round * 0.07;
337
+ const upperDip = 0.007 * (1 - p.lipPress * 0.55);
338
+ const lowerDip = 0.022 * (1 - p.lipPress * 0.55);
339
+ let cp;
340
+ if (isUpper) {
341
+ const upperY = cy + sep / 2 - compress + smileLift * 0.4;
342
+ cp = [
343
+ [-1.00, cy + smileLift, -roundFwd * 0.5],
344
+ [-0.45, upperY + 0.012, 0.012],
345
+ [ 0.00, upperY - upperDip, 0.018 + roundFwd],
346
+ [ 0.45, upperY + 0.012, 0.012],
347
+ [ 1.00, cy + smileLift, -roundFwd * 0.5],
348
+ ];
349
+ } else {
350
+ const lowerY = cy - sep / 2 + compress - jawDrop;
351
+ cp = [
352
+ [-1.00, cy + smileLift, -roundFwd * 0.5],
353
+ [-0.50, lowerY - 0.005, 0.014],
354
+ [ 0.00, lowerY - lowerDip, 0.022 + roundFwd * 1.1],
355
+ [ 0.50, lowerY - 0.005, 0.014],
356
+ [ 1.00, cy + smileLift, -roundFwd * 0.5],
357
+ ];
358
+ }
359
+ xRel = Math.max(-1, Math.min(1, xRel));
360
+ let i = 0;
361
+ while (i < cp.length - 1 && xRel > cp[i + 1][0]) i++;
362
+ i = Math.min(i, cp.length - 2);
363
+ const t = (xRel - cp[i][0]) / (cp[i + 1][0] - cp[i][0]);
364
+ const yT = cp[i][1] * (1 - t) + cp[i + 1][1] * t;
365
+ const zO = cp[i][2] * (1 - t) + cp[i + 1][2] * t;
366
+ return V(cx + xRel * hw, yT, cz + zO);
367
+ }
368
+
369
+ function eyeLidTargetFor(xRel, isUpper, eyeDef, blink, squint) {
370
+ const a = ((xRel + 1) / 2) * Math.PI;
371
+ const x = eyeDef.center.x + Math.cos(Math.PI - a) * eyeDef.hw;
372
+ const baseY = eyeDef.center.y + (isUpper ? 1 : -1) * Math.sin(a) * eyeDef.hh;
373
+ const y = baseY * (1 - blink) + eyeDef.center.y * blink;
374
+ const squintShift = squint * 0.012;
375
+ const yWithSquint = y + (isUpper ? -squintShift : squintShift * 0.5);
376
+ const z = eyeDef.center.z + 0.018 + Math.sin(a) * 0.012;
377
+ return V(x, yWithSquint, z);
378
+ }
379
+
380
+ /* ── viseme aggregator ── */
381
+ function computeMouthParams() {
382
+ let totalW = 0;
383
+ const out = { open: 0, width: 0, round: 0, smile: 0, lipPress: 0, jaw: 0 };
384
+ for (const v of Object.keys(VISEME_PARAMS)) {
385
+ const w = state['viseme_' + v] || 0;
386
+ if (w <= 0) continue;
387
+ totalW += w;
388
+ const p = VISEME_PARAMS[v];
389
+ out.open += p.open * w; out.width += p.width * w; out.round += p.round * w;
390
+ out.smile += p.smile * w; out.lipPress += p.lipPress * w; out.jaw += p.jaw * w;
391
+ }
392
+ if (totalW > 1) {
393
+ const k = 1 / totalW;
394
+ out.open *= k; out.width *= k; out.round *= k;
395
+ out.smile *= k; out.lipPress *= k; out.jaw *= k;
396
+ }
397
+ out.smile += state.mouthSmile;
398
+ const pucker = state.mouthPucker;
399
+ out.round += pucker * 0.7; out.width += -pucker * 0.4;
400
+ out.open += state.jawOpen * 0.6;
401
+ out.jaw += state.jawOpen * 0.7;
402
+ return out;
403
+ }
404
+
405
+ /* ── mesh state (per instance) ── */
406
+ let mesh = null;
407
+ let baseVertices = [];
408
+ let baseUVs = [];
409
+ let triIndices = [];
410
+ let adjacency = [];
411
+ let _dispBuf = null, _posBuf = null, _normBuf = null, _colBuf = null;
412
+ let _zMin = 0, _zMax = 0;
413
+ let _baseRGB = [1,1,1], _fadeRGB = [0,0,0];
414
+ let _dirtyBaseColor = false;
415
+
416
+ let mouthRingVerts = [];
417
+ let eyeRingVerts = [];
418
+
419
+ const NEUTRAL_MOUTH = { open: 0, width: 0, round: 0, smile: 0, lipPress: 0.30, jaw: 0 };
420
+
421
+ function computeAdjacency(tris, n) {
422
+ const adj = Array.from({ length: n }, () => new Set());
423
+ for (let i = 0; i < tris.length; i += 3) {
424
+ const a = tris[i], b = tris[i+1], c = tris[i+2];
425
+ adj[a].add(b); adj[a].add(c);
426
+ adj[b].add(a); adj[b].add(c);
427
+ adj[c].add(a); adj[c].add(b);
428
+ }
429
+ return adj.map(s => Array.from(s));
430
+ }
431
+
432
+ function rebuildMesh() {
433
+ if (mesh) { mesh.dispose(); mesh = null; }
434
+ const cols = config.meshCols;
435
+ const rows = config.meshRows;
436
+ baseVertices = []; baseUVs = []; triIndices = [];
437
+ for (let r = 0; r < rows; r++) {
438
+ for (let c = 0; c < cols; c++) {
439
+ const u = c / (cols - 1);
440
+ const v = r / (rows - 1);
441
+ baseUVs.push({ u, v });
442
+ baseVertices.push(warpToFace(u, v));
443
+ }
444
+ }
445
+ // optional oval clip
446
+ const passes = (i) => {
447
+ if (!config.fragment) return true;
448
+ const u = baseUVs[i].u, v = baseUVs[i].v;
449
+ const xRel = (u - 0.5) * 2;
450
+ const yRel = (0.5 - v) * 2;
451
+ return (xRel * xRel * 1.2 + yRel * yRel * 0.95) < 1.0;
452
+ };
453
+ const insideHole = (i, cu, cv, ru, rv) => {
454
+ const du = (baseUVs[i].u - cu) / ru;
455
+ const dv = (baseUVs[i].v - cv) / rv;
456
+ return du*du + dv*dv < 1;
457
+ };
458
+ const triAllowed = (a, b, c) => {
459
+ if (!passes(a) || !passes(b) || !passes(c)) return false;
460
+ if (config.mouthHole) {
461
+ const cu = 0.50, cv = 0.69;
462
+ const ru = 0.18 * config.mouthHoleSize, rv = 0.075 * config.mouthHoleSize;
463
+ // skip if centroid is inside the mouth ellipse
464
+ const ucen = (baseUVs[a].u + baseUVs[b].u + baseUVs[c].u) / 3;
465
+ const vcen = (baseUVs[a].v + baseUVs[b].v + baseUVs[c].v) / 3;
466
+ const du = (ucen - cu) / ru, dv = (vcen - cv) / rv;
467
+ if (du*du + dv*dv < 1) return false;
468
+ }
469
+ if (config.eyeHoles) {
470
+ const ucen = (baseUVs[a].u + baseUVs[b].u + baseUVs[c].u) / 3;
471
+ const vcen = (baseUVs[a].v + baseUVs[b].v + baseUVs[c].v) / 3;
472
+ const dl = ((ucen-0.30)/0.085)**2 + ((vcen-0.40)/0.045)**2;
473
+ const dr = ((ucen-0.70)/0.085)**2 + ((vcen-0.40)/0.045)**2;
474
+ if (dl < 1 || dr < 1) return false;
475
+ }
476
+ return true;
477
+ };
478
+ const maybeAdd = (a, b, c) => { if (triAllowed(a,b,c)) triIndices.push(a, b, c); };
479
+ for (let r = 0; r < rows - 1; r++) {
480
+ for (let c = 0; c < cols - 1; c++) {
481
+ const i00 = r*cols + c, i10 = r*cols + (c+1);
482
+ const i01 = (r+1)*cols + c, i11 = (r+1)*cols + (c+1);
483
+ if ((r + c) % 2 === 0) { maybeAdd(i00, i10, i11); maybeAdd(i00, i11, i01); }
484
+ else { maybeAdd(i00, i10, i01); maybeAdd(i10, i11, i01); }
485
+ }
486
+ }
487
+ adjacency = computeAdjacency(triIndices, baseVertices.length);
488
+ mesh = new BABYLON.Mesh('face', scene);
489
+ mesh.parent = faceRoot;
490
+ const N = baseVertices.length;
491
+ _posBuf = new Float32Array(N * 3);
492
+ _normBuf = new Float32Array(N * 3);
493
+ _colBuf = new Float32Array(N * 4);
494
+ _dispBuf = new Array(N);
495
+ _zMin = +Infinity; _zMax = -Infinity;
496
+ for (let i = 0; i < N; i++) {
497
+ _posBuf[3*i] = baseVertices[i].x;
498
+ _posBuf[3*i+1] = baseVertices[i].y;
499
+ _posBuf[3*i+2] = baseVertices[i].z;
500
+ if (baseVertices[i].z < _zMin) _zMin = baseVertices[i].z;
501
+ if (baseVertices[i].z > _zMax) _zMax = baseVertices[i].z;
502
+ _dispBuf[i] = V(0, 0, 0);
503
+ _colBuf[4*i] = 1; _colBuf[4*i+1] = 1; _colBuf[4*i+2] = 1; _colBuf[4*i+3] = 1;
504
+ }
505
+ BABYLON.VertexData.ComputeNormals(_posBuf, triIndices, _normBuf);
506
+ const vd = new BABYLON.VertexData();
507
+ vd.positions = Array.from(_posBuf);
508
+ vd.indices = triIndices;
509
+ vd.normals = Array.from(_normBuf);
510
+ vd.colors = Array.from(_colBuf);
511
+ vd.applyToMesh(mesh, true);
512
+ applyRenderMode(); applyFaceFlip(); applyMeshVisibility();
513
+ identifyAnchorRings();
514
+ _dirtyBaseColor = true;
515
+ }
516
+
517
+ function identifyAnchorRings() {
518
+ mouthRingVerts = []; eyeRingVerts = [];
519
+ const mRU = 0.18 * config.mouthHoleSize;
520
+ const mRV = 0.075 * config.mouthHoleSize;
521
+ const mCU = 0.50, mCV = 0.69;
522
+ for (let i = 0; i < baseUVs.length; i++) {
523
+ const du = (baseUVs[i].u - mCU) / mRU;
524
+ const dv = (baseUVs[i].v - mCV) / mRV;
525
+ const d2 = du*du + dv*dv;
526
+ if (d2 < 4) {
527
+ const isUpper = baseUVs[i].v < mCV;
528
+ const xRel = Math.max(-1, Math.min(1, du));
529
+ let weight = (d2 <= 1) ? d2 : (4 - d2) / 3;
530
+ weight = Math.max(0, Math.min(1, weight));
531
+ mouthRingVerts.push({
532
+ idx: i, isUpper, xRel, weight,
533
+ baselineTarget: lipTarget(xRel, isUpper, NEUTRAL_MOUTH)
534
+ });
535
+ }
536
+ }
537
+ const eyeRingDef = [
538
+ { side: 'L', cu: 0.30, cv: 0.40, ru: 0.085, rv: 0.045, hw: 0.10, hh: 0.040 },
539
+ { side: 'R', cu: 0.70, cv: 0.40, ru: 0.085, rv: 0.045, hw: 0.10, hh: 0.040 },
540
+ ];
541
+ for (const e of eyeRingDef) {
542
+ for (let i = 0; i < baseUVs.length; i++) {
543
+ const du = (baseUVs[i].u - e.cu) / e.ru;
544
+ const dv = (baseUVs[i].v - e.cv) / e.rv;
545
+ const d2 = du*du + dv*dv;
546
+ if (d2 < 4) {
547
+ const isUpper = baseUVs[i].v < e.cv;
548
+ const xRel = Math.max(-1, Math.min(1, du));
549
+ let weight = (d2 <= 1) ? d2 : (4 - d2) / 3;
550
+ weight = Math.max(0, Math.min(1, weight));
551
+ const center = warpToFace(e.cu, e.cv);
552
+ eyeRingVerts.push({
553
+ idx: i, side: e.side, isUpper, xRel, weight,
554
+ eyeDef: { center, hw: e.hw, hh: e.hh },
555
+ baselineTarget: eyeLidTargetFor(xRel, isUpper, { center, hw: e.hw, hh: e.hh }, 0, 0)
556
+ });
557
+ }
558
+ }
559
+ }
560
+ }
561
+
562
+ /* ── displacement passes ── */
563
+ function applyShape(disp, shape, weight, spread) {
564
+ if (Math.abs(weight) < 0.001) return;
565
+ const cu = shape.uv[0], cv = shape.uv[1];
566
+ const r = shape.radius * spread;
567
+ const r2 = r * r;
568
+ const dx = shape.dir.x * weight, dy = shape.dir.y * weight, dz = shape.dir.z * weight;
569
+ for (let i = 0; i < baseUVs.length; i++) {
570
+ const du = baseUVs[i].u - cu;
571
+ const dv = baseUVs[i].v - cv;
572
+ const d2 = du*du + dv*dv;
573
+ if (d2 > 4 * r2) continue;
574
+ const w = Math.exp(-d2 / r2);
575
+ disp[i].x += dx * w; disp[i].y += dy * w; disp[i].z += dz * w;
576
+ }
577
+ }
578
+
579
+ function computeMorphs(disp) {
580
+ const spread = config.spread;
581
+ const p = computeMouthParams();
582
+ // mouth
583
+ applyShape(disp, SHAPES.mouth_jaw_drop, p.jaw, spread);
584
+ applyShape(disp, SHAPES.mouth_open_lower, p.open, spread);
585
+ applyShape(disp, SHAPES.mouth_open_upper, p.open, spread);
586
+ const sm = p.smile;
587
+ if (sm > 0) { applyShape(disp, SHAPES.mouth_smile_L, sm, spread); applyShape(disp, SHAPES.mouth_smile_R, sm, spread); }
588
+ else if (sm < 0) { applyShape(disp, SHAPES.mouth_frown_L, -sm, spread); applyShape(disp, SHAPES.mouth_frown_R, -sm, spread); }
589
+ applyShape(disp, SHAPES.mouth_round_L, p.round, spread);
590
+ applyShape(disp, SHAPES.mouth_round_R, p.round, spread);
591
+ applyShape(disp, SHAPES.mouth_round_top, p.round, spread);
592
+ applyShape(disp, SHAPES.mouth_round_bot, p.round, spread);
593
+ applyShape(disp, SHAPES.mouth_press_top, p.lipPress, spread);
594
+ applyShape(disp, SHAPES.mouth_press_bot, p.lipPress, spread);
595
+ if (p.width > 0) {
596
+ applyShape(disp, SHAPES.mouth_width_L, p.width, spread);
597
+ applyShape(disp, SHAPES.mouth_width_R, p.width, spread);
598
+ }
599
+ // eyes
600
+ applyShape(disp, SHAPES.eye_blink_L_up, state.eyeBlinkLeft, spread);
601
+ applyShape(disp, SHAPES.eye_blink_L_lo, state.eyeBlinkLeft, spread);
602
+ applyShape(disp, SHAPES.eye_blink_R_up, state.eyeBlinkRight, spread);
603
+ applyShape(disp, SHAPES.eye_blink_R_lo, state.eyeBlinkRight, spread);
604
+ applyShape(disp, SHAPES.eye_squint_L, state.eyeSquint, spread);
605
+ applyShape(disp, SHAPES.eye_squint_R, state.eyeSquint, spread);
606
+ // brows
607
+ applyShape(disp, SHAPES.brow_inner_L, state.browInnerUp, spread);
608
+ applyShape(disp, SHAPES.brow_inner_R, state.browInnerUp, spread);
609
+ applyShape(disp, SHAPES.brow_outer_L, Math.max(0, state.browOuterUp), spread);
610
+ applyShape(disp, SHAPES.brow_outer_R, Math.max(0, state.browOuterUp), spread);
611
+ applyShape(disp, SHAPES.brow_down_L, state.browDown + Math.max(0,-state.browOuterUp), spread);
612
+ applyShape(disp, SHAPES.brow_down_R, state.browDown + Math.max(0,-state.browOuterUp), spread);
613
+ // nose
614
+ applyShape(disp, SHAPES.nose_sneer_L, state.noseSneer, spread);
615
+ applyShape(disp, SHAPES.nose_sneer_R, state.noseSneer, spread);
616
+ }
617
+
618
+ function couple(disp, factor) {
619
+ if (factor <= 0) return;
620
+ const N = disp.length;
621
+ const out = new Array(N);
622
+ for (let i = 0; i < N; i++) {
623
+ const adj = adjacency[i];
624
+ if (adj.length === 0) { out[i] = V(disp[i].x, disp[i].y, disp[i].z); continue; }
625
+ let sx = 0, sy = 0, sz = 0;
626
+ for (const j of adj) { sx += disp[j].x; sy += disp[j].y; sz += disp[j].z; }
627
+ sx /= adj.length; sy /= adj.length; sz /= adj.length;
628
+ out[i] = V(
629
+ disp[i].x * (1 - factor) + sx * factor,
630
+ disp[i].y * (1 - factor) + sy * factor,
631
+ disp[i].z * (1 - factor) + sz * factor,
632
+ );
633
+ }
634
+ for (let i = 0; i < N; i++) { disp[i].x = out[i].x; disp[i].y = out[i].y; disp[i].z = out[i].z; }
635
+ }
636
+
637
+ const FEATURE_CENTERS = [
638
+ { name: 'nose', uv: [0.50, 0.50], radiusUV: 0.16, get scale() { return config.scaleNose; } },
639
+ { name: 'eyeL', uv: [0.30, 0.40], radiusUV: 0.11, get scale() { return config.scaleEyes; } },
640
+ { name: 'eyeR', uv: [0.70, 0.40], radiusUV: 0.11, get scale() { return config.scaleEyes; } },
641
+ { name: 'mouth', uv: [0.50, 0.70], radiusUV: 0.18, get scale() { return config.scaleMouth; } },
642
+ ];
643
+
644
+ function applyFeatureScales(disp) {
645
+ for (const f of FEATURE_CENTERS) {
646
+ const s = f.scale;
647
+ if (Math.abs(s - 1) < 0.001) continue;
648
+ const center = warpToFace(f.uv[0], f.uv[1]);
649
+ const r2 = f.radiusUV * f.radiusUV;
650
+ const cutoff = r2 * 4;
651
+ for (let i = 0; i < baseUVs.length; i++) {
652
+ const du = baseUVs[i].u - f.uv[0];
653
+ const dv = baseUVs[i].v - f.uv[1];
654
+ const d2 = du*du + dv*dv;
655
+ if (d2 > cutoff) continue;
656
+ const w = Math.exp(-d2 / r2);
657
+ const ox = baseVertices[i].x - center.x;
658
+ const oy = baseVertices[i].y - center.y;
659
+ const oz = baseVertices[i].z - center.z;
660
+ const k = (s - 1) * w;
661
+ disp[i].x += ox * k; disp[i].y += oy * k; disp[i].z += oz * k;
662
+ }
663
+ }
664
+ }
665
+
666
+ function applyJawExtension(disp) {
667
+ const amt = config.jawExtend;
668
+ if (amt < 0.001) return;
669
+ const open = state.jawOpen || 0;
670
+ if (open < 0.001) return;
671
+ const push = open * amt * 0.10;
672
+ for (let i = 0; i < baseUVs.length; i++) {
673
+ const v = baseUVs[i].v;
674
+ if (v < 0.55) continue;
675
+ const w = Math.min(1, (v - 0.55) / 0.45);
676
+ disp[i].z += push * w;
677
+ }
678
+ }
679
+
680
+ function applyMouthGrow(disp) {
681
+ const amt = config.mouthGrow;
682
+ if (amt < 0.001) return;
683
+ const p = computeMouthParams();
684
+ const openness = p.open;
685
+ if (openness < 0.001) return;
686
+ const scale = openness * amt;
687
+ const r = 0.25, r2 = r * r;
688
+ const cu = 0.50, cv = 0.69;
689
+ for (let i = 0; i < baseUVs.length; i++) {
690
+ const du = baseUVs[i].u - cu;
691
+ const dv = baseUVs[i].v - cv;
692
+ const d2 = du*du + dv*dv;
693
+ if (d2 > r2) continue;
694
+ const w = 1 - Math.sqrt(d2 / r2);
695
+ const base = baseVertices[i];
696
+ disp[i].x += (base.x - mouthCenterUV.x) * scale * w * 0.40;
697
+ disp[i].y += (base.y - mouthCenterUV.y) * scale * w * 0.40;
698
+ disp[i].z += scale * w * 0.05;
699
+ }
700
+ }
701
+
702
+ function applyMouthAnchors(disp) {
703
+ if (!config.mouthAnchor) return;
704
+ const p = computeMouthParams();
705
+ for (const v of mouthRingVerts) {
706
+ const target = lipTarget(v.xRel, v.isUpper, p);
707
+ const dx = target.x - v.baselineTarget.x;
708
+ const dy = target.y - v.baselineTarget.y;
709
+ const dz = target.z - v.baselineTarget.z;
710
+ const w = v.weight;
711
+ disp[v.idx].x = disp[v.idx].x * (1 - w) + dx * w;
712
+ disp[v.idx].y = disp[v.idx].y * (1 - w) + dy * w;
713
+ disp[v.idx].z = disp[v.idx].z * (1 - w) + dz * w;
714
+ }
715
+ }
716
+
717
+ function applyEyeAnchors(disp) {
718
+ if (!config.eyeAnchor) return;
719
+ const blinkL = state.eyeBlinkLeft, blinkR = state.eyeBlinkRight;
720
+ const squint = state.eyeSquint;
721
+ for (const v of eyeRingVerts) {
722
+ const blink = v.side === 'L' ? blinkL : blinkR;
723
+ const target = eyeLidTargetFor(v.xRel, v.isUpper, v.eyeDef, blink, squint);
724
+ const dx = target.x - v.baselineTarget.x;
725
+ const dy = target.y - v.baselineTarget.y;
726
+ const dz = target.z - v.baselineTarget.z;
727
+ const w = v.weight;
728
+ disp[v.idx].x = disp[v.idx].x * (1 - w) + dx * w;
729
+ disp[v.idx].y = disp[v.idx].y * (1 - w) + dy * w;
730
+ disp[v.idx].z = disp[v.idx].z * (1 - w) + dz * w;
731
+ }
732
+ }
733
+
734
+ function applyFaceFlip() {
735
+ if (faceRoot) faceRoot.rotation.y = config.flipFace ? Math.PI : 0;
736
+ }
737
+ function applyMeshVisibility() {
738
+ if (mesh) mesh.isVisible = !!config.meshVisible;
739
+ }
740
+ function applyMinimalVisibility() {
741
+ if (minimalGroup) {
742
+ minimalGroup.getChildMeshes().forEach(m => m.isVisible = !!config.minimal);
743
+ }
744
+ }
745
+ function applyRenderMode() {
746
+ if (!mesh) return;
747
+ if (mesh._edgesRenderer) mesh.disableEdgesRendering();
748
+ const w = config.lineThickness;
749
+ switch (config.mode) {
750
+ case 'wire':
751
+ mesh.material = wireMat;
752
+ wireMat.wireframe = true;
753
+ wireMat.alpha = 1.0;
754
+ break;
755
+ case 'edges':
756
+ mesh.material = faceMat;
757
+ faceMat.alpha = 1.0;
758
+ faceMat.wireframe = false;
759
+ mesh.enableEdgesRendering(0.9999);
760
+ mesh.edgesWidth = 4 * w;
761
+ mesh.edgesColor = new BABYLON.Color4(_baseRGB[0], _baseRGB[1], _baseRGB[2], 1);
762
+ break;
763
+ case 'shaded':
764
+ mesh.material = faceMat;
765
+ faceMat.alpha = 1.0;
766
+ faceMat.wireframe = false;
767
+ break;
768
+ }
769
+ }
770
+
771
+ /* ── pupils + iris ── */
772
+ let pupilMat = null, pupilL = null, pupilR = null;
773
+ let irisMat = null, irisL = null, irisR = null;
774
+
775
+ function rebuildPupils() {
776
+ if (pupilL) { pupilL.dispose(); pupilL = null; }
777
+ if (pupilR) { pupilR.dispose(); pupilR = null; }
778
+ if (irisL) { irisL.dispose(); irisL = null; }
779
+ if (irisR) { irisR.dispose(); irisR = null; }
780
+ if (!config.pupils) return;
781
+ if (!pupilMat) {
782
+ pupilMat = new BABYLON.StandardMaterial('pupilMat', scene);
783
+ pupilMat.emissiveColor = BABYLON.Color3.FromHexString(config.pupilColor);
784
+ pupilMat.disableLighting = true;
785
+ pupilMat.backFaceCulling = false;
786
+ }
787
+ if (!irisMat) {
788
+ irisMat = new BABYLON.StandardMaterial('irisMat', scene);
789
+ irisMat.emissiveColor = BABYLON.Color3.FromHexString(config.irisColor);
790
+ irisMat.disableLighting = true;
791
+ irisMat.backFaceCulling = false;
792
+ }
793
+ const irisRsize = 0.035 * config.irisSize;
794
+ irisL = BABYLON.MeshBuilder.CreateDisc('irisL', { radius: irisRsize, tessellation: 24 }, scene);
795
+ irisR = BABYLON.MeshBuilder.CreateDisc('irisR', { radius: irisRsize, tessellation: 24 }, scene);
796
+ irisL.material = irisR.material = irisMat;
797
+ irisL.parent = irisR.parent = faceRoot;
798
+ pupilL = BABYLON.MeshBuilder.CreateDisc('pupilL', { radius: 0.035, tessellation: 14 }, scene);
799
+ pupilR = BABYLON.MeshBuilder.CreateDisc('pupilR', { radius: 0.035, tessellation: 14 }, scene);
800
+ pupilL.material = pupilR.material = pupilMat;
801
+ pupilL.parent = pupilR.parent = faceRoot;
802
+ }
803
+
804
+ function updatePupils() {
805
+ if (!pupilL || !pupilR) return;
806
+ const lookH = state.eyeLookH * 0.05;
807
+ const lookV = state.eyeLookV * 0.035;
808
+ const eyeL = warpToFace(0.30, 0.40);
809
+ const eyeR = warpToFace(0.70, 0.40);
810
+ if (irisL && irisR) {
811
+ irisL.position.set(eyeL.x + lookH * 0.6, eyeL.y + lookV * 0.6, eyeL.z + 0.045);
812
+ irisR.position.set(eyeR.x + lookH * 0.6, eyeR.y + lookV * 0.6, eyeR.z + 0.045);
813
+ }
814
+ pupilL.position.set(eyeL.x + lookH, eyeL.y + lookV, eyeL.z + 0.05);
815
+ pupilR.position.set(eyeR.x + lookH, eyeR.y + lookV, eyeR.z + 0.05);
816
+ const blink = (state.eyeBlinkLeft + state.eyeBlinkRight) * 0.5;
817
+ pupilL.isVisible = pupilR.isVisible = blink < 0.85;
818
+ if (irisL && irisR) irisL.isVisible = irisR.isVisible = blink < 0.85;
819
+ }
820
+
821
+ /* ── minimal-line overlay ── */
822
+ function sampleDispAtUV(u, v) {
823
+ if (!_dispBuf) return V(0, 0, 0);
824
+ const r2 = 0.06 * 0.06;
825
+ let totalW = 0, sx = 0, sy = 0, sz = 0;
826
+ for (let i = 0; i < baseUVs.length; i++) {
827
+ const du = baseUVs[i].u - u, dv = baseUVs[i].v - v;
828
+ const d2 = du*du + dv*dv;
829
+ if (d2 < r2) {
830
+ const w = 1 - Math.sqrt(d2 / r2);
831
+ totalW += w;
832
+ sx += _dispBuf[i].x * w; sy += _dispBuf[i].y * w; sz += _dispBuf[i].z * w;
833
+ }
834
+ }
835
+ if (totalW === 0) return V(0, 0, 0);
836
+ return V(sx/totalW, sy/totalW, sz/totalW);
837
+ }
838
+ function deformedPoint(u, v) {
839
+ const base = warpToFace(u, v);
840
+ if (!config.overlayTracksMesh) return base;
841
+ const d = sampleDispAtUV(u, v);
842
+ return V(base.x + d.x, base.y + d.y, base.z + d.z);
843
+ }
844
+
845
+ function smoothPath(controls, samples = 18) {
846
+ const out = [];
847
+ const N = controls.length;
848
+ const get = i => controls[Math.max(0, Math.min(N - 1, i))];
849
+ for (let i = 0; i < N - 1; i++) {
850
+ const p0 = get(i - 1), p1 = get(i), p2 = get(i + 1), p3 = get(i + 2);
851
+ for (let s = 0; s < samples; s++) {
852
+ const t = s / samples;
853
+ const t2 = t*t, t3 = t*t2;
854
+ const x = 0.5 * ((2*p1.x) + (-p0.x + p2.x)*t + (2*p0.x - 5*p1.x + 4*p2.x - p3.x)*t2 + (-p0.x + 3*p1.x - 3*p2.x + p3.x)*t3);
855
+ const y = 0.5 * ((2*p1.y) + (-p0.y + p2.y)*t + (2*p0.y - 5*p1.y + 4*p2.y - p3.y)*t2 + (-p0.y + 3*p1.y - 3*p2.y + p3.y)*t3);
856
+ const z = 0.5 * ((2*p1.z) + (-p0.z + p2.z)*t + (2*p0.z - 5*p1.z + 4*p2.z - p3.z)*t2 + (-p0.z + 3*p1.z - 3*p2.z + p3.z)*t3);
857
+ out.push(V(x, y, z));
858
+ }
859
+ }
860
+ out.push(controls[N - 1]);
861
+ return out;
862
+ }
863
+
864
+ function makeTube(name, points, radius, instance) {
865
+ const r = instance ? radius : radius * config.lineThickness;
866
+ const opts = { path: points, radius: r, tessellation: 6, updatable: true };
867
+ if (instance) opts.instance = instance;
868
+ const tube = BABYLON.MeshBuilder.CreateTube(name, opts, scene);
869
+ if (!instance) { tube.material = minimalMat; tube.parent = minimalGroup; }
870
+ return tube;
871
+ }
872
+
873
+ let mouthUpperMesh = null, mouthLowerMesh = null;
874
+ function mouthLipPaths() {
875
+ const p = computeMouthParams();
876
+ const upperXR = [-1.0, -0.45, 0.0, 0.45, 1.0];
877
+ const lowerXR = [-1.0, -0.5, 0.0, 0.5, 1.0];
878
+ const upper = smoothPath(upperXR.map(x => lipTarget(x, true, p)), 18);
879
+ const lower = smoothPath(lowerXR.map(x => lipTarget(x, false, p)), 18);
880
+ return { upper, lower };
881
+ }
882
+
883
+ const eyeData = [
884
+ { side: 'L', uv: [0.30, 0.40], hw: 0.10, hh: 0.040 },
885
+ { side: 'R', uv: [0.70, 0.40], hw: 0.10, hh: 0.040 },
886
+ ];
887
+ let eyeMeshes = [];
888
+ function eyePath(eye, isUpper) {
889
+ const blink = eye.side === 'L' ? state.eyeBlinkLeft : state.eyeBlinkRight;
890
+ const squint = state.eyeSquint;
891
+ const center = deformedPoint(eye.uv[0], eye.uv[1]);
892
+ const N = 12, pts = [], squintShift = squint * 0.012;
893
+ for (let i = 0; i <= N; i++) {
894
+ const t = i / N, a = t * Math.PI;
895
+ const x = center.x + Math.cos(Math.PI - a) * eye.hw;
896
+ const baseY = center.y + (isUpper ? 1 : -1) * Math.sin(a) * eye.hh;
897
+ const y = baseY * (1 - blink) + center.y * blink;
898
+ const yWithSquint = y + (isUpper ? -squintShift : squintShift * 0.5);
899
+ const z = center.z + 0.018 + Math.sin(a) * 0.012;
900
+ pts.push(V(x, yWithSquint, z));
901
+ }
902
+ return pts;
903
+ }
904
+
905
+ const browData = [
906
+ { side: 'L', uv: [0.27, 0.27] },
907
+ { side: 'R', uv: [0.73, 0.27] },
908
+ ];
909
+ let browMeshes = [];
910
+ function browPath(brow) {
911
+ const center = deformedPoint(brow.uv[0], brow.uv[1]);
912
+ const sign = brow.side === 'L' ? -1 : 1;
913
+ const innerLift = state.browInnerUp * 0.085 - state.browDown * 0.05;
914
+ const outerLift = (state.browOuterUp >= 0 ? state.browOuterUp : 0) * 0.07 - state.browDown * 0.05;
915
+ const innerX = center.x + sign * (-0.10);
916
+ const midX = center.x;
917
+ const outerX = center.x + sign * 0.10;
918
+ const innerY = center.y + innerLift;
919
+ const midY = center.y + (innerLift + outerLift) * 0.5 + 0.005;
920
+ const outerY = center.y + outerLift - 0.005;
921
+ const z = center.z + 0.018;
922
+ return smoothPath([V(innerX, innerY, z), V(midX, midY, z + 0.01), V(outerX, outerY, z)], 12);
923
+ }
924
+
925
+ let noseBridgeMesh = null, noseLeftMesh = null, noseRightMesh = null;
926
+ function nosePaths() {
927
+ const flair = state.noseSneer * 0.025;
928
+ const top = deformedPoint(0.50, 0.40);
929
+ const tip = deformedPoint(0.50, 0.55);
930
+ const bridge = smoothPath([
931
+ V(top.x, top.y - 0.02, top.z + 0.02),
932
+ V(top.x - 0.005, (top.y + tip.y) * 0.5, (top.z + tip.z) * 0.5 + 0.05),
933
+ V(tip.x, tip.y + 0.03, tip.z + 0.05),
934
+ ], 14);
935
+ const baseY = tip.y + 0.01;
936
+ const leftN = smoothPath([
937
+ V(tip.x, baseY, tip.z + 0.05),
938
+ V(tip.x - 0.06 - flair, baseY - 0.03, tip.z + 0.02),
939
+ V(tip.x - 0.04, baseY - 0.05, tip.z + 0.005),
940
+ V(tip.x - 0.01, baseY - 0.02, tip.z + 0.03),
941
+ ], 10);
942
+ const rightN = smoothPath([
943
+ V(tip.x, baseY, tip.z + 0.05),
944
+ V(tip.x + 0.06 + flair, baseY - 0.03, tip.z + 0.02),
945
+ V(tip.x + 0.04, baseY - 0.05, tip.z + 0.005),
946
+ V(tip.x + 0.01, baseY - 0.02, tip.z + 0.03),
947
+ ], 10);
948
+ return { bridge, leftN, rightN };
949
+ }
950
+
951
+ function rebuildMinimalLines() {
952
+ if (mouthUpperMesh) { mouthUpperMesh.dispose(); mouthUpperMesh = null; }
953
+ if (mouthLowerMesh) { mouthLowerMesh.dispose(); mouthLowerMesh = null; }
954
+ for (const em of eyeMeshes) { em.upper.dispose(); em.lower.dispose(); }
955
+ eyeMeshes = [];
956
+ for (const bm of browMeshes) bm.mesh.dispose();
957
+ browMeshes = [];
958
+ if (noseBridgeMesh) { noseBridgeMesh.dispose(); noseBridgeMesh = null; }
959
+ if (noseLeftMesh) { noseLeftMesh.dispose(); noseLeftMesh = null; }
960
+ if (noseRightMesh) { noseRightMesh.dispose(); noseRightMesh = null; }
961
+ const { upper, lower } = mouthLipPaths();
962
+ mouthUpperMesh = makeTube('mouth_u', upper, 0.010);
963
+ mouthLowerMesh = makeTube('mouth_l', lower, 0.010);
964
+ for (const eye of eyeData) {
965
+ const u = makeTube('eye_' + eye.side + '_u', eyePath(eye, true), 0.0085);
966
+ const l = makeTube('eye_' + eye.side + '_l', eyePath(eye, false), 0.0085);
967
+ eyeMeshes.push({ eye, upper: u, lower: l });
968
+ }
969
+ for (const brow of browData) {
970
+ const m = makeTube('brow_' + brow.side, browPath(brow), 0.011);
971
+ m.material = browMat;
972
+ browMeshes.push({ brow, mesh: m });
973
+ }
974
+ const np = nosePaths();
975
+ noseBridgeMesh = makeTube('nose_b', np.bridge, 0.009);
976
+ noseLeftMesh = makeTube('nose_l', np.leftN, 0.0085);
977
+ noseRightMesh = makeTube('nose_r', np.rightN, 0.0085);
978
+ applyMinimalVisibility();
979
+ }
980
+
981
+ function updateMinimal() {
982
+ if (!mouthUpperMesh) return;
983
+ const mp = mouthLipPaths();
984
+ makeTube('', mp.upper, 0.010, mouthUpperMesh);
985
+ makeTube('', mp.lower, 0.010, mouthLowerMesh);
986
+ for (const em of eyeMeshes) {
987
+ makeTube('', eyePath(em.eye, true), 0.0085, em.upper);
988
+ makeTube('', eyePath(em.eye, false), 0.0085, em.lower);
989
+ }
990
+ for (const bm of browMeshes) makeTube('', browPath(bm.brow), 0.011, bm.mesh);
991
+ const np = nosePaths();
992
+ makeTube('', np.bridge, 0.009, noseBridgeMesh);
993
+ makeTube('', np.leftN, 0.0085, noseLeftMesh);
994
+ makeTube('', np.rightN, 0.0085, noseRightMesh);
995
+ }
996
+
997
+ /* ── per-frame face update ── */
998
+ const _stateRawSnap = {};
999
+ function updateFace() {
1000
+ if (!mesh) return;
1001
+ // gain sandwich
1002
+ for (let i = 0; i < CHANNEL_NAMES.length; i++) {
1003
+ const ch = CHANNEL_NAMES[i];
1004
+ _stateRawSnap[ch] = state[ch];
1005
+ state[ch] = state[ch] * (channelGains[ch] || 1);
1006
+ }
1007
+ for (let i = 0; i < _dispBuf.length; i++) {
1008
+ _dispBuf[i].x = _dispBuf[i].y = _dispBuf[i].z = 0;
1009
+ }
1010
+ computeMorphs(_dispBuf);
1011
+ if (config.reactivity > 0) couple(_dispBuf, config.reactivity);
1012
+ applyFeatureScales(_dispBuf);
1013
+ applyJawExtension(_dispBuf);
1014
+ applyMouthGrow(_dispBuf);
1015
+ applyMouthAnchors(_dispBuf);
1016
+ applyEyeAnchors(_dispBuf);
1017
+ // write final positions
1018
+ for (let i = 0; i < baseVertices.length; i++) {
1019
+ _posBuf[3*i ] = baseVertices[i].x + _dispBuf[i].x;
1020
+ _posBuf[3*i+1] = baseVertices[i].y + _dispBuf[i].y;
1021
+ _posBuf[3*i+2] = baseVertices[i].z + _dispBuf[i].z;
1022
+ }
1023
+ mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, _posBuf);
1024
+ // depth fade colors
1025
+ if (config.depthFade > 0.001) {
1026
+ const zRange = (_zMax - _zMin) || 1, f = config.depthFade;
1027
+ for (let i = 0; i < baseVertices.length; i++) {
1028
+ const z = _posBuf[3*i + 2];
1029
+ const t = Math.max(0, Math.min(1, (_zMax - z) / zRange)) * f;
1030
+ _colBuf[4*i ] = _baseRGB[0] * (1 - t) + _fadeRGB[0] * t;
1031
+ _colBuf[4*i+1] = _baseRGB[1] * (1 - t) + _fadeRGB[1] * t;
1032
+ _colBuf[4*i+2] = _baseRGB[2] * (1 - t) + _fadeRGB[2] * t;
1033
+ _colBuf[4*i+3] = 1;
1034
+ }
1035
+ mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, _colBuf);
1036
+ } else if (_dirtyBaseColor) {
1037
+ for (let i = 0; i < baseVertices.length; i++) {
1038
+ _colBuf[4*i ] = _baseRGB[0];
1039
+ _colBuf[4*i+1] = _baseRGB[1];
1040
+ _colBuf[4*i+2] = _baseRGB[2];
1041
+ _colBuf[4*i+3] = 1;
1042
+ }
1043
+ mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, _colBuf);
1044
+ _dirtyBaseColor = false;
1045
+ }
1046
+ if (config.mode === 'edges' || config.mode === 'shaded') {
1047
+ BABYLON.VertexData.ComputeNormals(_posBuf, triIndices, _normBuf);
1048
+ mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, _normBuf);
1049
+ }
1050
+ updatePupils();
1051
+ if (config.minimal) updateMinimal();
1052
+ // head pose drives parent
1053
+ faceRoot.rotation.x = state.headRotateX * 0.35;
1054
+ faceRoot.rotation.y = state.headRotateY * 0.50;
1055
+ faceRoot.rotation.z = state.headRotateZ * 0.30;
1056
+ // restore
1057
+ for (let i = 0; i < CHANNEL_NAMES.length; i++) state[CHANNEL_NAMES[i]] = _stateRawSnap[CHANNEL_NAMES[i]];
1058
+ }
1059
+
1060
+ /* ── channel smoothing + mood blend + idle ── */
1061
+ function smoothChannels(dt) {
1062
+ for (const ch of CHANNEL_NAMES) {
1063
+ if (manualLock[ch]) { state[ch] = stateTarget[ch]; continue; }
1064
+ const k = SMOOTH[ch] || SMOOTH.default;
1065
+ const a = 1 - Math.exp(-k * dt * 30);
1066
+ state[ch] = state[ch] + (stateTarget[ch] - state[ch]) * a;
1067
+ }
1068
+ }
1069
+
1070
+ function updateMoodBlend(dt) {
1071
+ const T = Math.max(0.05, config.moodTransitionTime);
1072
+ const halflife = T / 4;
1073
+ const a = 1 - Math.pow(0.5, dt / halflife);
1074
+ for (const m of MOOD_NAMES) {
1075
+ moodCurrentWeights[m] += (moodTargetWeights[m] - moodCurrentWeights[m]) * a;
1076
+ }
1077
+ for (const ch of MOOD_CHANNELS) {
1078
+ let target = 0;
1079
+ for (const m of MOOD_NAMES) target += (MOODS[m][ch] || 0) * moodCurrentWeights[m];
1080
+ stateTarget[ch] = target;
1081
+ }
1082
+ }
1083
+
1084
+ /* ── idle micro-animations: blinks + saccades + head bob ── */
1085
+ let _nextBlink = 1.5 + Math.random() * 3;
1086
+ let _blinkAccum = 0;
1087
+ let _nextSaccade = 0.8 + Math.random() * 2;
1088
+ let _saccadeAccum = 0;
1089
+ let _saccTargetH = 0, _saccTargetV = 0;
1090
+ let _bobT = 0;
1091
+ function idleAnimate(dt) {
1092
+ // blinks
1093
+ _blinkAccum += dt;
1094
+ if (_blinkAccum > _nextBlink && !manualLock.eyeBlinkLeft && !manualLock.eyeBlinkRight) {
1095
+ // start a quick blink: target=1, then return to 0
1096
+ stateTarget.eyeBlinkLeft = 1;
1097
+ stateTarget.eyeBlinkRight = 1;
1098
+ setTimeout(() => {
1099
+ stateTarget.eyeBlinkLeft = moodCurrentWeights.sleep > 0.5 ? 1 : 0;
1100
+ stateTarget.eyeBlinkRight = moodCurrentWeights.sleep > 0.5 ? 1 : 0;
1101
+ }, 110);
1102
+ _blinkAccum = 0;
1103
+ _nextBlink = 1.5 + Math.random() * 3.5;
1104
+ }
1105
+ // micro-saccades
1106
+ _saccadeAccum += dt;
1107
+ if (_saccadeAccum > _nextSaccade && !manualLock.eyeLookH) {
1108
+ _saccTargetH = (Math.random() - 0.5) * 0.6;
1109
+ _saccTargetV = (Math.random() - 0.5) * 0.4;
1110
+ _saccadeAccum = 0;
1111
+ _nextSaccade = 0.7 + Math.random() * 2.5;
1112
+ }
1113
+ stateTarget.eyeLookH = _saccTargetH;
1114
+ stateTarget.eyeLookV = _saccTargetV;
1115
+ // head bob — gentle sway
1116
+ _bobT += dt;
1117
+ stateTarget.headRotateX = Math.sin(_bobT * 0.27) * 0.04;
1118
+ stateTarget.headRotateY = Math.sin(_bobT * 0.19) * 0.06;
1119
+ stateTarget.headRotateZ = Math.sin(_bobT * 0.11) * 0.03;
1120
+ }
1121
+
1122
+ /* ── audio analysis for live lip-sync ── */
1123
+ let audioCtx = null;
1124
+ let audioBuffer = null;
1125
+ let audioSource = null;
1126
+ let analyser = null;
1127
+ let audioStartCtxTime = 0;
1128
+ let pausedAt = 0;
1129
+ let isPlayingFlag = false;
1130
+ let audioFreqData = null;
1131
+
1132
+ function ensureAudioCtx() {
1133
+ if (!audioCtx) {
1134
+ audioCtx = new (window.AudioContext || window.webkitAudioContext)();
1135
+ }
1136
+ // Some browsers start AudioContext suspended until a user gesture
1137
+ if (audioCtx.state === 'suspended') audioCtx.resume();
1138
+ }
1139
+
1140
+ async function loadAudio(fileOrBlob) {
1141
+ ensureAudioCtx();
1142
+ const arrBuf = await fileOrBlob.arrayBuffer();
1143
+ audioBuffer = await audioCtx.decodeAudioData(arrBuf.slice(0));
1144
+ pausedAt = 0;
1145
+ }
1146
+
1147
+ function startPlayback(fromOffset) {
1148
+ if (!audioBuffer) return;
1149
+ ensureAudioCtx();
1150
+ audioSource = audioCtx.createBufferSource();
1151
+ audioSource.buffer = audioBuffer;
1152
+ audioSource.loop = !!config.loopAudio;
1153
+ analyser = audioCtx.createAnalyser();
1154
+ analyser.fftSize = 1024;
1155
+ analyser.smoothingTimeConstant = 0.4;
1156
+ audioFreqData = new Uint8Array(analyser.frequencyBinCount);
1157
+ audioSource.connect(analyser);
1158
+ analyser.connect(audioCtx.destination);
1159
+ audioStartCtxTime = audioCtx.currentTime - (fromOffset || 0);
1160
+ audioSource.start(0, fromOffset || 0);
1161
+ audioSource.onended = () => {
1162
+ if (!config.loopAudio) {
1163
+ isPlayingFlag = false;
1164
+ // dampen visemes back to silence
1165
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1166
+ stateTarget.viseme_sil = 1;
1167
+ stateTarget.jawOpen = 0;
1168
+ }
1169
+ };
1170
+ isPlayingFlag = true;
1171
+ }
1172
+
1173
+ function stopPlayback() {
1174
+ if (audioSource) {
1175
+ try { audioSource.stop(); } catch (_) {}
1176
+ try { audioSource.disconnect(); } catch (_) {}
1177
+ audioSource = null;
1178
+ }
1179
+ if (analyser) { try { analyser.disconnect(); } catch (_) {} analyser = null; }
1180
+ isPlayingFlag = false;
1181
+ }
1182
+
1183
+ function getPlaybackTime() {
1184
+ if (!audioCtx || !audioBuffer) return 0;
1185
+ if (isPlayingFlag) return audioCtx.currentTime - audioStartCtxTime;
1186
+ return pausedAt || 0;
1187
+ }
1188
+
1189
+ function freqEnergyHz(lo, hi) {
1190
+ if (!audioFreqData) return 0;
1191
+ const sr = audioCtx.sampleRate;
1192
+ const binHz = sr / 2 / audioFreqData.length;
1193
+ const i0 = Math.max(0, Math.floor(lo / binHz));
1194
+ const i1 = Math.min(audioFreqData.length - 1, Math.ceil(hi / binHz));
1195
+ let s = 0, n = 0;
1196
+ for (let i = i0; i <= i1; i++) { s += audioFreqData[i]; n++; }
1197
+ return n ? (s / n) / 255 : 0;
1198
+ }
1199
+
1200
+ function analyzeAudioFrame() {
1201
+ if (!analyser) return;
1202
+ analyser.getByteFrequencyData(audioFreqData);
1203
+ // overall amplitude
1204
+ const eLow = freqEnergyHz(200, 700);
1205
+ const eMid = freqEnergyHz(700, 2000);
1206
+ const eHi = freqEnergyHz(2000, 4000);
1207
+ const eSib = freqEnergyHz(4000, 8000);
1208
+ const eAir = freqEnergyHz(1500, 5000);
1209
+ const amp = Math.max(eLow, eMid, eHi, eSib);
1210
+ if (amp < 0.08) {
1211
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1212
+ stateTarget.viseme_sil = 1;
1213
+ stateTarget.jawOpen = 0;
1214
+ return;
1215
+ }
1216
+ stateTarget.viseme_sil = 0;
1217
+ stateTarget.jawOpen = amp * 0.7;
1218
+ // Reset all visemes
1219
+ for (const v of Object.keys(VISEME_PARAMS)) {
1220
+ if (v !== 'sil') stateTarget['viseme_' + v] = 0;
1221
+ }
1222
+ // Heuristic mapping
1223
+ if (eSib > 0.35 && eSib > eMid * 0.8) {
1224
+ stateTarget.viseme_SS = Math.min(1, eSib * 1.3);
1225
+ stateTarget.viseme_FF = Math.min(0.6, eAir * 1.2);
1226
+ }
1227
+ if (eLow > eMid && eLow > 0.18) {
1228
+ if (eHi > 0.25) {
1229
+ stateTarget.viseme_aa = Math.min(1, eLow * 1.2);
1230
+ } else {
1231
+ stateTarget.viseme_O = Math.min(1, eLow * 1.2);
1232
+ stateTarget.viseme_U = Math.min(0.7, eLow * 0.9);
1233
+ }
1234
+ } else if (eMid > 0.20) {
1235
+ if (eHi > eMid * 0.6) {
1236
+ stateTarget.viseme_I = Math.min(1, eHi * 1.4);
1237
+ stateTarget.viseme_E = Math.min(0.7, eMid * 1.1);
1238
+ } else {
1239
+ stateTarget.viseme_E = Math.min(1, eMid * 1.3);
1240
+ stateTarget.viseme_aa = Math.min(0.4, eLow * 0.9);
1241
+ }
1242
+ }
1243
+ }
1244
+
1245
+ /* ── color application ── */
1246
+ function applyLineColor(hex) {
1247
+ config.lineColor = hex;
1248
+ minimalMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
1249
+ }
1250
+ function applyPupilColor(hex) {
1251
+ config.pupilColor = hex;
1252
+ if (pupilMat) pupilMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
1253
+ }
1254
+ function applyBaseColor(hex) {
1255
+ config.baseColor = hex;
1256
+ _baseRGB = hex2rgb(hex);
1257
+ _dirtyBaseColor = true;
1258
+ wireMat.emissiveColor = new BABYLON.Color3(_baseRGB[0], _baseRGB[1], _baseRGB[2]);
1259
+ if (mesh && mesh._edgesRenderer) mesh.edgesColor = new BABYLON.Color4(_baseRGB[0], _baseRGB[1], _baseRGB[2], 1);
1260
+ }
1261
+ function applyFadeColor(hex) {
1262
+ config.fadeColor = hex;
1263
+ _fadeRGB = hex2rgb(hex);
1264
+ _dirtyBaseColor = true;
1265
+ }
1266
+ function applyIrisColor(hex) {
1267
+ config.irisColor = hex;
1268
+ if (irisMat) irisMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
1269
+ }
1270
+ function applyBrowColor(hex) {
1271
+ config.browColor = hex;
1272
+ browMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
1273
+ }
1274
+
1275
+ /* ── views ── */
1276
+ const VIEWS = {
1277
+ front: { alpha: -Math.PI/2, beta: Math.PI/2, radius: 4.4 },
1278
+ 'three-q':{ alpha: -Math.PI/2 - 0.6, beta: Math.PI/2 - 0.15, radius: 4.0 },
1279
+ profile: { alpha: 0, beta: Math.PI/2, radius: 4.6 },
1280
+ orbit: null,
1281
+ };
1282
+ let orbiting = false;
1283
+ function setView(view) {
1284
+ if (view === 'orbit') { orbiting = true; return; }
1285
+ orbiting = false;
1286
+ const v = VIEWS[view];
1287
+ if (!v) return;
1288
+ camera.alpha = v.alpha;
1289
+ camera.beta = v.beta;
1290
+ camera.radius = v.radius;
1291
+ }
1292
+
1293
+ function applyGlow() {
1294
+ glowLayer.intensity = config.glow ? 0.85 : 0;
1295
+ }
1296
+
1297
+ /* ── initial build ── */
1298
+ rebuildMesh();
1299
+ rebuildPupils();
1300
+ rebuildMinimalLines();
1301
+ applyBaseColor(config.baseColor);
1302
+ applyFadeColor(config.fadeColor);
1303
+ applyLineColor(config.lineColor);
1304
+ applyBrowColor(config.browColor);
1305
+ applyPupilColor(config.pupilColor);
1306
+ applyIrisColor(config.irisColor);
1307
+ applyGlow();
1308
+ setView(config.cameraView);
1309
+
1310
+ /* ── render loop ── */
1311
+ let lastT = performance.now();
1312
+ let _disposed = false;
1313
+ engine.runRenderLoop(() => {
1314
+ if (_disposed) return;
1315
+ const now = performance.now();
1316
+ const dt = Math.min(0.05, (now - lastT) / 1000);
1317
+ lastT = now;
1318
+ idleAnimate(dt);
1319
+ if (isPlayingFlag) analyzeAudioFrame();
1320
+ updateMoodBlend(dt);
1321
+ smoothChannels(dt);
1322
+ updateFace();
1323
+ if (orbiting) camera.alpha += dt * 0.3;
1324
+ scene.render();
1325
+ });
1326
+ const onResize = () => engine.resize();
1327
+ window.addEventListener('resize', onResize);
1328
+
1329
+ /* ── preset loader (consumes JSON saved by v010+ UI) ── */
1330
+ function loadPreset(p) {
1331
+ if (!p) return;
1332
+ const rc = p.renderConfig || {};
1333
+ let needRebuild = false;
1334
+ if (rc.meshCols !== undefined && rc.meshCols !== config.meshCols) needRebuild = true;
1335
+ if (rc.meshRows !== undefined && rc.meshRows !== config.meshRows) needRebuild = true;
1336
+ if (rc.fragment !== undefined && rc.fragment !== config.fragment) needRebuild = true;
1337
+ if (rc.mouthHole !== undefined && rc.mouthHole !== config.mouthHole) needRebuild = true;
1338
+ if (rc.eyeHoles !== undefined && rc.eyeHoles !== config.eyeHoles) needRebuild = true;
1339
+ if (rc.mouthHoleSize !== undefined && rc.mouthHoleSize !== config.mouthHoleSize) needRebuild = true;
1340
+ if (rc.eyeDepth !== undefined && rc.eyeDepth !== config.eyeDepth) needRebuild = true;
1341
+
1342
+ Object.assign(config, rc);
1343
+ if (p.lineColor) applyLineColor(p.lineColor);
1344
+ if (p.pupilColor) applyPupilColor(p.pupilColor);
1345
+ if (rc.baseColor) applyBaseColor(rc.baseColor);
1346
+ if (rc.fadeColor) applyFadeColor(rc.fadeColor);
1347
+ if (rc.lineColor) applyLineColor(rc.lineColor);
1348
+ if (rc.pupilColor) applyPupilColor(rc.pupilColor);
1349
+ if (rc.irisColor) applyIrisColor(rc.irisColor);
1350
+ if (rc.browColor) applyBrowColor(rc.browColor);
1351
+
1352
+ if (needRebuild) {
1353
+ rebuildMesh();
1354
+ rebuildMinimalLines();
1355
+ rebuildPupils();
1356
+ } else {
1357
+ // partial refreshes
1358
+ applyRenderMode();
1359
+ applyFaceFlip();
1360
+ applyMeshVisibility();
1361
+ applyMinimalVisibility();
1362
+ if (rc.lineThickness !== undefined) rebuildMinimalLines();
1363
+ if (rc.irisSize !== undefined) rebuildPupils();
1364
+ if (rc.lipVertAmp !== undefined || rc.lipPressForce !== undefined) identifyAnchorRings();
1365
+ }
1366
+ if (rc.glow !== undefined) applyGlow();
1367
+ // channel gains
1368
+ if (p.channelGains) {
1369
+ for (const ch of CHANNEL_NAMES) if (p.channelGains[ch] !== undefined) channelGains[ch] = p.channelGains[ch];
1370
+ }
1371
+ if (p.activeMood && MOODS[p.activeMood]) {
1372
+ activeMood = p.activeMood;
1373
+ for (const m of MOOD_NAMES) moodTargetWeights[m] = (m === activeMood) ? 1 : 0;
1374
+ }
1375
+ }
1376
+
1377
+ /* ── public API ── */
1378
+ return {
1379
+ loadAudio,
1380
+ play(fromOffset) {
1381
+ if (!audioBuffer) return;
1382
+ startPlayback(fromOffset !== undefined ? fromOffset : pausedAt);
1383
+ },
1384
+ pause() {
1385
+ if (!isPlayingFlag) return;
1386
+ pausedAt = getPlaybackTime();
1387
+ stopPlayback();
1388
+ },
1389
+ stop() {
1390
+ pausedAt = 0;
1391
+ stopPlayback();
1392
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1393
+ stateTarget.viseme_sil = 1;
1394
+ stateTarget.jawOpen = 0;
1395
+ },
1396
+ setLoop(b) { config.loopAudio = !!b; if (audioSource) audioSource.loop = !!b; },
1397
+ setMood(name) {
1398
+ if (!MOODS[name]) return;
1399
+ activeMood = name;
1400
+ for (const m of MOOD_NAMES) moodTargetWeights[m] = (m === name) ? 1 : 0;
1401
+ },
1402
+ setChannel(name, value) {
1403
+ if (!CHANNELS[name]) return;
1404
+ const r = CHANNELS[name].range;
1405
+ const v = Math.max(r[0], Math.min(r[1], value));
1406
+ stateTarget[name] = v; state[name] = v;
1407
+ manualLock[name] = true;
1408
+ clearTimeout(manualLock['_t_' + name]);
1409
+ manualLock['_t_' + name] = setTimeout(() => { manualLock[name] = false; }, 1200);
1410
+ },
1411
+ setView,
1412
+ loadPreset,
1413
+ /* lighter than loadPreset — apply a partial renderConfig without touching
1414
+ channelGains/activeMood. Intended for live UI controls (sliders, toggles,
1415
+ color pickers) where you change one field per call. */
1416
+ setRenderConfig(partial) { loadPreset({ renderConfig: partial }); },
1417
+ getRenderConfig() { return Object.assign({}, config); },
1418
+ /* live channel introspection — useful for editor channel meters that
1419
+ display the smoothed audio-driven values and gain knobs. */
1420
+ getChannel(name) { return state[name] !== undefined ? state[name] : 0; },
1421
+ getChannelTarget(name) { return stateTarget[name] !== undefined ? stateTarget[name] : 0; },
1422
+ getChannelGain(name) { return channelGains[name] !== undefined ? channelGains[name] : 1; },
1423
+ setChannelGain(name, gain) { if (CHANNELS[name]) channelGains[name] = gain; },
1424
+ getChannelNames() { return CHANNEL_NAMES.slice(); },
1425
+ getMoodNames() { return MOOD_NAMES.slice(); },
1426
+ isPlaying() { return isPlayingFlag; },
1427
+ getDuration() { return audioBuffer ? audioBuffer.duration : 0; },
1428
+ getPosition() { return getPlaybackTime(); },
1429
+ getActiveMood() { return activeMood; },
1430
+ dispose() {
1431
+ _disposed = true;
1432
+ try { stopPlayback(); } catch (_) {}
1433
+ if (audioCtx) { try { audioCtx.close(); } catch (_) {} audioCtx = null; }
1434
+ window.removeEventListener('resize', onResize);
1435
+ try { engine.stopRenderLoop(); } catch (_) {}
1436
+ try { scene.dispose(); } catch (_) {}
1437
+ try { engine.dispose(); } catch (_) {}
1438
+ },
1439
+ };
1440
+ }
1441
+
1442
+ /* ── exports ── */
1443
+ global.createWireface = createWireface;
1444
+ if (typeof module !== 'undefined' && module.exports) {
1445
+ module.exports = { createWireface };
1446
+ }
1447
+ })(typeof window !== 'undefined' ? window : globalThis);